<?php
session_start();
require_once 'config/connexion.php';

// Vérifier si l'utilisateur est connecté
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");    exit();
}

// Fonction pour écrire dans le log spécifique d'une compagnie (simplifiée)
function writeCompagnieLog($compagnieRef, $message, $type = 'INFO') {
    // Ne conserver que SUCCESS et ERROR (ignorer INFO)
    if ($type === 'INFO') {
        return; // On ignore simplement les messages d'information désormais
    }
    try {
        $logDir = "backup";
        if (!is_dir($logDir)) {
            mkdir($logDir, 0755, true);
        }
        $logFile = "$logDir/{$compagnieRef}_backup.log";
        $timestamp = date('Y-m-d H:i:s');
        $logEntry = "[$timestamp] [$type] $message" . PHP_EOL;
        // Lire les logs existants
        $existingLogs = [];
        if (file_exists($logFile)) {
            $lines = file($logFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            if ($lines !== false) {
                $existingLogs = $lines;
            }
        }
        // Ajouter le nouveau log
        $existingLogs[] = rtrim($logEntry);
        // Garder seulement les 80 dernières opérations
        if (count($existingLogs) > 80) {
            $existingLogs = array_slice($existingLogs, -80);
        }
        file_put_contents($logFile, implode(PHP_EOL, $existingLogs) . PHP_EOL, LOCK_EX);
    } catch (Exception $e) {
        error_log("Erreur écriture log compagnie $compagnieRef: " . $e->getMessage());
    }
}

// Fonction pour obtenir la référence de la compagnie
function getCompagnieRef($pdo, $userId) {
    try {
        // Connexion spécifique à la base assurance_gestion pour récupérer la compagnie de l'utilisateur
        $host = 'localhost';
        $username = 'root';
        $password = '';
        $gestionDbName = 'assurance_gestion';
        
        $dsn = "mysql:host=$host;dbname=$gestionDbName;charset=utf8";
        $gestionPdo = new PDO($dsn, $username, $password, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
        ]);
        
        // Pour l'instant, récupérer la première compagnie
        // TODO: Adapter selon la logique de votre application (utilisateur -> compagnie)
        $stmt = $gestionPdo->query("SELECT compagnie_ref FROM compagnies_table LIMIT 1");
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result ? $result['compagnie_ref'] : null;
    } catch (PDOException $e) {
        return null;
    }
}

// Fonction pour lire les logs de backup d'une compagnie
function getCompagnieLogs($compagnieRef, $limit = 20) {
    $logFile = "backup/{$compagnieRef}_backup.log";
    $logs = [];
    
    if (!file_exists($logFile)) {
        return $logs;
    }
    
    try {
        $lines = file($logFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        if ($lines === false) {
            return $logs;
        }
        
        // Prendre les dernières lignes (plus récentes) et les inverser pour affichage chronologique inverse
        $lines = array_slice($lines, -$limit);
        $lines = array_reverse($lines); // Afficher les plus récents en premier
        
        foreach ($lines as $line) {
            // Parser le format: [YYYY-MM-DD HH:ii:ss] [TYPE] Message
            if (preg_match('/^\[(.+?)\] \[(.+?)\] (.+)$/', $line, $matches)) {
                $logs[] = [
                    'timestamp' => $matches[1],
                    'type' => $matches[2],
                    'message' => $matches[3]
                ];
            }
        }
        
        return $logs;
    } catch (Exception $e) {
        return $logs;
    }
}

// Fonction pour créer un backup complet (SQL + Fichiers dans un seul ZIP)
function createFullBackup($pdo, $compagnieRef) {
    try {
        $backupDir = "backup/$compagnieRef";
        if (!is_dir($backupDir)) {
            mkdir($backupDir, 0755, true);
        }
        
        // Supprimer l'ancien backup manuel s'il existe
        $files = glob("$backupDir/backup_manuel_*.zip");
        $deletedCount = 0;
        foreach ($files as $file) {
            unlink($file);
            $deletedCount++;
        }
        
        $timestamp = date('Y-m-d_H-i-s');
        $zipFile = "$backupDir/backup_manuel_$timestamp.zip";
        
        // 1. Créer le dump SQL temporaire
        if (!is_dir("backup/temp")) {
            mkdir("backup/temp", 0755, true);
        }
        $tempSqlFile = "backup/temp/backup_sql_" . time() . ".sql";
        
        // Générer le SQL
        $stmt = $pdo->query("SHOW TABLES");
        $tables = $stmt->fetchAll(PDO::FETCH_COLUMN);
        
        $tableCount = count($tables);
        
        $sql = "-- Backup manuel de la base de données\n";
        $sql .= "-- Date: " . date('Y-m-d H:i:s') . "\n";
        $sql .= "-- Compagnie: $compagnieRef\n\n";
        
        foreach ($tables as $table) {
            // Structure de la table
            $stmt = $pdo->query("SHOW CREATE TABLE `$table`");
            $createTable = $stmt->fetch(PDO::FETCH_ASSOC);
            $sql .= "DROP TABLE IF EXISTS `$table`;\n";
            $sql .= $createTable['Create Table'] . ";\n\n";
            
            // Données de la table
            $stmt = $pdo->query("SELECT * FROM `$table`");
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            if (!empty($rows)) {
                $sql .= "INSERT INTO `$table` VALUES\n";
                $values = [];
                foreach ($rows as $row) {
                    $escapedValues = array_map(function($value) use ($pdo) {
                        return $value === null ? 'NULL' : $pdo->quote($value);
                    }, $row);
                    $values[] = "(" . implode(", ", $escapedValues) . ")";
                }
                $sql .= implode(",\n", $values) . ";\n\n";
            }
        }
        
        file_put_contents($tempSqlFile, $sql);
        
        // 2. Créer le ZIP avec SQL + Fichiers
        $zip = new ZipArchive();
        if ($zip->open($zipFile, ZipArchive::CREATE) !== TRUE) {
            unlink($tempSqlFile);
            throw new Exception("Impossible de créer le fichier ZIP");
        }
        
        // Ajouter le fichier SQL au ZIP
        $zip->addFile($tempSqlFile, "database_backup_$timestamp.sql");
        
        // Ajouter les fichiers du dossier data si il existe
        $sourceDir = "data/$compagnieRef";
        if (is_dir($sourceDir)) {
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($sourceDir),
                RecursiveIteratorIterator::LEAVES_ONLY
            );
            
            foreach ($iterator as $file) {
                if (!$file->isDir()) {
                    $filePath = $file->getRealPath();
                    $relativePath = "files/" . substr($filePath, strlen(realpath($sourceDir)) + 1);
                    $zip->addFile($filePath, $relativePath);
                }
            }
        }        $zip->close();
        unlink($tempSqlFile); // Supprimer le fichier SQL temporaire
        
        $fileSize = filesize($zipFile);
        $fileCount = 0;
        $sourceDir = "data/$compagnieRef";
        if (is_dir($sourceDir)) {
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($sourceDir),
                RecursiveIteratorIterator::LEAVES_ONLY
            );
            foreach ($iterator as $file) {
                if (!$file->isDir()) {
                    $fileCount++;
                }
            }
        }
          // LOG SIMPLIFIÉ : Seulement le succès final avec le nom du fichier
        $zipFileName = basename($zipFile);
        writeCompagnieLog($compagnieRef, "Backup manuel réussi: $zipFileName", 'SUCCESS');
        
        return $zipFile;
    } catch (Exception $e) {
        // LOG SIMPLIFIÉ : Seulement l'échec final
        writeCompagnieLog($compagnieRef, "Backup manuel échoué", 'ERROR');
        throw new Exception("Erreur lors du backup: " . $e->getMessage());
    }
}

