<?php
require_once 'auth.php';
require_once '../config/database.php';
check_admin_login();

$message = '';
$error = '';

// Fonction pour sauvegarder la base de données
if (isset($_POST['backup_db'])) {
    try {
        $filename = 'backup_db_' . date('Y-m-d_H-i-s') . '.sql';
        $path = '../backups/';
        if (!is_dir($path)) mkdir($path, 0777, true);
        
        $filePath = $path . $filename;
        
        // Utilisation de mysqldump si disponible, sinon export PHP basique
        // Pour cet environnement, on va tenter un export PHP simple
        $tables = [];
        $result = $pdo->query("SHOW TABLES");
        while ($row = $result->fetch(PDO::FETCH_NUM)) {
            $tables[] = $row[0];
        }
        
        $sql = "-- Sauvegarde Kutzenhausen\n-- Date: " . date('Y-m-d H:i:s') . "\n\n";
        $sql .= "SET FOREIGN_KEY_CHECKS=0;\n";
        $sql .= "SET NAMES utf8mb4;\n\n";
        
        foreach ($tables as $table) {
            $sql .= "DROP TABLE IF EXISTS `$table`;\n";
            $res = $pdo->query("SHOW CREATE TABLE `$table` ");
            $createTable = $res->fetch(PDO::FETCH_NUM);
            $sql .= $createTable[1] . ";\n\n";
            
            $res = $pdo->query("SELECT * FROM `$table` ");
            while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
                $sql .= "INSERT INTO `$table` VALUES (";
                $vals = [];
                foreach ($row as $val) {
                    if ($val === null) {
                        $vals[] = 'NULL';
                    } else {
                        $vals[] = $pdo->quote($val);
                    }
                }
                $sql .= implode(',', $vals) . ");\n";
            }
            $sql .= "\n";
        }
        
        $sql .= "SET FOREIGN_KEY_CHECKS=1;\n";
        
        file_put_contents($filePath, $sql);
        
        // Proposer le téléchargement direct
        header('Content-Type: application/octet-stream');
        header("Content-Transfer-Encoding: Binary");
        header("Content-disposition: attachment; filename=\"" . $filename . "\"");
        echo $sql;
        exit;
        
    } catch (Exception $e) {
        $error = "Erreur lors de la sauvegarde : " . $e->getMessage();
    }
}

// Fonction pour sauvegarder les fichiers (Zip)
if (isset($_POST['backup_site'])) {
    try {
        if (!class_exists('ZipArchive')) {
            throw new Exception("L'extension ZipArchive n'est pas activée sur ce serveur.");
        }
        
        $filename = 'backup_site_' . date('Y-m-d_H-i-s') . '.zip';
        $path = '../backups/';
        if (!is_dir($path)) mkdir($path, 0777, true);
        $filePath = $path . $filename;
        
        $zip = new ZipArchive();
        if ($zip->open($filePath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) {
            throw new Exception("Impossible de créer le fichier Zip.");
        }
        
        $rootPath = realpath('../');
        $files = new RecursiveIteratorIterator(
            new RecursiveCallbackFilterIterator(
                new RecursiveDirectoryIterator($rootPath, RecursiveDirectoryIterator::SKIP_DOTS),
                function ($current, $key, $iterator) {
                    // Exclure le dossier backups lui-même pour éviter la récursion infinie
                    return $current->getFilename() !== 'backups';
                }
            )
        );

        foreach ($files as $name => $file) {
            if (!$file->isDir()) {
                $filePathInZip = substr($file->getRealPath(), strlen($rootPath) + 1);
                // Remplacer les antislashs de Windows par des slashs pour préserver l'arborescence
                $filePathInZip = str_replace('\\', '/', $filePathInZip);
                $zip->addFile($file->getRealPath(), $filePathInZip);
            }
        }
        
        $zip->close();
        
        // Téléchargement
        header('Content-Type: application/zip');
        header("Content-disposition: attachment; filename=\"" . $filename . "\"");
        header('Content-Length: ' . filesize($filePath));
        readfile($filePath);
        exit;
        
    } catch (Exception $e) {
        $error = "Erreur lors du backup site : " . $e->getMessage();
    }
}

?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Sauvegarde du Site - Admin</title>
    <script src="../js/tailwind.min.js"></script>
    <script src="../js/lucide.min.js"></script>
</head>
<body class="bg-gray-50 flex h-screen font-sans text-gray-800">
    
    <?php include 'includes/sidebar.php'; ?>

    <main class="flex-1 flex flex-col h-screen overflow-hidden">
        <header class="h-20 bg-white shadow-sm flex items-center justify-between px-8 flex-shrink-0">
            <h1 class="text-2xl font-bold text-gray-800">Sauvegarde & Maintenance</h1>
        </header>

        <div class="flex-1 overflow-auto p-8 space-y-8">
            <?php if($error): ?>
                <div class="p-4 bg-red-100 text-red-700 rounded-lg shadow-sm border border-red-200"><?php echo $error; ?></div>
            <?php endif; ?>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                <!-- Database Backup -->
                <div class="bg-white p-8 rounded-2xl shadow-sm border border-gray-100 flex flex-col items-center text-center">
                    <div class="p-4 bg-blue-50 text-blue-600 rounded-full mb-6">
                        <i data-lucide="database" class="w-12 h-12"></i>
                    </div>
                    <h2 class="text-2xl font-bold mb-4">Base de données</h2>
                    <p class="text-gray-500 mb-8 leading-relaxed">Téléchargez un export complet au format SQL contenant toutes vos pages, articles, associations et réglages.</p>
                    <form method="POST">
                        <button type="submit" name="backup_db" class="bg-blue-600 text-white px-8 py-3 rounded-xl font-bold hover:bg-blue-700 transition flex items-center shadow-md">
                            <i data-lucide="download" class="w-5 h-5 mr-2"></i> Sauvegarder la BDD
                        </button>
                    </form>
                </div>

                <!-- Files Backup -->
                <div class="bg-white p-8 rounded-2xl shadow-sm border border-gray-100 flex flex-col items-center text-center">
                    <div class="p-4 bg-purple-50 text-purple-600 rounded-full mb-6">
                        <i data-lucide="folder-archive" class="w-12 h-12"></i>
                    </div>
                    <h2 class="text-2xl font-bold mb-4">Fichiers du Site</h2>
                    <p class="text-gray-500 mb-8 leading-relaxed">Créez une archive ZIP contenant l'intégralité des fichiers du site, y compris les images et documents téléchargés.</p>
                    <form method="POST">
                        <button type="submit" name="backup_site" class="bg-purple-600 text-white px-8 py-3 rounded-xl font-bold hover:bg-purple-700 transition flex items-center shadow-md">
                            <i data-lucide="file-archive" class="w-5 h-5 mr-2"></i> Sauvegarder tout le site
                        </button>
                    </form>
                </div>
            </div>

            <div class="bg-yellow-50 p-6 rounded-2xl border border-yellow-100">
                <div class="flex">
                    <i data-lucide="alert-triangle" class="w-6 h-6 text-yellow-600 mr-4"></i>
                    <div>
                        <h4 class="font-bold text-yellow-800 mb-1">Recommandations</h4>
                        <p class="text-yellow-700 text-sm leading-relaxed">Il est conseillé de réaliser une sauvegarde avant toute mise à jour majeure ou modification importante de la structure du site. Stockez vos sauvegardes dans un endroit sûr, hors du serveur web.</p>
                    </div>
                </div>
            </div>
        </div>
    </main>
    <script>lucide.createIcons();</script>
</body>
</html>
