<?php
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../includes/session_term_helper.php';

$pass = 0;
$fail = 0;

function check($label, $condition)
{
    global $pass, $fail;
    if ($condition) {
        echo "  PASS: $label\n";
        $pass++;
    } else {
        echo "  FAIL: $label\n";
        $fail++;
    }
}

// Test 1: Both present
$h = renderSessionTermBadges('2024/2025', 'First Term');
check('Both present - session badge', str_contains($h, 'badge-primary'));
check('Both present - term badge', str_contains($h, 'badge-success'));
check('Both present - no warning', !str_contains($h, 'badge-warning'));

// Test 2: Session only, no term
$h = renderSessionTermBadges('2024/2025', null);
check('No term - session badge present', str_contains($h, 'badge-primary'));
check('No term - warning badge present', str_contains($h, 'badge-warning'));
check('No term - no success badge', !str_contains($h, 'badge-success'));

// Test 3: Term only, no session
$h = renderSessionTermBadges(null, 'First Term');
check('No session - no primary badge', !str_contains($h, 'badge-primary'));
check('No session - term badge present', str_contains($h, 'badge-success'));

// Test 4: Both null
$h = renderSessionTermBadges(null, null);
check('Both null - no primary', !str_contains($h, 'badge-primary'));
check('Both null - warning present', str_contains($h, 'badge-warning'));

// Test 5: XSS in session
$h = renderSessionTermBadges('<script>alert(1)</script>', 'Term');
check('XSS session - escaped', str_contains($h, '&lt;script&gt;'));
check('XSS session - raw not present', !str_contains($h, '<script>'));

// Test 6: XSS in term
$h = renderSessionTermBadges('2024/2025', '<b>Term</b>');
check('XSS term - escaped', str_contains($h, '&lt;b&gt;'));
check('XSS term - raw not present', !str_contains($h, '<b>Term</b>'));

// Test 7: Empty string session
$h = renderSessionTermBadges('', 'First Term');
check('Empty session - no primary badge', !str_contains($h, 'badge-primary'));

// Test 8: Wrapper div always present
foreach ([['2024/2025', 'First Term'], [null, null], ['2024/2025', null], [null, 'First Term']] as $combo) {
    $h = renderSessionTermBadges($combo[0], $combo[1]);
    check('mt-1 wrapper present for ' . json_encode($combo), str_contains($h, '<div class="mt-1">'));
}

// Property 3: Mutual exclusivity
foreach ([null, '', 'First Term', 'Second Term'] as $term) {
    $h = renderSessionTermBadges('2024/2025', $term);
    $hasSuccess = str_contains($h, 'badge-success');
    $hasWarning = str_contains($h, 'badge-warning');
    check('Mutual exclusivity for term=' . json_encode($term), $hasSuccess xor $hasWarning);
}

echo "\n=== Results: $pass passed, $fail failed ===\n";
exit($fail > 0 ? 1 : 0);