// Fonction pour restaurer un backup
function restoreBackup($pdo, $compagnieRef, $backupFile, $isFromTemp = false) {
    try {
        // Déterminer le chemin du backup
        if (file_exists($backupFile)) {
            $backupPath = $backupFile;
        } elseif ($isFromTemp) {
            $backupPath = "backup/$compagnieRef/temp/$backupFile";
        } elseif (file_exists("backup/$compagnieRef/$backupFile")) {
            $backupPath = "backup/$compagnieRef/$backupFile";
        } elseif (file_exists("backup/$compagnieRef/imports/$backupFile")) {
            $backupPath = "backup/$compagnieRef/imports/$backupFile";
        } else {
            throw new Exception("Le fichier de backup n'existe pas");
        }

        // 1. Backup temporaire actuel si pas restauration depuis temp
        if (!$isFromTemp) {
            $tempBackupDir = "backup/$compagnieRef/temp";
            if (!is_dir($tempBackupDir)) mkdir($tempBackupDir, 0755, true);
            $timestamp = date('Y-m-d_H-i-s');
            $tempBackupFile = "$tempBackupDir/backup_temp_avant_restauration_$timestamp.zip";
            $zip = new ZipArchive();
            if ($zip->open($tempBackupFile, ZipArchive::CREATE) !== true) {
                throw new Exception("Impossible de créer le backup temporaire");
            }
            $tempSqlDir = "backup/temp";
            if (!is_dir($tempSqlDir)) mkdir($tempSqlDir, 0755, true);
            $tempSqlFile = $tempSqlDir . "/temp_backup_" . time() . ".sql";
            $stmt = $pdo->query("SHOW TABLES");
            $tables = $stmt->fetchAll(PDO::FETCH_COLUMN);
            $sql = "-- Backup temporaire avant restauration\n-- Date: " . date('Y-m-d H:i:s') . "\n\n";
            foreach ($tables as $table) {
                $stmt = $pdo->query("SHOW CREATE TABLE `$table`");
                $createTable = $stmt->fetch(PDO::FETCH_ASSOC);
                $sql .= "DROP TABLE IF EXISTS `$table`;\n";
                $sql .= $createTable['Create Table'] . ";\n\n";
                $stmt = $pdo->query("SELECT * FROM `$table`");
                $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
                if ($rows) {
                    $sql .= "INSERT INTO `$table` VALUES\n";
                    $vals = [];
                    foreach ($rows as $row) {
                        $escaped = array_map(function($v) use ($pdo){return $v===null?'NULL':$pdo->quote($v);}, $row);
                        $vals[] = '(' . implode(', ', $escaped) . ')';
                    }
                    $sql .= implode(",\n", $vals) . ";\n\n";
                }
            }
            file_put_contents($tempSqlFile, $sql);
            $zip->addFile($tempSqlFile, "database_backup_temp_$timestamp.sql");
            // Ajouter fichiers
            $src = "data/$compagnieRef";
            if (is_dir($src)) {
                $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($src), RecursiveIteratorIterator::LEAVES_ONLY);
                foreach ($it as $f) {
                    if (!$f->isDir()) {
                        $filePath = $f->getRealPath();
                        $relativePath = 'files/' . substr($filePath, strlen(realpath($src)) + 1);
                        $zip->addFile($filePath, $relativePath);
                    }
                }
            }
            $zip->close();
            @unlink($tempSqlFile);
            // Rotation garder 1
            try {
                $temps = glob($tempBackupDir . '/backup_temp_avant_restauration_*.zip');
                usort($temps, function($a,$b){return filemtime($a)-filemtime($b);} );
                while (count($temps) > 1) {
                    $old = array_shift($temps);
                    @unlink($old);
                }
            } catch(Exception $ignored) {}
        }

        // 2. Extraction du backup à restaurer
        $restoreTempDir = "backup/temp/restore_" . time() . '_' . rand(1000,9999);
        if (!is_dir('backup/temp')) mkdir('backup/temp', 0755, true);
        mkdir($restoreTempDir, 0755, true);
        $zip = new ZipArchive();
        if ($zip->open($backupPath) !== true) throw new Exception("Impossible d'ouvrir le fichier ZIP");
        writeCompagnieLog($compagnieRef, "Ouverture ZIP: $backupPath", 'INFO');
        if (!$zip->extractTo($restoreTempDir)) {
            $zip->close();
            writeCompagnieLog($compagnieRef, 'Extraction ZIP échouée', 'ERROR');
            throw new Exception("Échec extraction ZIP");
        }
        $zip->close();
        writeCompagnieLog($compagnieRef, "Extraction ZIP OK dans $restoreTempDir", 'INFO');

        // Snapshot avant (compte lignes)
        $preStats = [];
        try {
            $tstmt = $pdo->query('SHOW TABLES');
            foreach ($tstmt->fetchAll(PDO::FETCH_COLUMN) as $t) {
                try { $preStats[$t] = (int)$pdo->query("SELECT COUNT(*) FROM `$t`")->fetchColumn(); } catch(Exception $ign) {}
            }
            writeCompagnieLog($compagnieRef, 'Snapshot avant: '.count($preStats).' tables', 'INFO');
        } catch(Exception $e) { writeCompagnieLog($compagnieRef,'Snapshot avant impossible: '.$e->getMessage(),'INFO'); }

        $restored = [];

        // 3. Restauration SQL
        $sqlFiles = glob($restoreTempDir.'/*.sql');
        if ($sqlFiles) {
            $sqlFile = $sqlFiles[0];
            writeCompagnieLog($compagnieRef, 'Fichier SQL: '.basename($sqlFile), 'INFO');
            $sql = file_get_contents($sqlFile);
            $size = strlen($sql);
            writeCompagnieLog($compagnieRef, 'Taille SQL: '.$size.' octets', 'INFO');
            $queries = explode(';', $sql);
            $total=0;$exec=0;$cCreate=0;$cInsert=0;$ignoredErr=0;
            // Filtrer les requêtes qui touchent users_table ou menu_items
            $filteredQueries = [];
            foreach ($queries as $q) {
                $qNorm = preg_replace('/\s+/', ' ', strtolower($q));
                if (preg_match('/\b(insert|update|delete|drop|truncate|replace|create)\b[^;]*\b(users_table|menu_items)\b/', $qNorm)) {
                    continue;
                }
                $filteredQueries[] = $q;
            }
            foreach ($filteredQueries as $q) {
                $q = trim($q);
                if ($q==='') continue;
                $total++;
                try {
                    $pdo->exec($q);
                    $exec++;
                    if (stripos($q,'CREATE TABLE')===0) {
                        $cCreate++;
                        if (preg_match('/CREATE TABLE `?(\w+)`?/i',$q,$m)) writeCompagnieLog($compagnieRef,'Table créée/restaurée: '.$m[1],'INFO');
                    } elseif (stripos($q,'INSERT INTO')===0) {
                        $cInsert++;
                        if (preg_match('/INSERT INTO `?(\w+)`?/i',$q,$m)) {
                            $valuesPart = substr($q, stripos($q,'VALUES')+6);
                            $rowApprox = substr_count($valuesPart,'(');
                            writeCompagnieLog($compagnieRef,'INSERT '.$m[1]." (~$rowApprox lignes)",'INFO');
                        }
                    }
                } catch(PDOException $e) {
                    if (stripos($e->getMessage(),'already exists')!==false || stripos($e->getMessage(),'Duplicate entry')!==false) {
                        $ignoredErr++;
                    } else {
                        writeCompagnieLog($compagnieRef,'Erreur SQL: '.$e->getMessage(),'ERROR');
                        throw $e;
                    }
                }
            }
            writeCompagnieLog($compagnieRef, "Résumé SQL: $exec/$total exécutées ($cCreate CREATE, $cInsert INSERT, $ignoredErr erreurs ignorées)", 'INFO');
            $restored[] = 'Base de données';

            // Snapshot après
            try {
                $postStats = [];$changes=[];
                $tstmt2 = $pdo->query('SHOW TABLES');
                foreach ($tstmt2->fetchAll(PDO::FETCH_COLUMN) as $t) {
                    try { $cnt = (int)$pdo->query("SELECT COUNT(*) FROM `$t`")->fetchColumn(); $postStats[$t]=$cnt; $before=$preStats[$t]??null; if ($before===null || $before!==$cnt) $changes[$t]=[$before===null?0:$before,$cnt]; } catch(Exception $ign) {}
                }
                if ($changes) {
                    $parts=[];$i=0;foreach ($changes as $tn=>$vals){ if($i>=8){$parts[]='...';break;} $parts[]=$tn.': '.$vals[0].'->'.$vals[1];$i++; }
                    writeCompagnieLog($compagnieRef,'Tables modifiées: '.implode(', ',$parts),'INFO');
                } else {
                    writeCompagnieLog($compagnieRef,'Aucun changement de lignes détecté','INFO');
                }
            } catch(Exception $e) { writeCompagnieLog($compagnieRef,'Snapshot après impossible: '.$e->getMessage(),'INFO'); }
            writeCompagnieLog($compagnieRef,'Restauration SQL terminée','INFO');
        }

        // 4. Fichiers
        $filesDir = $restoreTempDir.'/files';
        if (is_dir($filesDir)) {
            $targetDir = "data/$compagnieRef";
            if (!is_dir($targetDir)) mkdir($targetDir,0755,true);
            $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($filesDir), RecursiveIteratorIterator::SELF_FIRST);
            $fileCopied=0;
            foreach ($it as $f) {
                $dest = $targetDir . DIRECTORY_SEPARATOR . substr($f->getPathname(), strlen($filesDir)+1);
                if ($f->isDir()) {
                    if (!is_dir($dest)) mkdir($dest,0755,true);
                } else {
                    @copy($f->getPathname(), $dest);
                    $fileCopied++;
                }
            }
            writeCompagnieLog($compagnieRef, 'Fichiers restaurés: '.$fileCopied, 'INFO');
            $restored[] = 'Fichiers';
        }

        // 5. Nettoyage
        $deleteFn = function($dir) use (&$deleteFn){ if(!is_dir($dir)) return; $items=array_diff(scandir($dir),['.','..']); foreach($items as $itName){ $p=$dir.DIRECTORY_SEPARATOR.$itName; if(is_dir($p)) $deleteFn($p); else @unlink($p);} @rmdir($dir); };
        $deleteFn($restoreTempDir);
        writeCompagnieLog($compagnieRef,'Nettoyage dossier temporaire effectué','INFO');

        if (empty($restored)) {
            throw new Exception("Aucun élément restauré (ni SQL ni fichiers)");
        }
        $backupFileName = basename($backupFile);
        writeCompagnieLog($compagnieRef, "Restauration réussie: $backupFileName", 'SUCCESS');
        return $restored;
    } catch(Exception $e) {
        writeCompagnieLog($compagnieRef, 'Restauration échouée: '.basename($backupFile).' - '.$e->getMessage(),'ERROR');
        if (isset($restoreTempDir) && is_dir($restoreTempDir)) {
            try { $deleteFn($restoreTempDir); } catch(Exception $ign) {}
        }
        throw new Exception('Erreur lors de la restauration: '.$e->getMessage());
    }
}

