<?php
// /public_html/admin/backups.php
session_start();
require '../config/db_connect.php';

// 1. Admin Auth
if (!isset($_SESSION['user_id'])) { header("Location: ../login.php"); exit(); }
$check = $conn->query("SELECT role FROM users WHERE id = {$_SESSION['user_id']}")->fetch_assoc();
if (($check['role'] ?? '') !== 'admin') { die("Access Denied"); }

$msg = "";

// 2. HANDLE BACKUP GENERATION
if (isset($_POST['create_backup'])) {
    $tables = [];
    $result = $conn->query("SHOW TABLES");
    while($row = $result->fetch_row()) { $tables[] = $row[0]; }

    $sqlScript = "";
    foreach($tables as $table) {
        $result = $conn->query("SELECT * FROM $table");
        $num_fields = $result->field_count;

        $sqlScript .= "DROP TABLE IF EXISTS $table;";
        $row2 = $conn->query("SHOW CREATE TABLE $table")->fetch_row();
        $sqlScript .= "\n\n" . $row2[1] . ";\n\n";

        for ($i = 0; $i < $num_fields; $i++) {
            while($row = $result->fetch_row()) {
                $sqlScript .= "INSERT INTO $table VALUES(";
                for($j=0; $j < $num_fields; $j++) {
                    $row[$j] = $row[$j];
                    if (isset($row[$j])) { $sqlScript .= '"' . $conn->real_escape_string($row[$j]) . '"'; } else { $sqlScript .= '""'; }
                    if ($j < ($num_fields - 1)) { $sqlScript .= ','; }
                }
                $sqlScript .= ");\n";
            }
        }
        $sqlScript .= "\n";
    }

    // Save File
    $backup_dir = '../backups/';
    if (!file_exists($backup_dir)) { mkdir($backup_dir, 0777, true); }
    
    $filename = 'db_backup_' . date('Y-m-d_H-i-s') . '.sql';
    $handle = fopen($backup_dir . $filename, 'w+');
    fwrite($handle, $sqlScript);
    fclose($handle);

    $msg = "Backup created successfully: <strong>$filename</strong>";
}

// 3. HANDLE DELETE
if (isset($_GET['delete'])) {
    $file = '../backups/' . basename($_GET['delete']);
    if (file_exists($file)) { unlink($file); }
    header("Location: backups.php");
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Database Backups - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
</head>
<body class="bg-light">
    
    <?php include 'includes/navbar.php'; ?>

    <div class="container mt-5">
        <h2 class="mb-4">Database Backups</h2>
        
        <?php if(!empty($msg)) echo "<div class='alert alert-success'>$msg</div>"; ?>

        <div class="card shadow-sm mb-4">
            <div class="card-body">
                <h5 class="card-title">Create New Backup</h5>
                <p class="text-muted">This will export all Users, QR Codes, Settings, and Analytics into a single SQL file.</p>
                <form method="POST">
                    <button type="submit" name="create_backup" class="btn btn-primary">
                        <i class="bi bi-cloud-download"></i> Generate Backup Now
                    </button>
                </form>
            </div>
        </div>

        <div class="card shadow-sm">
            <div class="card-header bg-dark text-white">Available Backups</div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0 align-middle">
                        <thead><tr><th>Filename</th><th>Size</th><th>Date</th><th>Actions</th></tr></thead>
                        <tbody>
                            <?php
                            $files = glob('../backups/*.sql');
                            if (count($files) > 0) {
                                // Sort by newest first
                                usort($files, function($a, $b) { return filemtime($b) - filemtime($a); });
                                
                                foreach($files as $file) {
                                    $filename = basename($file);
                                    $size = round(filesize($file) / 1024, 2) . ' KB';
                                    $date = date('M d, Y H:i:s', filemtime($file));
                                    echo "<tr>
                                        <td>$filename</td>
                                        <td>$size</td>
                                        <td>$date</td>
                                        <td>
                                            <a href='download_backup.php?file=$filename' class='btn btn-sm btn-success'>Download</a>
                                            <a href='?delete=$filename' class='btn btn-sm btn-danger' onclick=\"return confirm('Delete this backup?');\">Delete</a>
                                        </td>
                                    </tr>";
                                }
                            } else {
                                echo "<tr><td colspan='4' class='text-center py-4 text-muted'>No backups found.</td></tr>";
                            }
                            ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <?php include 'includes/footer.php'; ?>