<?php
require_once '../config/db.php';
require_once '../config/auth.php';
require_once '../config/functions.php';
requireAdmin();

$page_title = 'Database Backup';
$msg = '';

$backup_dir = $_SERVER['DOCUMENT_ROOT'] . '/lostfound_relink/backups/';
if (!is_dir($backup_dir)) mkdir($backup_dir, 0755, true);

// --- Download / Create Backup ---
if (isset($_POST['create_backup'])) {
    $filename = 'backup_' . date('Y-m-d_H-i-s') . '.sql';
    $filepath = $backup_dir . $filename;

    $tables = [];
    $res = $conn->query("SHOW TABLES");
    while ($row = $res->fetch_row()) $tables[] = $row[0];

    $sql = "-- RELINK Database Backup\n-- Generated: " . date('Y-m-d H:i:s') . "\n-- Database: " . DB_NAME . "\n\nSET FOREIGN_KEY_CHECKS=0;\n\n";

    foreach ($tables as $table) {
        $sql .= "DROP TABLE IF EXISTS `$table`;\n";
        $create = $conn->query("SHOW CREATE TABLE `$table`")->fetch_row();
        $sql .= $create[1] . ";\n\n";

        $rows = $conn->query("SELECT * FROM `$table`");
        while ($row = $rows->fetch_assoc()) {
            $vals = array_map(fn($v) => $v === null ? 'NULL' : "'" . $conn->real_escape_string($v) . "'", array_values($row));
            $sql .= "INSERT INTO `$table` VALUES (" . implode(', ', $vals) . ");\n";
        }
        $sql .= "\n";
    }

    $sql .= "SET FOREIGN_KEY_CHECKS=1;\n";
    file_put_contents($filepath, $sql);
    logActivity($conn, 'create_backup', 'backup', null, 'Created backup: ' . $filename);
    $msg = '<div class="alert alert-success">✅ Backup created: <strong>' . htmlspecialchars($filename) . '</strong></div>';
}

// --- Download existing backup ---
if (isset($_GET['download'])) {
    $file = basename($_GET['download']);
    $path = $backup_dir . $file;
    if (file_exists($path) && pathinfo($file, PATHINFO_EXTENSION) === 'sql') {
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $file . '"');
        header('Content-Length: ' . filesize($path));
        readfile($path);
        exit;
    }
}

// --- Delete backup ---
if (isset($_POST['delete_backup'])) {
    $file = basename($_POST['backup_file']);
    $path = $backup_dir . $file;
    if (file_exists($path)) {
        unlink($path);
        logActivity($conn, 'delete_backup', 'backup', null, 'Deleted backup: ' . $file);
        $msg = '<div class="alert alert-success">🗑️ Backup deleted.</div>';
    }
}

// --- Restore backup ---
if (isset($_POST['restore_backup'])) {
    if (!empty($_FILES['restore_file']['name'])) {
        $ext = strtolower(pathinfo($_FILES['restore_file']['name'], PATHINFO_EXTENSION));
        if ($ext !== 'sql') {
            $msg = '<div class="alert alert-danger">❌ Only .sql files are allowed.</div>';
        } else {
            $sql_content = file_get_contents($_FILES['restore_file']['tmp_name']);
            if ($conn->multi_query($sql_content)) {
                while ($conn->next_result()); // flush results
                logActivity($conn, 'restore_backup', 'backup', null, 'Restored from uploaded SQL file');
                $msg = '<div class="alert alert-success">✅ Database restored successfully.</div>';
            } else {
                $msg = '<div class="alert alert-danger">❌ Restore failed: ' . htmlspecialchars($conn->error) . '</div>';
            }
        }
    } else {
        $msg = '<div class="alert alert-danger">❌ Please select a .sql file to restore.</div>';
    }
}