// Pattern POST/Redirect/GET (PRG) pour éviter l'alerte de renvoi de formulaire
$message = '';
$messageType = '';

// Traitement du formulaire POST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $compagnieRef = getCompagnieRef($pdo, $_SESSION['user_id']);

    if (!$compagnieRef) {
        $_SESSION['backup_message'] = "Erreur: Impossible de récupérer la référence de la compagnie";
        $_SESSION['backup_message_type'] = 'error';
    } else {
        try {
            if ($_POST['action'] === 'backup_full') {
                $zipFile = createFullBackup($pdo, $compagnieRef);
                $fileSize = number_format(filesize($zipFile) / 1024, 2);
                $fileName = basename($zipFile);
                $_SESSION['backup_message'] = "✅ Backup créé avec succès !<br>📁 <strong>{$fileName}</strong><br>📊 Taille : {$fileSize} KB";
                $_SESSION['backup_message_type'] = 'success';
            } elseif ($_POST['action'] === 'restore' && isset($_POST['backup_file'])) {
                $backupFile = $_POST['backup_file'];
                $isFromTemp = isset($_POST['from_temp']) && $_POST['from_temp'] === '1';
                $restored = restoreBackup($pdo, $compagnieRef, $backupFile, $isFromTemp);
                $_SESSION['backup_message'] = "🔄 Restauration terminée avec succès !<br>✅ Éléments restaurés : " . implode(', ', $restored);
                $_SESSION['backup_message_type'] = 'success';
            } elseif ($_POST['action'] === 'restore_local' && isset($_FILES['local_backup']) && $_FILES['local_backup']['error'] === UPLOAD_ERR_OK) {
                $tmpFile = $_FILES['local_backup']['tmp_name'];
                $fileName = basename($_FILES['local_backup']['name']);
                $targetDir = "backup/$compagnieRef/imports";
                if (!is_dir($targetDir)) {
                    mkdir($targetDir, 0755, true);
                }
                $targetPath = $targetDir . "/" . uniqid("import_") . "_" . preg_replace('/[^a-zA-Z0-9_.-]/', '', $fileName);
                if (move_uploaded_file($tmpFile, $targetPath)) {
                    // Vérification ZIP
                    $zip = new ZipArchive();
                    if ($zip->open($targetPath) !== TRUE) {
                        $_SESSION['backup_message'] = "❌ Le fichier uploadé n'est pas un ZIP valide ou est corrompu. Veuillez sélectionner un backup généré par le système.";
                        $_SESSION['backup_message_type'] = 'error';
                        @unlink($targetPath);
                        // Nettoyer le dossier imports
                        $importsDir = "backup/$compagnieRef/imports";
                        if (is_dir($importsDir)) {
                            $files = array_diff(scandir($importsDir), array('.', '..'));
                            foreach ($files as $file) {
                                $filePath = $importsDir . "/" . $file;
                                if (is_file($filePath)) {
                                    @unlink($filePath);
                                }
                            }
                        }
                    } else {
                        $zip->close();
                        try {
                            $restored = restoreBackup($pdo, $compagnieRef, $targetPath, true);
                            $_SESSION['backup_message'] = "🔄 Restauration du backup local terminée avec succès !<br>✅ Éléments restaurés : " . implode(', ', $restored);
                            $_SESSION['backup_message_type'] = 'success';
                        } catch (Exception $e) {
                            $_SESSION['backup_message'] = "❌ Erreur lors de la restauration du backup local : " . $e->getMessage();
                            $_SESSION['backup_message_type'] = 'error';
                        }
                        // Nettoyer le dossier imports après restauration
                        $importsDir = "backup/$compagnieRef/imports";
                        if (is_dir($importsDir)) {
                            $files = array_diff(scandir($importsDir), array('.', '..'));
                            foreach ($files as $file) {
                                $filePath = $importsDir . "/" . $file;
                                if (is_file($filePath)) {
                                    @unlink($filePath);
                                }
                            }
                        }
                    }
                } else {
                    $_SESSION['backup_message'] = "❌ Échec de l'import du fichier. Veuillez réessayer.";
                    $_SESSION['backup_message_type'] = 'error';
                    // Nettoyer le dossier imports même en cas d'échec upload
                    $importsDir = "backup/$compagnieRef/imports";
                    if (is_dir($importsDir)) {
                        $files = array_diff(scandir($importsDir), array('.', '..'));
                        foreach ($files as $file) {
                            $filePath = $importsDir . "/" . $file;
                            if (is_file($filePath)) {
                                @unlink($filePath);
                            }
                        }
                    }
                }
            }
        } catch (Exception $e) {
            $_SESSION['backup_message'] = "❌ " . $e->getMessage();
            $_SESSION['backup_message_type'] = 'error';
        }
    }

    // Redirection POST/Redirect/GET
    header("Location: " . $_SERVER['PHP_SELF'] . "?action=completed");
    exit();
}

