<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../src/auth.php';
require_login();

date_default_timezone_set('Asia/Beirut');

$backupDir = __DIR__ . "/backups/";
if (!is_dir($backupDir)) mkdir($backupDir, 0777, true);

// AUTO CLEAN – keep last 5 backups
$files = glob($backupDir . "*.sql");
usort($files, fn($a,$b)=> filemtime($b)-filemtime($a));
if (count($files) > 5) {
    for ($i=5; $i < count($files); $i++) unlink($files[$i]);
}

// CREATE BACKUP
if (isset($_GET['create'])) {
    $date = date("Y-m-d_H-i-s");
    $file = $backupDir . "backup_$date.sql";
    $cmd = "mysqldump -u $DB_USER -p$DB_PASS $DB_NAME > $file";
    system($cmd);
    header("Location: download_backup.php?created=1");
    exit;
}

// DOWNLOAD
if (isset($_GET['download'])) {
    $file = $backupDir . basename($_GET['download']);
    if (file_exists($file)) {
        header("Content-Type: application/octet-stream");
        header("Content-Disposition: attachment; filename='".basename($file)."'");
        readfile($file);
        exit;
    }
}

// RESTORE
if (isset($_GET['restore'])) {
    $file = $backupDir . basename($_GET['restore']);
    if (file_exists($file)) {
        $cmd = "mysql -u $DB_USER -p$DB_PASS $DB_NAME < $file";
        system($cmd);
        header("Location: download_backup.php?restored=1");
        exit;
    }
}

// DELETE
if (isset($_GET['delete'])) {
    $file = $backupDir . basename($_GET['delete']);
    if (file_exists($file)) unlink($file);
    header("Location: download_backup.php?deleted=1");
    exit;
}

$backups = glob($backupDir . "*.sql");
usort($backups, fn($a,$b)=> filemtime($b)-filemtime($a));
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Database Backups</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
<style>
body {
    background:#f5f6fa;
    font-family:'Inter', sans-serif;
    color:#333;
}
.card {
    border:none;
    border-radius:14px;
    background:white;
    box-shadow:0 4px 12px rgba(0,0,0,0.06);
}
.table thead {
    background:#e9eef6;
}
.btn-main {
    background:#4e73df;
    color:white;
    border-radius:8px;
}
.btn-main:hover {
    background:#3d5ec9;
}
.btn-grey {
    background:#dfe4ea;
    color:#333;
    border-radius:8px;
}
.btn-grey:hover {
    background:#cdd3db;
}
.btn-round {
    border-radius:8px;
}
</style>
</head>
<body>

<div class="container py-4">

    <div class="d-flex justify-content-between align-items-center mb-3">
        <h3 class="fw-bold"><i class="fa fa-database text-primary"></i> Database Backups</h3>

        <a href="../index.php" class="btn btn-grey btn-round">
            <i class="fa fa-home"></i> Home
        </a>
    </div>

    <?php if(isset($_GET['created'])): ?>
        <div class="alert alert-success">Backup created successfully.</div>
    <?php endif; ?>
    <?php if(isset($_GET['restored'])): ?>
        <div class="alert alert-warning">Database restored successfully.</div>
    <?php endif; ?>
    <?php if(isset($_GET['deleted'])): ?>
        <div class="alert alert-danger">Backup deleted successfully.</div>
    <?php endif; ?>

    <div class="card p-4 mb-4">
        <h5 class="fw-semibold">Backup Tools</h5>
        <p class="text-muted">Create system backup anytime.</p>

        <a href="download_backup.php?create=1" class="btn btn-main mt-2">
            <i class="fa fa-save"></i> Create Backup Now
        </a>
    </div>

    <div class="card p-4">
        <h5 class="fw-semibold mb-3">Saved Backups</h5>

        <div class="table-responsive">
            <table class="table table-bordered align-middle">
                <thead>
                    <tr>
                        <th>File Name</th>
                        <th>Date</th>
                        <th>Size</th>
                        <th style="width:170px;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php if(empty($backups)): ?>
                    <tr><td colspan="4" class="text-center text-muted py-3">No backups yet.</td></tr>
                <?php else: foreach($backups as $file): ?>
                    <tr>
                        <td><?= basename($file) ?></td>
                        <td><?= date("Y-m-d H:i:s", filemtime($file)) ?></td>
                        <td><?= round(filesize($file)/1024,2) ?> KB</td>
                        <td>
                            <a href="download_backup.php?download=<?= basename($file) ?>" class="btn btn-success btn-sm btn-round">
                                <i class="fa fa-download"></i>
                            </a>
                            <a href="download_backup.php?restore=<?= basename($file) ?>" 
                               class="btn btn-warning btn-sm btn-round"
                               onclick="return confirm('Restore this backup? It will overwrite all data!');">
                                <i class="fa fa-rotate-left"></i>
                            </a>
                            <a href="download_backup.php?delete=<?= basename($file) ?>" 
                               class="btn btn-danger btn-sm btn-round"
                               onclick="return confirm('Delete this backup?');">
                                <i class="fa fa-trash"></i>
                            </a>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>

</div>

</body>
</html>