// --- Load backup history ---
$backups = [];
foreach (glob($backup_dir . '*.sql') as $f) {
    $backups[] = ['name' => basename($f), 'size' => filesize($f), 'time' => filemtime($f)];
}
usort($backups, fn($a, $b) => $b['time'] - $a['time']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= $page_title ?> - RELINK Admin</title>
<link rel="stylesheet" href="/lostfound_relink/assets/css/style.css">
<style>
    .backup-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; align-items: start; }
    .backup-row { display: flex; align-items: center; gap: 10px; padding: 10px 12px; background: var(--bg); border-radius: var(--radius); border: 1px solid var(--border); margin-bottom: 6px; }
    .backup-name { flex: 1; font-size: 13px; font-weight: 500; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .backup-meta { font-size: 11px; color: var(--text-muted); white-space: nowrap; }
    @media (max-width: 768px) { .backup-grid { grid-template-columns: 1fr; } }
</style>
</head>
<body>
<div class="layout">
    <?php include '../includes/admin_sidebar.php'; ?>
    <div class="main-content">
        <?php include '../includes/topbar.php'; ?>
        <div class="page-content">
            <?= $msg ?>

            <div class="backup-grid">

                <!-- Create Backup -->
                <div class="card">
                    <div class="card-header"><h3>💾 Create Backup</h3></div>
                    <div class="card-body">
                        <p style="font-size:13px;color:var(--text-muted);margin-bottom:16px">
                            Generate a full SQL dump of the <strong><?= DB_NAME ?></strong> database. The file will be saved to the server and available for download.
                        </p>
                        <form method="POST">
                            <button type="submit" name="create_backup" class="btn btn-primary btn-block">
                                💾 Generate Backup Now
                            </button>
                        </form>
                    </div>
                </div>

                <!-- Restore Backup -->
                <div class="card">
                    <div class="card-header"><h3>🔄 Restore Database</h3></div>
                    <div class="card-body">
                        <p style="font-size:13px;color:var(--danger);margin-bottom:16px">
                            ⚠️ <strong>Warning:</strong> Restoring will overwrite existing data. Make sure to create a backup first.
                        </p>
                        <form method="POST" enctype="multipart/form-data" onsubmit="return confirm('Are you sure you want to restore? This will overwrite all current data.')">
                            <div class="form-group">
                                <label>Upload .sql File</label>
                                <input type="file" name="restore_file" class="form-control" accept=".sql" required>
                            </div>
                            <button type="submit" name="restore_backup" class="btn btn-danger btn-block">
                                🔄 Restore Now
                            </button>
                        </form>
                    </div>
                </div>

            </div>

            <!-- Backup History -->
            <div class="card" style="margin-top:20px">
                <div class="card-header">
                    <h3>📂 Backup History</h3>
                    <span class="badge badge-matched"><?= count($backups) ?> file<?= count($backups) !== 1 ? 's' : '' ?></span>
                </div>
                <div class="card-body">
                    <?php if (empty($backups)): ?>
                    <div class="text-center text-muted" style="padding:32px 0">
                        <div style="font-size:36px;margin-bottom:8px">💾</div>
                        <p>No backups yet. Create one above.</p>
                    </div>
                    <?php else: ?>
                    <?php foreach ($backups as $b): ?>
                    <div class="backup-row">
                        <span style="font-size:20px">🗄️</span>
                        <span class="backup-name"><?= htmlspecialchars($b['name']) ?></span>
                        <span class="backup-meta"><?= round($b['size'] / 1024, 1) ?> KB</span>
                        <span class="backup-meta"><?= date('M d, Y H:i', $b['time']) ?></span>
                        <a href="?download=<?= urlencode($b['name']) ?>" class="btn btn-sm btn-primary">⬇ Download</a>
                        <form method="POST" onsubmit="return confirm('Delete this backup?')" style="margin:0">
                            <input type="hidden" name="backup_file" value="<?= htmlspecialchars($b['name']) ?>">
                            <button type="submit" name="delete_backup" class="btn btn-sm btn-danger">🗑</button>
                        </form>
                    </div>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>

        </div>
    </div>
</div>
<script src="/lostfound_relink/assets/js/main.js"></script>
</body>
</html>
