<?php
/**
 * Update All Admin Pages to Use New Sidebar and Footer
 * Run this script once to update all admin pages
 */

session_start();
require_once 'config/config.php';

// Simple admin check
if (!isset($_SESSION['user_id'])) {
    die('<h1>Access Denied</h1><p>Please <a href="login.php">login</a> first.</p>');
}

// Check if user is admin (role_id 1 or 2)
try {
    $db = getDB();
    $stmt = $db->prepare("SELECT role_id FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $user = $stmt->fetch();
    
    if (!$user || ($user['role_id'] != 1 && $user['role_id'] != 2)) {
        die('<h1>Access Denied</h1><p>Admin access required.</p>');
    }
} catch (Exception $e) {
    die('<h1>Database Error</h1><p>' . $e->getMessage() . '</p>');
}

$updated = [];
$errors = [];
$skipped = [];

?>
<!DOCTYPE html>
<html>
<head>
    <title>Update Admin Pages</title>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'>
</head>
<body>
<div class='container mt-5'>
    <h1>Updating Admin Pages</h1>
    <p class='text-info'>This script will update all admin pages to use the new sidebar and footer.</p>
    
    <div class='alert alert-warning'>
        <strong>⚠️ Important:</strong> This will modify your admin PHP files. Make sure you have backups!
    </div>
    
    <div class='progress mb-3'>
        <div class='progress-bar progress-bar-striped progress-bar-animated' role='progressbar' style='width: 0%' id='progress'></div>
    </div>
    
    <div id='output'>
<?php

// Get all PHP files in admin directory
$adminFiles = glob('admin/*.php');
$total = count($adminFiles);
$current = 0;

echo "<p class='text-info'>Found {$total} admin files to process...</p>";

foreach ($adminFiles as $file) {
    $current++;
    $progress = ($current / $total) * 100;
    $filename = basename($file);
    
    echo "<script>document.getElementById('progress').style.width = '{$progress}%';</script>";
    echo "<p>Processing {$current}/{$total}: <strong>{$filename}</strong>...</p>";
    flush();
    
    // Skip certain files
    if (in_array($filename, ['sidebar.php', 'sidebar-new.php', 'header-bar.php'])) {
        echo "<p class='text-warning'>⚠️ Skipped: {$filename} (system file)</p>";
        $skipped[] = $filename;
        continue;
    }
    
    try {
        $content = file_get_contents($file);
        $originalContent = $content;
        $modified = false;
        
        // Replace old sidebar include with new one
        if (strpos($content, "include 'sidebar.php'") !== false) {
            $content = str_replace("include 'sidebar.php'", "include 'sidebar-new.php'", $content);
            $modified = true;
            echo "<p class='text-success'>  ✓ Updated sidebar include</p>";
        } elseif (strpos($content, 'include "sidebar.php"') !== false) {
            $content = str_replace('include "sidebar.php"', 'include "sidebar-new.php"', $content);
            $modified = true;
            echo "<p class='text-success'>  ✓ Updated sidebar include</p>";
        }
        
        // Check if footer is already included
        $hasFooter = (strpos($content, "include '../templates/footer.php'") !== false) ||
                     (strpos($content, 'include "../templates/footer.php"') !== false) ||
                     (strpos($content, "include '../templates/admin-footer.php'") !== false) ||
                     (strpos($content, 'include "../templates/admin-footer.php"') !== false);
        
        // Add admin footer before closing body tag if not present
        if (!$hasFooter && strpos($content, '</body>') !== false) {
            $content = str_replace(
                '</body>',
                "<?php include '../templates/admin-footer.php'; ?>\n</body>",
                $content
            );
            $modified = true;
            echo "<p class='text-success'>  ✓ Added admin footer</p>";
        } elseif ($hasFooter) {
            // Replace regular footer with admin footer
            $content = str_replace(
                "include '../templates/footer.php'",
                "include '../templates/admin-footer.php'",
                $content
            );
            $content = str_replace(
                'include "../templates/footer.php"',
                'include "../templates/admin-footer.php"',
                $content
            );
            if ($content !== $originalContent) {
                $modified = true;
                echo "<p class='text-success'>  ✓ Replaced footer with admin footer</p>";
            }
        }
        
        // Save if modified
        if ($modified) {
            file_put_contents($file, $content);
            echo "<p class='text-success'>✓ Updated: {$filename}</p>";
            $updated[] = $filename;
        } else {
            echo "<p class='text-muted'>  No changes needed for {$filename}</p>";
            $skipped[] = $filename;
        }
        
    } catch (Exception $e) {
        echo "<p class='text-danger'>✗ Error processing {$filename}: " . $e->getMessage() . "</p>";
        $errors[] = $filename . ': ' . $e->getMessage();
    }
    
    usleep(100000); // Small delay for visual effect
}

echo "<hr>";
echo "<h2 class='text-success'>✓ Update Complete!</h2>";
echo "<div class='row'>";
echo "<div class='col-md-4'>";
echo "<div class='card border-success'>";
echo "<div class='card-body'>";
echo "<h5 class='card-title text-success'><i class='fas fa-check-circle'></i> Updated</h5>";
echo "<p class='card-text display-4'>" . count($updated) . "</p>";
echo "</div></div></div>";

echo "<div class='col-md-4'>";
echo "<div class='card border-warning'>";
echo "<div class='card-body'>";
echo "<h5 class='card-title text-warning'><i class='fas fa-exclamation-circle'></i> Skipped</h5>";
echo "<p class='card-text display-4'>" . count($skipped) . "</p>";
echo "</div></div></div>";

echo "<div class='col-md-4'>";
echo "<div class='card border-danger'>";
echo "<div class='card-body'>";
echo "<h5 class='card-title text-danger'><i class='fas fa-times-circle'></i> Errors</h5>";
echo "<p class='card-text display-4'>" . count($errors) . "</p>";
echo "</div></div></div>";
echo "</div>";

if (!empty($updated)) {
    echo "<div class='alert alert-success mt-4'>";
    echo "<h4>✓ Successfully Updated Files:</h4>";
    echo "<ul>";
    foreach ($updated as $file) {
        echo "<li>{$file}</li>";
    }
    echo "</ul>";
    echo "</div>";
}

if (!empty($skipped)) {
    echo "<div class='alert alert-warning mt-4'>";
    echo "<h4>⚠️ Skipped Files:</h4>";
    echo "<ul>";
    foreach ($skipped as $file) {
        echo "<li>{$file}</li>";
    }
    echo "</ul>";
    echo "</div>";
}

if (!empty($errors)) {
    echo "<div class='alert alert-danger mt-4'>";
    echo "<h4>✗ Errors:</h4>";
    echo "<ul>";
    foreach ($errors as $error) {
        echo "<li>{$error}</li>";
    }
    echo "</ul>";
    echo "</div>";
}

echo "<div class='alert alert-info mt-4'>";
echo "<h4>Next Steps:</h4>";
echo "<ol>";
echo "<li>Test the admin pages to ensure everything works correctly</li>";
echo "<li>Check the mobile menu on different devices</li>";
echo "<li>Verify the footer displays properly on all pages</li>";
echo "<li>If everything looks good, you can delete the old <code>admin/sidebar.php</code> file</li>";
echo "<li>Visit <a href='admin/dashboard.php'>Admin Dashboard</a> to see the changes</li>";
echo "</ol>";
echo "</div>";

?>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</body>
</html>