// Récupération du message depuis la session (après redirection GET)
if (isset($_GET['action']) && $_GET['action'] === 'completed') {
    if (isset($_SESSION['backup_message'])) {
        $message = $_SESSION['backup_message'];
        $messageType = $_SESSION['backup_message_type'];
        
        // Nettoyer la session pour éviter l'affichage répété
        unset($_SESSION['backup_message']);
        unset($_SESSION['backup_message_type']);
    }
}

// Fonction pour lister les backups existants séparément
function listBackupsByType($compagnieRef) {
    $backups = ['manuel' => [], 'auto' => [], 'temp' => []];
    $backupDir = "backup/$compagnieRef";
    
    if (is_dir($backupDir)) {
        $files = scandir($backupDir);
        foreach ($files as $file) {
            if ($file !== '.' && $file !== '..' && pathinfo($file, PATHINFO_EXTENSION) === 'zip') {
                $filePath = "$backupDir/$file";
                
                $backupData = [
                    'name' => $file,
                    'size' => filesize($filePath),
                    'date' => date('Y-m-d H:i:s', filemtime($filePath))
                ];
                
                // Séparer par type
                if (strpos($file, 'backup_manuel_') === 0) {
                    $backups['manuel'][] = $backupData;
                } elseif (strpos($file, 'backup_auto_') === 0) {
                    $backups['auto'][] = $backupData;
                }
            }
        }
        
        // Récupérer les backups temporaires
        $tempDir = "$backupDir/temp";
        if (is_dir($tempDir)) {
            $tempFiles = scandir($tempDir);
            foreach ($tempFiles as $file) {
                if ($file !== '.' && $file !== '..' && pathinfo($file, PATHINFO_EXTENSION) === 'zip') {
                    $filePath = "$tempDir/$file";
                    
                    if (strpos($file, 'backup_temp_avant_restauration_') === 0) {
                        $backups['temp'][] = [
                            'name' => $file,
                            'size' => filesize($filePath),
                            'date' => date('Y-m-d H:i:s', filemtime($filePath))
                        ];
                    }
                }
            }
        }
        
        // Trier par date (plus récent en premier)
        usort($backups['manuel'], function($a, $b) {
            return strcmp($b['date'], $a['date']);
        });
        usort($backups['auto'], function($a, $b) {
            return strcmp($b['date'], $a['date']);
        });
        usort($backups['temp'], function($a, $b) {
            return strcmp($b['date'], $a['date']);
        });
    }
    
    return $backups;
}

