<?php
session_start();
require_once 'config.php';
require_once 'functions.php';
requireLogin();
$user = getConnectedUser($pdo);
requireAdmin($user);

$msg = ''; $err = '';
$backupDir = __DIR__ . '/backups/';

// Créer dossier si absent
if (!is_dir($backupDir)) {
    mkdir($backupDir, 0750, true);
    file_put_contents($backupDir . '.htaccess', "Deny from all\n");
}

// --- LANCER UN BACKUP MANUEL ---
if (isset($_POST['run_backup'])) {
    $token = 'JETEGAGE_BACKUP_2024_SECRET'; // Doit correspondre à cron_backup.php
    $url   = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST']
           . str_replace('admin_backup.php', 'cron_backup.php', $_SERVER['REQUEST_URI'])
           . '?token=' . $token;
    // Lancer via include direct (plus fiable que HTTP interne)
    ob_start();
    $_GET['token'] = $token;
    include __DIR__ . '/cron_backup.php';
    $output = ob_get_clean();
    $data = json_decode($output, true);
    if ($data && empty($data['errors'])) {
        $msg = "✅ Backup terminé — " . implode(' | ', $data['log'] ?? []);
    } else {
        $err = "⚠️ Backup avec erreurs — " . implode(' | ', $data['errors'] ?? ['Erreur inconnue']);
    }
}

// --- TÉLÉCHARGER UN FICHIER ---
if (isset($_GET['dl'])) {
    $file = basename($_GET['dl']);
    $path = $backupDir . $file;
    if (file_exists($path) && preg_match('/^backup_[\d_-]+\.sql\.gz$/', $file)) {
        header('Content-Type: application/gzip');
        header('Content-Disposition: attachment; filename="' . $file . '"');
        header('Content-Length: ' . filesize($path));
        readfile($path);
        exit;
    }
}

// --- SUPPRIMER UN FICHIER ---
if (isset($_GET['del'])) {
    $file = basename($_GET['del']);
    $path = $backupDir . $file;
    if (file_exists($path) && preg_match('/^backup_[\d_-]+\.sql\.gz$/', $file)) {
        unlink($path);
        $msg = "🗑️ Fichier supprimé : {$file}";
    }
}

// Charger infos
$lastDate = getWalletConfig($pdo, 'last_backup_date', '—');
$lastLog  = getWalletConfig($pdo, 'last_backup_log',  '—');
$lastFile = getWalletConfig($pdo, 'last_backup_file',  '—');

// Liste des fichiers de backup
$files = glob($backupDir . 'backup_*.sql.gz') ?: [];
usort($files, fn($a,$b) => filemtime($b) - filemtime($a));

// Taille totale
$totalSize = array_sum(array_map('filesize', $files));

