<?php
/**
 * BOM Stripper - Upload to server root and visit /fix_bom.php
 * This fixes "headers already sent" by removing invisible BOM characters
 */
ini_set('display_errors', 1);
error_reporting(E_ALL);

$filesToFix = [
    'config/database.php',
    'lms/login.php',
    'lms/dashboard.php',
    'classes/User.php',
    'lms/session_test.php',
];

$bom = "\xEF\xBB\xBF";
$baseDir = __DIR__;

echo "<pre>";
echo "=== BOM FIXER ===\n\n";

foreach ($filesToFix as $file) {
    $path = $baseDir . '/' . $file;
    if (!file_exists($path)) {
        echo "MISSING: $file\n";
        continue;
    }
    
    $content = file_get_contents($path);
    $hasBom = substr($content, 0, 3) === $bom;
    
    if ($hasBom) {
        $newContent = substr($content, 3);
        file_put_contents($path, $newContent);
        echo "FIXED: $file (BOM removed)\n";
    } else {
        echo "OK: $file (no BOM)\n";
    }
    
    // Also check for whitespace/newlines before <?php
    if (preg_match('/^(\s+|\xEF\xBB\xBF)*<\?php/', $content, $m)) {
        $prefix = $m[0];
        $beforePhp = str_replace('<?php', '', $prefix);
        if (strlen($beforePhp) > 0) {
            echo "  WARNING: " . strlen($beforePhp) . " bytes before <?php\n";
        }
    }
}

echo "\n=== SESSION TEST ===\n";

// Test actual session after fix
ob_clean();
ob_start();

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$_SESSION['fix_test'] = time();
$sid = session_id();

$cookies = session_get_cookie_params();
echo "Session ID: $sid\n";
echo "Cookie domain: " . ($cookies['domain'] ?: '(empty)') . "\n";
echo "Cookie path: " . ($cookies['path'] ?: '(empty)') . "\n";
echo "Cookie secure: " . ($cookies['secure'] ? 'true' : 'false') . "\n";
echo "Cookie samesite: " . ($cookies['samesite'] ?: '(empty)') . "\n";

// Send headers and flush
ob_end_flush();

echo "\n=== HEADERS SENT ===\n";
$headers = headers_list();
$hasCookie = false;
foreach ($headers as $h) {
    if (stripos($h, 'Set-Cookie') !== false) {
        echo $h . "\n";
        $hasCookie = true;
    }
}
if (!$hasCookie) {
    echo "NO Set-Cookie header found! Session cookie was NOT sent.\n";
}

echo "\nDone. If 'NO Set-Cookie header found' appears above, the session is still broken.\n";
echo "</pre>";