$compagnieRef = getCompagnieRef($pdo, $_SESSION['user_id']);
$backupsByType = $compagnieRef ? listBackupsByType($compagnieRef) : ['manuel' => [], 'auto' => [], 'temp' => []];
$compagnieLogs = $compagnieRef ? getCompagnieLogs($compagnieRef, 20) : [];
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <?php include('includes/head.php'); ?>
    <style>
        .backup-card {
            transition: all 0.3s ease;
            cursor: pointer;
        }
        .backup-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }
        .backup-btn {
            height: 80px;
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;
            border: none;
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            border-radius: 10px;
            width: 100%;
            font-size: 1.1rem;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        .backup-btn:hover {
            background: linear-gradient(135deg, #20c997 0%, #28a745 100%);
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(40, 167, 69, 0.3);
        }
        .backup-btn i {
            font-size: 1.5rem;
            margin-right: 10px;
        }
        .alert.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .alert.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .table-container {
            background: white;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
    </style>
</head>

<body id="page-top">
    <div id="wrapper">
        <!-- Sidebar -->
        <?php include('includes/sidebar.php'); ?>
        
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <!-- TopBar -->
                <?php include('includes/topbar.php'); ?>

                <!-- Container Fluid-->
                <div class="container-fluid" id="container-wrapper">
                    <div class="d-sm-flex align-items-center justify-content-between mb-4">
                        <h1 class="h3 mb-0 text-gray-800">Système de Backup</h1>
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="dashboard.php">Accueil</a></li>
                            <li class="breadcrumb-item active" aria-current="page">Backup</li>
                        </ol>
                    </div>

                    <?php if ($compagnieRef): ?>

                        <!-- Statistiques des backups -->
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <div class="card border-left-primary">
                                    <div class="card-body">
                                        <div class="row no-gutters align-items-center">
                                            <div class="col mr-2">
                                                <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                                    Backup Manuel</div>
                                                <div class="h5 mb-0 font-weight-bold text-gray-800">
                                                    <?php echo count($backupsByType['manuel']); ?>/1
                                                </div>
                                            </div>
                                            <div class="col-auto">
                                                <i class="fas fa-hand-paper fa-2x text-primary"></i>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="card border-left-success">
                                    <div class="card-body">
                                        <div class="row no-gutters align-items-center">
                                            <div class="col mr-2">
                                                <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                                    Backups Automatiques</div>
                                                <div class="h5 mb-0 font-weight-bold text-gray-800">
                                                    <?php echo count($backupsByType['auto']); ?>/5
                                                </div>
                                            </div>
                                            <div class="col-auto">
                                                <i class="fas fa-robot fa-2x text-success"></i>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Messages de succès/erreur -->
                        <?php if ($message): ?>
                            <div class="row mb-4">
                                <div class="col-12">
                                    <div class="alert alert-<?php echo $messageType === 'success' ? 'success' : 'danger'; ?> alert-dismissible fade show">
                                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                        <?php echo $message; ?>
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>


                        <!-- Bouton de backup et restauration locale -->
                        <div class="row mb-4">
                            <div class="col-md-8 offset-md-2">
                                <div class="card mb-4">
                                    <div class="card-body text-center p-4">
                                        <h5 class="mb-3">Créer un backup manuel</h5>
                                        <p class="text-muted mb-4">Sauvegarde la base de données et tous les fichiers dans un seul fichier ZIP</p>
                                        <button type="button" class="backup-btn" onclick="showBackupModal()">
                                            <i class="fas fa-cloud-download-alt"></i>
                                            <span>Lancer le Backup</span>
                                        </button>
                                    </div>
                                </div>
                                <div class="card">
                                    <div class="card-body text-center p-4">
                                        <h5 class="mb-3">Restaurer un backup depuis votre ordinateur</h5>
                                        <form method="POST" enctype="multipart/form-data" style="display:inline-block;" onsubmit="return confirm('Cette opération va remplacer toutes les données et fichiers actuels. Continuer ?');">
                                            <input type="hidden" name="action" value="restore_local">
                                            <input type="file" name="local_backup" accept=".zip" required class="form-control mb-2" style="max-width:300px;display:inline-block;">
                                            <button type="submit" class="btn btn-warning"><i class="fas fa-upload"></i> Importer & Restaurer</button>
                                        </form>
                                        <small class="text-muted d-block mt-2">Seuls les fichiers ZIP générés par le système sont acceptés.</small>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Barre de progression -->
                        <div class="row mb-4" id="progressContainer" style="display: none;">
                            <div class="col-12">
                                <div class="card">
                                    <div class="card-body">
                                        <h6 id="progressTitle">Progression de l'opération...</h6>
                                        <div class="progress mb-2" style="height: 25px;">
                                            <div class="progress-bar progress-bar-striped progress-bar-animated" 
                                                 id="progressBar" role="progressbar" style="width: 0%"
                                                 aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
                                                <span id="progressPercent">0%</span>
                                            </div>
                                        </div>
                                        <small id="progressText" class="text-muted">Préparation...</small>
                                    </div>
                                </div>
                            </div>                        </div>

                        <!-- Historique des backups -->
                        <!-- Backups Temporaires -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <div class="card shadow">
                                    <div class="card-header py-3 bg-warning">
                                        <h6 class="m-0 font-weight-bold text-white">
                                            <i class="fas fa-clock"></i> Backups Temporaires (Avant Restauration)
                                            <span class="badge badge-light ml-2"><?php echo count($backupsByType['temp']); ?>/1</span>
                                        </h6>
                                    </div>
                                    <div class="card-body">
                                        <?php if (empty($backupsByType['temp'])): ?>
                                            <div class="text-center text-muted py-5">
                                                <i class="fas fa-clock fa-4x mb-3 text-warning"></i>
                                                <h5>Aucun backup temporaire trouvé</h5>
                                                <p class="mb-0">Les backups temporaires sont créés automatiquement avant chaque restauration.</p>
                                                <small class="text-muted">Seul le dernier backup temporaire est conservé.</small>
                                            </div>
                                        <?php else: ?>
                                            <div class="table-responsive">
                                                <table class="table table-bordered table-hover">
                                                    <thead class="thead-light">
                                                        <tr>
                                                            <th><i class="fas fa-file-archive"></i> Fichier</th>
                                                            <th><i class="fas fa-weight-hanging"></i> Taille</th>
                                                            <th><i class="fas fa-calendar-alt"></i> Date de création</th>
                                                            <th><i class="fas fa-cogs"></i> Actions</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php foreach ($backupsByType['temp'] as $backup): ?>
                                                            <tr>
                                                                <td>
                                                                    <i class="fas fa-file-archive text-warning mr-2"></i>
                                                                    <strong><?php echo htmlspecialchars($backup['name']); ?></strong>
                                                                </td>
                                                                <td>
                                                                    <span class="badge badge-warning">
                                                                        <?php echo number_format($backup['size'] / 1024, 1); ?> KB
                                                                    </span>
                                                                </td>
                                                                <td>
                                                                    <i class="fas fa-clock text-muted mr-1"></i>
                                                                    <?php echo date('d/m/Y à H:i:s', strtotime($backup['date'])); ?>
                                                                </td>
                                                                <td>
                                                                    <a href="backup/<?php echo htmlspecialchars($compagnieRef); ?>/temp/<?php echo htmlspecialchars($backup['name']); ?>" 
                                                                       class="btn btn-primary btn-sm mr-1" download title="Télécharger">
                                                                        <i class="fas fa-download"></i> Télécharger
                                                                    </a>
                                                                    <button type="button" class="btn btn-warning btn-sm" 
                                                                            onclick="showRestoreModal('<?php echo htmlspecialchars($backup['name']); ?>', true)" title="Restaurer (sans créer de backup temp)">
                                                                        <i class="fas fa-undo"></i> Restaurer
                                                                    </button>
                                                                </td>
                                                            </tr>
                                                        <?php endforeach; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Backups Manuels -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <div class="card shadow">
                                    <div class="card-header py-3 bg-primary">
                                        <h6 class="m-0 font-weight-bold text-white">
                                            <i class="fas fa-hand-paper"></i> Backups Manuels 
                                            <span class="badge badge-light ml-2"><?php echo count($backupsByType['manuel']); ?>/1</span>
                                        </h6>
                                    </div>
                                    <div class="card-body">
                                        <?php if (empty($backupsByType['manuel'])): ?>
                                            <div class="text-center text-muted py-5">
                                                <i class="fas fa-hand-paper fa-4x mb-3 text-primary"></i>
                                                <h5>Aucun backup manuel trouvé</h5>
                                                <p class="mb-0">Créez votre premier backup manuel en cliquant sur le bouton ci-dessus.</p>
                                            </div>
                                        <?php else: ?>
                                            <div class="table-responsive">
                                                <table class="table table-bordered table-hover">
                                                    <thead class="thead-light">
                                                        <tr>
                                                            <th><i class="fas fa-file-archive"></i> Fichier</th>
                                                            <th><i class="fas fa-weight-hanging"></i> Taille</th>
                                                            <th><i class="fas fa-calendar-alt"></i> Date de création</th>
                                                            <th><i class="fas fa-cogs"></i> Actions</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php foreach ($backupsByType['manuel'] as $backup): ?>
                                                            <tr>
                                                                <td>
                                                                    <i class="fas fa-file-archive text-primary mr-2"></i>
                                                                    <strong><?php echo htmlspecialchars($backup['name']); ?></strong>
                                                                </td>
                                                                <td>
                                                                    <span class="badge badge-primary">
                                                                        <?php echo number_format($backup['size'] / 1024, 1); ?> KB
                                                                    </span>
                                                                </td>
                                                                <td>
                                                                    <i class="fas fa-clock text-muted mr-1"></i>
                                                                    <?php echo date('d/m/Y à H:i:s', strtotime($backup['date'])); ?>
                                                                </td>
                                                                <td>
                                                                    <a href="backup/<?php echo htmlspecialchars($compagnieRef); ?>/<?php echo htmlspecialchars($backup['name']); ?>" 
                                                                       class="btn btn-primary btn-sm mr-1" download title="Télécharger">
                                                                        <i class="fas fa-download"></i> Télécharger
                                                                    </a>
                                                                    <button type="button" class="btn btn-warning btn-sm" 
                                                                            onclick="showRestoreModal('<?php echo htmlspecialchars($backup['name']); ?>')" title="Restaurer">
                                                                        <i class="fas fa-undo"></i> Restaurer
                                                                    </button>
                                                                </td>
                                                            </tr>
                                                        <?php endforeach; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Backups Automatiques -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <div class="card shadow">
                                    <div class="card-header py-3 bg-success">
                                        <h6 class="m-0 font-weight-bold text-white">
                                            <i class="fas fa-robot"></i> Backups Automatiques 
                                            <span class="badge badge-light ml-2"><?php echo count($backupsByType['auto']); ?>/5</span>
                                        </h6>
                                    </div>
                                    <div class="card-body">
                                        <?php if (empty($backupsByType['auto'])): ?>
                                            <div class="text-center text-muted py-5">
                                                <i class="fas fa-robot fa-4x mb-3 text-success"></i>
                                                <h5>Aucun backup automatique trouvé</h5>
                                                <p class="mb-0">Les backups automatiques seront créés par le script de cron.</p>
                                                <small class="text-muted">Planification recommandée : tous les jours à 2h00</small>
                                            </div>
                                        <?php else: ?>
                                            <div class="table-responsive">
                                                <table class="table table-bordered table-hover">
                                                    <thead class="thead-light">
                                                        <tr>
                                                            <th><i class="fas fa-file-archive"></i> Fichier</th>
                                                            <th><i class="fas fa-weight-hanging"></i> Taille</th>
                                                            <th><i class="fas fa-calendar-alt"></i> Date de création</th>
                                                            <th><i class="fas fa-cogs"></i> Actions</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php foreach ($backupsByType['auto'] as $backup): ?>
                                                            <tr>
                                                                <td>
                                                                    <i class="fas fa-file-archive text-success mr-2"></i>
                                                                    <strong><?php echo htmlspecialchars($backup['name']); ?></strong>
                                                                </td>
                                                                <td>
                                                                    <span class="badge badge-success">
                                                                        <?php echo number_format($backup['size'] / 1024, 1); ?> KB
                                                                    </span>
                                                                </td>
                                                                <td>
                                                                    <i class="fas fa-clock text-muted mr-1"></i>
                                                                    <?php echo date('d/m/Y à H:i:s', strtotime($backup['date'])); ?>
                                                                </td>
                                                                <td>
                                                                    <a href="backup/<?php echo htmlspecialchars($compagnieRef); ?>/<?php echo htmlspecialchars($backup['name']); ?>" 
                                                                       class="btn btn-primary btn-sm mr-1" download title="Télécharger">
                                                                        <i class="fas fa-download"></i> Télécharger
                                                                    </a>
                                                                    <button type="button" class="btn btn-warning btn-sm" 
                                                                            onclick="showRestoreModal('<?php echo htmlspecialchars($backup['name']); ?>')" title="Restaurer">
                                                                        <i class="fas fa-undo"></i> Restaurer
                                                                    </button>
                                                                </td>
                                                            </tr>
                                                        <?php endforeach; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        <?php endif; ?>                                    </div>
                                </div>
                            </div>                        </div>

                        <!-- Section des logs de backup -->
                        <div class="row mt-4">
                            <div class="col-12">
                                <div class="card shadow mb-4">                                    <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                                        <h6 class="m-0 font-weight-bold text-primary">
                                            <i class="fas fa-history"></i> Journal de Backup / Restauration - <?php echo htmlspecialchars($compagnieRef); ?>
                                        </h6>
                                        <div class="dropdown no-arrow">
                                            <a class="dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                                <i class="fas fa-ellipsis-v fa-sm fa-fw text-gray-400"></i>
                                            </a>
                                            <div class="dropdown-menu dropdown-menu-right shadow animated--fade-in" aria-labelledby="dropdownMenuLink">
                                                <div class="dropdown-header">Actions:</div>
                                                <a class="dropdown-item" href="#" onclick="refreshLogs()">
                                                    <i class="fas fa-sync-alt fa-sm fa-fw mr-2 text-gray-400"></i>
                                                    Actualiser
                                                </a>
                                            </div>
                                        </div>
                                    </div><div class="card-body">
                                        <?php if (!empty($compagnieLogs)): ?>
                                            <div class="table-responsive" style="max-height: 400px; overflow-y: auto;">
                                                <table class="table table-bordered table-striped table-sm" width="100%" cellspacing="0">
                                                    <thead class="thead-dark" style="position: sticky; top: 0; z-index: 10;">
                                                        <tr>
                                                            <th style="width: 20%">Date/Heure</th>
                                                            <th style="width: 15%">Résultat</th>
                                                            <th style="width: 65%">Détails</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php foreach ($compagnieLogs as $log): ?>
                                                            <tr>
                                                                <td>
                                                                    <small class="text-muted">
                                                                        <?php 
                                                                        $datetime = DateTime::createFromFormat('Y-m-d H:i:s', $log['timestamp']);
                                                                        echo $datetime ? $datetime->format('d/m/Y H:i') : $log['timestamp'];
                                                                        ?>
                                                                    </small>
                                                                </td>
                                                                <td>
                                                                    <?php
                                                                    $badgeClass = 'secondary';
                                                                    $icon = 'info-circle';
                                                                    
                                                                    switch ($log['type']) {
                                                                        case 'SUCCESS':
                                                                            $badgeClass = 'success';
                                                                            $icon = 'check-circle';
                                                                            break;
                                                                        case 'ERROR':
                                                                            $badgeClass = 'danger';
                                                                            $icon = 'times-circle';
                                                                            break;
                                                                        case 'INFO':
                                                                            $badgeClass = 'info';
                                                                            $icon = 'info-circle';
                                                                            break;
                                                                    }
                                                                    ?>
                                                                    <span class="badge badge-<?php echo $badgeClass; ?> badge-pill">
                                                                        <i class="fas fa-<?php echo $icon; ?> fa-sm"></i>
                                                                        <?php echo $log['type'] == 'SUCCESS' ? 'Réussi' : ($log['type'] == 'ERROR' ? 'Échec' : 'Info'); ?>
                                                                    </span>
                                                                </td>
                                                                <td>
                                                                    <small><?php echo htmlspecialchars($log['message']); ?></small>
                                                                </td>
                                                            </tr>
                                                        <?php endforeach; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                            <div class="text-center mt-3">
                                                <small class="text-muted">
                                                    <i class="fas fa-info-circle"></i>
                                                    Affichage des 20 dernières opérations de backup/restauration
                                                </small>
                                            </div>
                                        <?php else: ?>
                                            <div class="text-center py-4">
                                                <i class="fas fa-file-alt fa-3x text-muted mb-3"></i>
                                                <h5 class="text-muted">Aucun historique disponible</h5>
                                                <p class="text-muted">
                                                    L'historique des opérations apparaîtra ici après le premier backup.
                                                </p>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>

                    <?php else: ?>
                        <div class="row">
                            <div class="col-12">
                                <div class="alert alert-warning">
                                    <h4 class="alert-heading"><i class="fas fa-exclamation-triangle"></i> Erreur</h4>
                                    <p>Impossible de récupérer la référence de votre compagnie.</p>
                                    <hr>
                                    <p class="mb-0">Veuillez contacter l'administrateur.</p>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>

                </div>
            </div>
            
            <!-- Footer -->
            <?php include('includes/footer.php'); ?>
        </div>
    </div>

    <!-- Modal de confirmation backup -->
    <div class="modal fade" id="backupModal" tabindex="-1" role="dialog" aria-labelledby="backupModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="backupModalLabel">
                        <i class="fas fa-cloud-download-alt"></i> Confirmation de backup
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-info">
                        <h6><i class="fas fa-info-circle"></i> Information</h6>
                        <p class="mb-0">Cette action va créer un nouveau backup manuel qui va :</p>
                        <ul class="mb-0 mt-2">
                            <li><strong>Remplacer</strong> l'ancien backup manuel s'il existe</li>
                            <li>Sauvegarder toute la base de données</li>
                            <li>Sauvegarder tous les fichiers</li>
                        </ul>
                    </div>
                    <p>Voulez-vous continuer ?</p>
                    <div class="text-center">
                        <p class="mb-0"><strong>Backups actuels :</strong></p>
                        <span class="badge badge-primary mr-2">Manuel: <?php echo count($backupsByType['manuel']); ?>/1</span>
                        <span class="badge badge-success">Auto: <?php echo count($backupsByType['auto']); ?>/5</span>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">
                        <i class="fas fa-times"></i> Annuler
                    </button>
                    <button type="button" class="btn btn-primary" onclick="startBackup()">
                        <i class="fas fa-cloud-download-alt"></i> Confirmer le backup
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal de restauration -->
    <div class="modal fade" id="restoreModal" tabindex="-1" role="dialog" aria-labelledby="restoreModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header bg-warning text-white">
                    <h5 class="modal-title" id="restoreModalLabel">
                        <i class="fas fa-exclamation-triangle"></i> Confirmation de restauration
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-warning">
                        <h6><i class="fas fa-exclamation-triangle"></i> Attention !</h6>
                        <p class="mb-0">Cette action va :</p>
                        <ul class="mb-0 mt-2">
                            <li>Remplacer toutes les données actuelles de la base</li>
                            <li>Restaurer tous les fichiers du backup</li>
                            <li><strong>Cette action est irréversible</strong></li>
                        </ul>
                    </div>
                    <p>Êtes-vous sûr de vouloir restaurer le backup :</p>
                    <p><strong id="backupFileName"></strong></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">
                        <i class="fas fa-times"></i> Annuler
                    </button>
                    <button type="button" class="btn btn-warning" onclick="startRestore()">
                        <i class="fas fa-undo"></i> Confirmer la restauration
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Formulaires cachés -->
    <form id="backupForm" method="POST" style="display: none;">
        <input type="hidden" name="action" value="backup_full">
    </form>
    
    <form id="restoreForm" method="POST" style="display: none;">
        <input type="hidden" name="action" value="restore">
        <input type="hidden" name="backup_file" id="backupFileInput">
    </form>

    <!-- Scroll to top -->
    <a class="scroll-to-top rounded" href="#page-top">
        <i class="fas fa-angle-up"></i>
    </a>

    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
    <script src="js/ruang-admin.min.js"></script>
    <script src="vendor/datatables/jquery.dataTables.min.js"></script>
    <script src="vendor/datatables/dataTables.bootstrap4.min.js"></script>
    
    <script>        // Affichage simple des modals
        function showBackupModal() { $('#backupModal').modal('show'); }
        function showRestoreModal(fileName, isFromTemp = false) {
            document.getElementById('backupFileName').textContent = fileName;
            document.getElementById('backupFileInput').value = fileName;
            let fromTempInput = document.getElementById('fromTempInput');
            if (!fromTempInput) {
                fromTempInput = document.createElement('input');
                fromTempInput.type = 'hidden';
                fromTempInput.id = 'fromTempInput';
                fromTempInput.name = 'from_temp';
                document.getElementById('restoreForm').appendChild(fromTempInput);
            }
            fromTempInput.value = isFromTemp ? '1' : '0';
            $('#restoreModal').modal('show');
        }

        // Soumission immédiate (pas de simulation JS) pour voir les erreurs serveur directement
        function startBackup() {
            $('#backupModal').modal('hide');
            document.getElementById('backupForm').submit();
        }
        function startRestore() {
            $('#restoreModal').modal('hide');
            document.getElementById('restoreForm').submit();
        }

        // Masquer la zone de progression si elle existe (plus utilisée)
        $(document).ready(function(){
            const pc = document.getElementById('progressContainer');
            if (pc) pc.style.display='none';
        });

        // Gestion des touches Escape pour fermer les modals
        $(document).keyup(function(e) {
            if (e.keyCode === 27) { // Escape key
                $('.modal').modal('hide');
            }
        });        // Animation des cartes au survol
        $('.backup-card').hover(
            function() {
                $(this).addClass('shadow-lg');
            },
            function() {
                $(this).removeClass('shadow-lg');
            }
        );

        // Fonction pour actualiser les logs
        function refreshLogs() {
            location.reload();
        }
    </script>
</body>
</html>
