<?php
/**
 * BOM & Pre-PHP Whitespace Stripper v3 - includes logout.php
 * Upload to server root and visit /fix_bom3.php
 */
ini_set('display_errors', 1);
error_reporting(E_ALL);

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

$baseDir = __DIR__;

echo "<pre>";
echo "=== FIXING FILES (v3) ===\n\n";

foreach ($filesToFix as $file) {
    $path = $baseDir . '/' . $file;
    if (!file_exists($path)) {
        echo "MISSING: $file\n";
        continue;
    }

    $content = file_get_contents($path);
    $original = $content;

    // Strip BOM if present
    $bom = "\xEF\xBB\xBF";
    if (substr($content, 0, 3) === $bom) {
        $content = substr($content, 3);
        echo "FIXED BOM: $file\n";
    }

    // Strip ANY whitespace/characters before <?php
    $pos = strpos($content, '<?php');
    if ($pos !== false && $pos > 0) {
        $before = substr($content, 0, $pos);
        $bytes = strlen($before);
        $content = substr($content, $pos);
        echo "FIXED: $file (removed $bytes bytes before <?php)\n";
    } elseif ($pos === false) {
        echo "WARNING: $file has no <?php tag!\n";
    } else {
        echo "OK: $file (clean start)\n";
    }

    // Write back if changed
    if ($content !== $original) {
        file_put_contents($path, $content);
    }
}

echo "\n=== DONE ===\n";
echo "Now test logout from dashboard.\n";
echo "</pre>";
