<?php
require_once 'init.php';

// Suraksha jaanch: Sirf Admin hi is page ko access kar sakta hai.
if (!userHasRole(['Admin'])) {
    header("Location: dashboard.php");
    exit();
}

// --- RESTORE LOGIC ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['start_restore'])) {
    $backup_date = $_POST['backup_date'];
    $confirmation_text = $_POST['confirmation_text'];
    $admin_password = $_POST['admin_password'];
    $admin_id = $_SESSION['user_id'];

    // Step 1: Confirmation text check
    if ($confirmation_text !== 'RESTORE') {
        $_SESSION['message'] = 'Restore confirmation text did not match. Process aborted.';
        $_SESSION['message_type'] = 'error';
        header("Location: restore_backup.php");
        exit();
    }

    // Step 2: Admin password verification
    $stmt = $conn->prepare("SELECT password FROM users WHERE id = ?");
    $stmt->bind_param("i", $admin_id);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    $hashed_password = $result['password'];
    $stmt->close();

    if (!password_verify($admin_password, $hashed_password)) {
        $_SESSION['message'] = 'Incorrect admin password. Restore process aborted for security reasons.';
        $_SESSION['message_type'] = 'error';
        header("Location: restore_backup.php");
        exit();
    }

    // Step 3: Backup files check
    $backup_dir = '/home6/cybsoul/backups';
    $db_file = "{$backup_dir}/db_backup_{$backup_date}.sql.gz";
    $files_file = "{$backup_dir}/files_backup_{$backup_date}.zip";

    if (!file_exists($db_file) || !file_exists($files_file)) {
        $_SESSION['message'] = "Backup files for {$backup_date} not found. Restore failed.";
        $_SESSION['message_type'] = 'error';
        header("Location: restore_backup.php");
        exit();
    }

    // Step 4: Start restore process in background
    $restore_script = __DIR__ . '/run_restore.php';
    $command = "/usr/local/bin/php {$restore_script} " . escapeshellarg($db_file) . " " . escapeshellarg($files_file) . " > /dev/null 2>&1 &";
    
    exec($command);

    $_SESSION['message'] = "Restore process has been started for backup date {$backup_date}. It may take several minutes for the changes to reflect. The system might be temporarily unavailable.";
    $_SESSION['message_type'] = 'success';
    header("Location: restore_backup.php");
    exit();
}


// --- PAGE DISPLAY LOGIC ---
$backup_dir = '/home6/cybsoul/backups';
$backup_files = glob($backup_dir . '/*.{sql.gz,zip}', GLOB_BRACE);
$backups = [];
foreach ($backup_files as $file) {
    preg_match('/(db|files)_backup_(\d{4}-\d{2}-\d{2})\.(sql\.gz|zip)/', basename($file), $matches);
    if ($matches) {
        $date = $matches[2];
        $type = $matches[1];
        $backups[$date][$type] = $file;
    }
}
$valid_backups = array_filter($backups, function($files) {
    return isset($files['db']) && isset($files['files']);
});
krsort($valid_backups);

require_once 'header.php';
?>
<title>Restore from Backup - Digify OS</title>

<div class="p-6 md:p-10" x-data="{ restoreModalOpen: false, selectedBackupDate: '' }">
    <header class="mb-6">
        <h2 class="text-2xl font-bold text-gray-800">Restore from Backup</h2>
        <p class="text-gray-600">Restore your application to a previous state using an available backup point.</p>
    </header>

    <?php if (isset($_SESSION['message'])): ?>
    <div class="mb-4 p-4 rounded-lg <?php echo ($_SESSION['message_type'] == 'success') ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
        <?php echo htmlspecialchars($_SESSION['message']); unset($_SESSION['message'], $_SESSION['message_type']); ?>
    </div>
    <?php endif; ?>

    <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 mb-6" role="alert">
        <p class="font-bold">Warning!</p>
        <p>Restoring a backup is a destructive action. It will completely overwrite your current files and database with the selected backup version. This process cannot be undone.</p>
    </div>

    <div class="bg-white p-8 rounded-lg shadow-md">
        <h3 class="text-lg font-semibold text-gray-700 mb-4">Available Backup Points</h3>
        <div class="overflow-x-auto">
            <table class="min-w-full">
                <thead class="bg-gray-100">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Backup Date</th>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Actions</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if (empty($valid_backups)): ?>
                        <tr><td colspan="2" class="px-6 py-10 text-center text-gray-500">No complete backup points found.</td></tr>
                    <?php else: ?>
                        <?php foreach ($valid_backups as $date => $files): ?>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"><?php echo date("F j, Y", strtotime($date)); ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                    <button @click="restoreModalOpen = true; selectedBackupDate = '<?php echo $date; ?>'" class="px-4 py-2 bg-red-600 text-white font-semibold rounded-lg shadow-md hover:bg-red-700">Restore</button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- Restore Confirmation Modal -->
    <div x-show="restoreModalOpen" x-transition class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center z-50" @keydown.escape.window="restoreModalOpen = false" style="display: none;">
        <div class="bg-white rounded-lg shadow-xl p-8 w-full max-w-lg" @click.away="restoreModalOpen = false">
            <h3 class="text-xl font-semibold mb-4 text-red-700">Confirm Restore</h3>
            <p class="text-gray-600">You are about to restore the system to the state it was on <b x-text="selectedBackupDate"></b>. All data and files created after this date will be permanently lost.</p>
            
            <form method="POST" action="restore_backup.php" class="mt-6 space-y-4">
                <input type="hidden" name="backup_date" :value="selectedBackupDate">
                
                <div>
                    <label class="block text-sm font-medium text-gray-700">To proceed, please type <b class="text-red-600">RESTORE</b> in the box below.</label>
                    <input type="text" name="confirmation_text" required class="w-full border-gray-300 rounded-md mt-1" placeholder="Type RESTORE to confirm">
                </div>
                
                <div>
                    <label for="admin_password" class="block text-sm font-medium text-gray-700">Enter Your Admin Password</label>
                    <input type="password" name="admin_password" id="admin_password" required class="w-full border-gray-300 rounded-md mt-1" placeholder="Enter your password to confirm">
                </div>

                <div class="flex justify-end pt-4 border-t mt-6">
                    <button type="button" @click="restoreModalOpen = false" class="px-4 py-2 border rounded-md mr-2">Cancel</button>
                    <button type="submit" name="start_restore" class="px-4 py-2 bg-red-600 text-white rounded-md font-semibold">I understand, Restore Now</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php
require_once 'footer.php';
?>

