<?php
/**
 * Restore Database from Backup
 * Restore a previously created backup file
 */

require_once '../../config/config.php';
require_once '../../includes/functions.php';

requireAdmin();

$pdo = getDB();
$error = '';
$success = '';
$backupDir = '../../backups/';
$backupFile = isset($_GET['file']) ? basename($_GET['file']) : '';
$filePath = $backupDir . $backupFile;

if (empty($backupFile) || !file_exists($filePath)) {
    header('Location: backup.php?error=Backup file not found');
    exit;
}

// Handle restore confirmation
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = "Security token validation failed.";
    } else {
        $confirm = $_POST['confirm'] ?? '';
        
        if ($confirm == 'RESTORE') {
            try {
                // Read backup file
                $sql = file_get_contents($filePath);
                
                // Split SQL into individual queries
                $queries = [];
                $currentQuery = '';
                $lines = explode("\n", $sql);
                
                foreach ($lines as $line) {
                    $line = trim($line);
                    if (empty($line) || strpos($line, '--') === 0) {
                        continue;
                    }
                    $currentQuery .= $line . "\n";
                    if (substr(rtrim($line), -1) == ';') {
                        $queries[] = trim($currentQuery);
                        $currentQuery = '';
                    }
                }
                
                // Execute queries in a transaction
                beginTransaction();
                
                foreach ($queries as $query) {
                    if (!empty($query)) {
                        $pdo->exec($query);
                    }
                }
                
                commitTransaction();
                $success = "Database restored successfully from: " . $backupFile;
                
            } catch (Exception $e) {
                rollbackTransaction();
                $error = "Restore failed: " . $e->getMessage();
            }
        } else {
            $error = "Please type RESTORE to confirm";
        }
    }
}

// Get file info
$fileSize = formatFileSize(filesize($filePath));
$fileDate = date('d-m-Y H:i:s', filemtime($filePath));
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Restore Backup - Admin Panel</title>
    <link href="../../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../../assets/vendor/fontawesome/css/all.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-8 mx-auto">
                <div class="card">
                    <div class="card-header bg-warning">
                        <h4 class="mb-0"><i class="fas fa-exclamation-triangle"></i> Restore Database</h4>
                    </div>
                    <div class="card-body">
                        <?php if ($success): ?>
                            <div class="alert alert-success">
                                <i class="fas fa-check-circle"></i> <?php echo $success; ?>
                                <br><br>
                                <a href="backup.php" class="btn btn-primary">Back to Backups</a>
                                <a href="../dashboard.php" class="btn btn-secondary">Go to Dashboard</a>
                            </div>
                        <?php elseif ($error): ?>
                            <div class="alert alert-danger"><?php echo $error; ?></div>
                            <a href="backup.php" class="btn btn-secondary">Back to Backups</a>
                        <?php else: ?>
                            <div class="alert alert-danger">
                                <strong>⚠️ WARNING!</strong><br>
                                Restoring a backup will overwrite ALL current database data!
                                <br><br>
                                This action cannot be undone.
                            </div>
                            
                            <div class="card mb-3">
                                <div class="card-header">Backup File Details</div>
                                <div class="card-body">
                                    <table class="table table-bordered">
                                        <tr><th>Filename:</th><td><?php echo $backupFile; ?></td></tr>
                                        <tr><th>Size:</th><td><?php echo $fileSize; ?></td></tr>
                                        <tr><th>Created:</th><td><?php echo $fileDate; ?></td></tr>
                                    </table>
                                </div>
                            </div>
                            
                            <form method="POST">
                                <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                                <div class="mb-3">
                                    <label>Type <strong>RESTORE</strong> to confirm:</label>
                                    <input type="text" name="confirm" class="form-control" placeholder="RESTORE" required>
                                </div>
                                <button type="submit" class="btn btn-danger">
                                    <i class="fas fa-undo"></i> Restore Database
                                </button>
                                <a href="backup.php" class="btn btn-secondary">Cancel</a>
                            </form>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>