// Infos BD de backup
$backupDbName = 'jetegage_db_backup';
$backupDbExists = false;
$backupLastUpdate = '—';
try {
    $pdoCheck = new PDO("mysql:host={$host};charset=utf8mb4", $user, $pass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
    $dbs = $pdoCheck->query("SHOW DATABASES LIKE '{$backupDbName}'")->fetchAll();
    $backupDbExists = !empty($dbs);
    if ($backupDbExists) {
        $pdoCheck->exec("USE `{$backupDbName}`");
        $logRow = $pdoCheck->query("SELECT backup_date FROM `_backup_log` ORDER BY backup_date DESC LIMIT 1")->fetch();
        if ($logRow) $backupLastUpdate = $logRow['backup_date'];
    }
} catch (Exception $e) {}

$currentPage = 'admin_backup.php';
include 'header.php';
?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">

<div class="container mt-4 mb-5">

    <div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
        <div>
            <h5 class="text-info mb-0 fw-bold" style="letter-spacing:1px;">
                <i class="fa-solid fa-database me-2"></i>GESTION DES BACKUPS
            </h5>
            <small class="text-muted">Snapshots quotidiennes automatiques — 30 jours de rétention</small>
        </div>
        <a href="admin_config.php" class="btn btn-outline-secondary btn-sm">← Config</a>
    </div>

    <?php if ($msg): ?>
    <div class="alert alert-success py-2 small"><?= htmlspecialchars($msg) ?></div>
    <?php endif; ?>
    <?php if ($err): ?>
    <div class="alert alert-warning py-2 small"><?= htmlspecialchars($err) ?></div>
    <?php endif; ?>

    <div class="row g-3 mb-4">

        <!-- Statut backup BD -->
        <div class="col-md-4">
            <div class="card bg-dark border-info h-100">
                <div class="card-header py-2" style="background:#050520;border-bottom:1px solid #0dcaf0;">
                    <span class="text-info fw-bold" style="font-size:0.7rem;"><i class="fa-solid fa-server me-1"></i> BD DE BACKUP</span>
                </div>
                <div class="card-body p-3">
                    <div class="d-flex align-items-center gap-2 mb-2">
                        <?php if ($backupDbExists): ?>
                        <span class="badge bg-success" style="font-size:0.6rem;">✅ EXISTE</span>
                        <?php else: ?>
                        <span class="badge bg-secondary" style="font-size:0.6rem;">⚪ NON CRÉÉE</span>
                        <?php endif; ?>
                        <code class="text-info" style="font-size:0.62rem;"><?= htmlspecialchars($backupDbName) ?></code>
                    </div>
                    <div class="text-muted" style="font-size:0.62rem;">Dernière synchro :</div>
                    <div class="text-white" style="font-size:0.68rem;"><?= htmlspecialchars($backupLastUpdate) ?></div>
                    <div class="text-muted mt-2" style="font-size:0.58rem;">
                        La BD de backup est une copie complète sur le même serveur MySQL, mise à jour à chaque backup nocturne.
                    </div>
                </div>
            </div>
        </div>

        <!-- Statut dernier backup -->
        <div class="col-md-4">
            <div class="card bg-dark border-secondary h-100">
                <div class="card-header py-2" style="background:#050520;">
                    <span class="text-white fw-bold" style="font-size:0.7rem;"><i class="fa-solid fa-clock-rotate-left me-1"></i> DERNIER BACKUP</span>
                </div>
                <div class="card-body p-3">
                    <div class="text-warning fw-bold mb-1" style="font-size:0.72rem;"><?= htmlspecialchars($lastDate) ?></div>
                    <?php if ($lastFile !== '—'): ?>
                    <div class="text-muted mb-2" style="font-size:0.6rem;"><i class="fa-solid fa-file-zipper me-1"></i><?= htmlspecialchars($lastFile) ?></div>
                    <?php endif; ?>
                    <div style="font-size:0.58rem;color:#aaa;word-break:break-word;"><?= htmlspecialchars($lastLog) ?></div>
                </div>
            </div>
        </div>

        <!-- Stats fichiers + backup manuel -->
        <div class="col-md-4">
            <div class="card bg-dark border-secondary h-100">
                <div class="card-header py-2" style="background:#050520;">
                    <span class="text-white fw-bold" style="font-size:0.7rem;"><i class="fa-solid fa-folder me-1"></i> FICHIERS SQL</span>
                </div>
                <div class="card-body p-3">
                    <div class="d-flex justify-content-between mb-1">
                        <span class="text-muted small" style="font-size:0.65rem;">Fichiers disponibles</span>
                        <span class="text-white fw-bold small"><?= count($files) ?> / 30</span>
                    </div>
                    <div class="d-flex justify-content-between mb-3">
                        <span class="text-muted small" style="font-size:0.65rem;">Taille totale</span>
                        <span class="text-info fw-bold small"><?= round($totalSize/1024/1024, 1) ?> MB</span>
                    </div>
                    <form method="POST">
                        <button type="submit" name="run_backup" class="btn btn-info btn-sm fw-bold w-100"
                                onclick="return confirm('Lancer un backup maintenant ?')"
                                style="font-size:0.68rem;">
                            <i class="fa-solid fa-play me-1"></i>Backup manuel maintenant
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Configuration cron -->
    <div class="card bg-dark border-secondary mb-4">
        <div class="card-header py-2" style="background:#0a0a1a;">
            <span class="text-warning fw-bold" style="font-size:0.7rem;"><i class="fa-solid fa-terminal me-1"></i> CONFIGURATION CRON (cPanel)</span>
        </div>
        <div class="card-body p-3">
            <div class="text-muted mb-2" style="font-size:0.65rem;">Ajouter cette ligne dans cPanel → Cron Jobs pour un backup automatique à 3h00 chaque nuit :</div>
            <div class="p-2 rounded d-flex align-items-center gap-2" style="background:#060610;border:1px solid #1a1a2a;">
                <code id="cronCmd" style="font-size:0.65rem;color:#0dcaf0;flex:1;word-break:break-all;">0 3 * * * php <?= __DIR__ ?>/cron_backup.php >> /dev/null 2>&1</code>
                <button onclick="copyCron()" class="btn btn-xs btn-outline-info py-0 flex-shrink-0" style="font-size:0.6rem;">Copier</button>
            </div>
            <div class="text-muted mt-2" style="font-size:0.6rem;">
                ⚠️ Avant d'activer le cron, assurez-vous que la BD <code><?= htmlspecialchars($backupDbName) ?></code> existe sur votre serveur MySQL et que l'utilisateur <code><?= htmlspecialchars($user) ?></code> a les droits CREATE/INSERT/DROP dessus.
            </div>
        </div>
    </div>

    <!-- Liste des fichiers -->
    <div class="card bg-dark border-secondary">
        <div class="card-header py-2 d-flex justify-content-between align-items-center" style="background:#0a0a1a;">
            <span class="text-white fw-bold" style="font-size:0.7rem;">📦 FICHIERS DE BACKUP DISPONIBLES</span>
            <span class="text-muted" style="font-size:0.6rem;">Rétention : 30 jours</span>
        </div>
        <?php if (empty($files)): ?>
        <div class="card-body text-center text-muted py-5 small">
            <i class="fa-solid fa-box-open fa-2x mb-2 d-block opacity-25"></i>
            Aucun fichier de backup pour l'instant.<br>Lance un backup manuel ou attends le cron nocturne.
        </div>
        <?php else: ?>
        <div class="table-responsive">
            <table class="table table-dark table-hover mb-0" style="font-size:0.68rem;">
                <thead style="background:#060610;">
                    <tr>
                        <th class="py-2 ps-3">FICHIER</th>
                        <th class="py-2">DATE</th>
                        <th class="py-2">TAILLE</th>
                        <th class="py-2 text-center">ACTIONS</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($files as $i => $f):
                    $fname   = basename($f);
                    $fdate   = date('Y-m-d H:i', filemtime($f));
                    $fsize   = round(filesize($f) / 1024, 0);
                    $isLatest = $i === 0;
                ?>
                <tr>
                    <td class="py-2 ps-3">
                        <i class="fa-solid fa-file-zipper text-info me-1"></i>
                        <code style="font-size:0.62rem;"><?= htmlspecialchars($fname) ?></code>
                        <?php if ($isLatest): ?>
                        <span class="badge bg-success ms-1" style="font-size:0.5rem;">DERNIER</span>
                        <?php endif; ?>
                    </td>
                    <td class="py-2 text-muted"><?= $fdate ?></td>
                    <td class="py-2 text-info"><?= number_format($fsize) ?> KB</td>
                    <td class="py-2 text-center">
                        <div class="d-flex gap-1 justify-content-center">
                            <a href="?dl=<?= urlencode($fname) ?>"
                               class="btn btn-xs btn-outline-info py-0" title="Télécharger">
                                <i class="fa-solid fa-download"></i>
                            </a>
                            <a href="?del=<?= urlencode($fname) ?>"
                               onclick="return confirm('Supprimer ce backup ?')"
                               class="btn btn-xs btn-outline-danger py-0" title="Supprimer">
                                <i class="fa-solid fa-trash"></i>
                            </a>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>
</div>

<script>
function copyCron() {
    const text = document.getElementById('cronCmd').textContent;
    navigator.clipboard.writeText(text).then(() => {
        const btn = event.target;
        btn.textContent = '✓ Copié';
        setTimeout(() => btn.textContent = 'Copier', 2000);
    });
}
</script>

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