<?php
/**
 * Rollback Render-Blocking Fix
 * 
 * This script restores the original header.view.php and footer.view.php
 * from the most recent backup.
 * 
 * Usage: php rollback_render_blocking_fix.php
 */

echo "=== Rollback Render-Blocking Fix ===\n\n";

// Find backup files
$files_to_restore = [
    'views/header.view.php',
    'views/footer.view.php'
];

$backup_pattern = '_backup_';
$backups_found = [];

foreach ($files_to_restore as $file) {
    $dir = dirname($file);
    $filename = basename($file);
    
    // Find all backup files for this file
    $pattern = $dir . '/' . $filename . $backup_pattern . '*';
    $matches = glob($pattern);
    
    if (!empty($matches)) {
        // Sort by modification time (newest first)
        usort($matches, function($a, $b) {
            return filemtime($b) - filemtime($a);
        });
        
        $backups_found[$file] = $matches[0];
    }
}

if (empty($backups_found)) {
    echo "ERROR: No backup files found!\n";
    echo "Looking for files matching pattern: *{$backup_pattern}*\n";
    exit(1);
}

echo "Found backup files:\n";
foreach ($backups_found as $original => $backup) {
    $backup_date = date('Y-m-d H:i:s', filemtime($backup));
    echo "  - $backup (created: $backup_date)\n";
}

// Auto-confirm if running from web or command line with no interaction
$auto_confirm = (php_sapi_name() !== 'cli' || isset($_GET['confirm']));

if (!$auto_confirm) {
    echo "\n";
    echo "Do you want to restore these backups? (yes/no): ";
    $handle = fopen("php://stdin", "r");
    $line = trim(fgets($handle));
    fclose($handle);

    if (strtolower($line) !== 'yes') {
        echo "Rollback cancelled.\n";
        exit(0);
    }
} else {
    echo "\nAuto-confirming rollback...\n";
}

echo "\nRestoring backups...\n";
foreach ($backups_found as $original => $backup) {
    if (copy($backup, $original)) {
        echo "  ✓ Restored: $original\n";
    } else {
        echo "  ✗ Failed to restore: $original\n";
        exit(1);
    }
}

echo "\n";
echo "=== SUCCESS ===\n";
echo "Original files have been restored!\n\n";
echo "Your site should now be using the original CSS/JS loading.\n";
echo "Backup files have been preserved in case you need them.\n\n";
?>
