<?php
// admin/backup_database.php
require_once '../includes/auth.php';

// Hanya admin yang bisa akses
if (!isAdmin()) {
    redirect('../login.php');
    exit;
}

// Buat folder backup di root (sejajar dengan folder admin, penguji, includes)
$root_dir = dirname(__DIR__); // Mengambil root directory
$backup_dir = $root_dir . '/backups/';

if (!file_exists($backup_dir)) {
    mkdir($backup_dir, 0755, true);
}

// Fungsi backup database
function backupDatabase($pdo, $backup_dir) {
    // Ambil semua tabel
    $stmt = $pdo->query("SHOW TABLES");
    $tables = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    if (empty($tables)) {
        return false;
    }
    
    // Nama file backup
    $date = date('Y-m-d_H-i-s');
    $filename = "backup_{$date}.sql";
    $filepath = $backup_dir . $filename;
    
    // Buka file untuk ditulis
    $handle = fopen($filepath, 'w');
    
    if (!$handle) {
        return false;
    }
    
    // Header backup
    fwrite($handle, "-- Backup Database - " . APP_NAME . "\n");
    fwrite($handle, "-- Generated: " . date('Y-m-d H:i:s') . "\n");
    fwrite($handle, "-- Database: " . $GLOBALS['dbname'] . "\n");
    fwrite($handle, "-- --------------------------------------------------------\n\n");
    
    fwrite($handle, "SET FOREIGN_KEY_CHECKS=0;\n\n");
    
    // Backup setiap tabel
    foreach ($tables as $table) {
        // Drop table statement
        fwrite($handle, "\n-- --------------------------------------------------------\n");
        fwrite($handle, "-- Struktur tabel: `{$table}`\n");
        fwrite($handle, "-- --------------------------------------------------------\n\n");
        fwrite($handle, "DROP TABLE IF EXISTS `{$table}`;\n\n");
        
        // Get create table statement
        $stmt = $pdo->query("SHOW CREATE TABLE `{$table}`");
        $create = $stmt->fetch(PDO::FETCH_ASSOC);
        fwrite($handle, $create['Create Table'] . ";\n\n");
        
        // Get data
        $stmt = $pdo->query("SELECT * FROM `{$table}`");
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (!empty($rows)) {
            fwrite($handle, "-- Data untuk tabel: `{$table}`\n");
            
            $columns = array_keys($rows[0]);
            $columns_escaped = array_map(function($col) {
                return "`" . str_replace("`", "``", $col) . "`";
            }, $columns);
            
            // Batch insert untuk performa lebih baik
            $batch_size = 100;
            $row_count = 0;
            
            foreach ($rows as $row) {
                if ($row_count % $batch_size == 0 && $row_count > 0) {
                    fwrite($handle, ";\n\n");
                }
                
                if ($row_count % $batch_size == 0) {
                    fwrite($handle, "INSERT INTO `{$table}` (" . implode(', ', $columns_escaped) . ") VALUES \n");
                } else {
                    fwrite($handle, ",\n");
                }
                
                $values = array_map(function($value) use ($pdo) {
                    if ($value === null) return 'NULL';
                    return "'" . str_replace("'", "''", $value) . "'";
                }, array_values($row));
                
                fwrite($handle, "(" . implode(', ', $values) . ")");
                $row_count++;
            }
            
            fwrite($handle, ";\n\n");
        }
    }
    
    fwrite($handle, "\nSET FOREIGN_KEY_CHECKS=1;\n");
    
    fclose($handle);
    
    // Kompres file jika fungsi gzopen tersedia
    $compressed = compressBackup($filepath, $backup_dir, $filename);
    
    return $compressed ?: $filename;
}

// Fungsi kompres backup
function compressBackup($filepath, $backup_dir, $filename) {
    if (function_exists('gzopen')) {
        $gz_filename = str_replace('.sql', '.sql.gz', $filename);
        $gz_filepath = $backup_dir . $gz_filename;
        
        $gz = gzopen($gz_filepath, 'wb9');
        if ($gz) {
            gzwrite($gz, file_get_contents($filepath));
            gzclose($gz);
            
            // Hapus file asli, simpan yang sudah dikompres
            unlink($filepath);
            return $gz_filename;
        }
    }
    return false;
}

// Fungsi hapus backup lama
function cleanOldBackups($backup_dir, $days = 30) {
    $files = glob($backup_dir . "backup_*.sql*");
    $now = time();
    $deleted = 0;
    
    foreach ($files as $file) {
        if (is_file($file)) {
            if ($now - filemtime($file) >= $days * 86400) {
                unlink($file);
                $deleted++;
            }
        }
    }
    return $deleted;
}

// Fungsi download backup
function downloadBackup($filename, $backup_dir) {
    $filepath = $backup_dir . $filename;
    
    if (file_exists($filepath)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filepath));
        readfile($filepath);
        exit;
    }
    return false;
}

// Fungsi restore database (opsional)
function restoreDatabase($pdo, $filepath) {
    // Baca file SQL
    $sql = file_get_contents($filepath);
    
    // Pisahkan query
    $queries = explode(";\n", $sql);
    
    $pdo->exec("SET FOREIGN_KEY_CHECKS=0");
    
    foreach ($queries as $query) {
        $query = trim($query);
        if (!empty($query) && !preg_match('/^--/', $query)) {
            try {
                $pdo->exec($query);
            } catch (PDOException $e) {
                // Log error tapi lanjutkan
                error_log("Restore error: " . $e->getMessage());
            }
        }
    }
    
    $pdo->exec("SET FOREIGN_KEY_CHECKS=1");
    return true;
}

// Proses request
$message = '';
$message_type = '';
$backup_files = [];

// Ambil daftar file backup
$backup_files = glob($backup_dir . "backup_*.sql*");
rsort($backup_files); // Urutkan dari terbaru

// Handle backup baru
if (isset($_POST['create_backup'])) {
    $result = backupDatabase($pdo, $backup_dir);
    if ($result) {
        $message = "Backup berhasil dibuat: " . htmlspecialchars($result);
        $message_type = "success";
        // Refresh daftar file
        $backup_files = glob($backup_dir . "backup_*.sql*");
        rsort($backup_files);
    } else {
        $message = "Gagal membuat backup! Pastikan folder 'backups' dapat ditulis.";
        $message_type = "error";
    }
}

// Handle download backup
if (isset($_GET['download'])) {
    $filename = basename($_GET['download']);
    downloadBackup($filename, $backup_dir);
    exit;
}

// Handle delete backup
if (isset($_GET['delete'])) {
    $filename = basename($_GET['delete']);
    $filepath = $backup_dir . $filename;
    if (file_exists($filepath)) {
        unlink($filepath);
        $message = "Backup dihapus: " . htmlspecialchars($filename);
        $message_type = "success";
        $backup_files = glob($backup_dir . "backup_*.sql*");
        rsort($backup_files);
    } else {
        $message = "File tidak ditemukan!";
        $message_type = "error";
    }
}

// Handle clean old backups
if (isset($_POST['clean_backups'])) {
    $days = intval($_POST['days'] ?? 30);
    $deleted = cleanOldBackups($backup_dir, $days);
    $message = "Berhasil menghapus $deleted backup yang lebih dari $days hari";
    $message_type = "success";
    $backup_files = glob($backup_dir . "backup_*.sql*");
    rsort($backup_files);
}

// Handle restore backup (opsional, hati-hati!)
if (isset($_POST['restore_backup']) && isset($_POST['restore_file'])) {
    $filename = basename($_POST['restore_file']);
    $filepath = $backup_dir . $filename;
    
    if (file_exists($filepath)) {
        // Cek apakah file terkompres
        if (pathinfo($filepath, PATHINFO_EXTENSION) == 'gz') {
            // Baca file gz
            $content = file_get_contents('compress.zlib://' . $filepath);
            $temp_file = $backup_dir . 'temp_restore.sql';
            file_put_contents($temp_file, $content);
            $result = restoreDatabase($pdo, $temp_file);
            unlink($temp_file);
        } else {
            $result = restoreDatabase($pdo, $filepath);
        }
        
        if ($result) {
            $message = "Database berhasil direstore dari: " . htmlspecialchars($filename);
            $message_type = "success";
        } else {
            $message = "Gagal merestore database!";
            $message_type = "error";
        }
    } else {
        $message = "File backup tidak ditemukan!";
        $message_type = "error";
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Backup Database - <?php echo APP_NAME; ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f0f2f5;
            min-height: 100vh;
        }
        
        /* Sidebar Styles */
        .sidebar {
            width: 280px;
            background: linear-gradient(135deg, #2c3e50 0%, #1a1a2e 100%);
            color: white;
            position: fixed;
            left: 0;
            top: 0;
            height: 100vh;
            overflow-y: auto;
            transition: all 0.3s;
            z-index: 100;
        }
        
        .sidebar-header {
            padding: 25px 20px;
            text-align: center;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }
        
        .sidebar-header h3 {
            font-size: 1.3rem;
            margin-bottom: 5px;
        }
        
        .sidebar-header p {
            font-size: 0.85rem;
            opacity: 0.7;
        }
        
        .sidebar-menu {
            padding: 20px 0;
        }
        
        .sidebar-menu a {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 25px;
            color: rgba(255,255,255,0.8);
            text-decoration: none;
            transition: all 0.3s;
            border-left: 3px solid transparent;
        }
        
        .sidebar-menu a:hover,
        .sidebar-menu a.active {
            background: rgba(255,255,255,0.1);
            border-left-color: #667eea;
            color: white;
        }
        
        .sidebar-menu a i {
            width: 20px;
        }
        
        /* Main Content */
        .main-content {
            margin-left: 280px;
            padding: 20px;
        }
        
        .top-bar {
            background: white;
            border-radius: 15px;
            padding: 15px 25px;
            margin-bottom: 25px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        
        .page-title h1 {
            font-size: 1.5rem;
            color: #2c3e50;
        }
        
        .page-title p {
            color: #6c757d;
            font-size: 0.85rem;
            margin-top: 5px;
        }
        
        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .user-name {
            font-weight: 600;
            color: #2c3e50;
        }
        
        .btn-logout {
            background: #dc3545;
            color: white;
            padding: 8px 16px;
            border-radius: 8px;
            text-decoration: none;
            font-size: 0.85rem;
            transition: all 0.3s;
        }
        
        .btn-logout:hover {
            background: #c82333;
        }
        
        .card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            overflow: hidden;
            margin-bottom: 20px;
        }
        
        .card-header {
            padding: 20px 25px;
            border-bottom: 1px solid #e9ecef;
        }
        
        .card-header h2 {
            font-size: 1.2rem;
            display: flex;
            align-items: center;
            gap: 10px;
            color: #2c3e50;
        }
        
        .card-body {
            padding: 25px;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            padding: 20px;
            border-radius: 12px;
            text-align: center;
            border: 1px solid #dee2e6;
        }
        
        .stat-number {
            font-size: 2rem;
            font-weight: bold;
            color: #667eea;
        }
        
        .stat-label {
            color: #6c757d;
            margin-top: 5px;
        }
        
        .btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            font-size: 0.9rem;
            cursor: pointer;
            text-decoration: none;
            transition: all 0.3s ease;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .btn-danger {
            background: #dc3545;
            color: white;
        }
        
        .btn-danger:hover {
            background: #c82333;
        }
        
        .btn-warning {
            background: #ffc107;
            color: #212529;
        }
        
        .btn-warning:hover {
            background: #e0a800;
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-sm {
            padding: 6px 12px;
            font-size: 0.8rem;
        }
        
        .alert {
            padding: 12px 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .alert-info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        
        .table-container {
            overflow-x: auto;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .data-table th,
        .data-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #e9ecef;
        }
        
        .data-table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #495057;
        }
        
        .data-table tr:hover {
            background: #f8f9fa;
        }
        
        .file-size {
            color: #6c757d;
            font-size: 0.85rem;
        }
        
        .action-buttons {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
        
        .form-inline {
            display: inline-flex;
            gap: 10px;
            align-items: center;
            flex-wrap: wrap;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-control {
            padding: 8px 12px;
            border: 1px solid #dee2e6;
            border-radius: 6px;
            width: 100%;
        }
        
        .clean-section {
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #e9ecef;
        }
        
        .info-box {
            margin-top: 30px;
            padding: 20px;
            background: #e7f3ff;
            border-radius: 12px;
        }
        
        .info-box h4 {
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .info-box ul {
            margin-left: 20px;
            line-height: 1.8;
        }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        
        .modal.show {
            display: flex;
        }
        
        .modal-content {
            background: white;
            border-radius: 15px;
            max-width: 500px;
            width: 90%;
            padding: 25px;
        }
        
        .modal-header {
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #e9ecef;
        }
        
        .modal-footer {
            margin-top: 20px;
            padding-top: 15px;
            border-top: 1px solid #e9ecef;
            display: flex;
            gap: 10px;
            justify-content: flex-end;
        }
        
        @media (max-width: 768px) {
            .sidebar {
                left: -280px;
            }
            
            .sidebar.show {
                left: 0;
            }
            
            .main-content {
                margin-left: 0;
            }
            
            .action-buttons {
                flex-direction: column;
            }
            
            .stats-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <!-- Sidebar -->
    <div class="sidebar">
        <div class="sidebar-header">
            <h3><?php echo APP_NAME; ?></h3>
            <p>Admin Panel</p>
        </div>
        <div class="sidebar-menu">
            <a href="dashboard.php">
                <i class="fas fa-tachometer-alt"></i> Dashboard
            </a>
            <a href="manage_ujian.php">
                <i class="fas fa-calendar-alt"></i> Kelola Ujian
            </a>
            <a href="manage_stations.php">
                <i class="fas fa-clinic-medical"></i> Kelola Station
            </a>
            <a href="manage_peserta.php">
                <i class="fas fa-users"></i> Kelola Peserta
            </a>
            <a href="manage_penguji.php">
                <i class="fas fa-user-tie"></i> Kelola Penguji
            </a>
            <a href="rekap_nilai.php">
                <i class="fas fa-chart-line"></i> Rekap Nilai
            </a>
            <a href="backup_database.php" class="active">
                <i class="fas fa-database"></i> Backup Database
            </a>
            <a href="../logout.php">
                <i class="fas fa-sign-out-alt"></i> Logout
            </a>
        </div>
    </div>
    
    <!-- Main Content -->
    <div class="main-content">
        <div class="top-bar">
            <div class="page-title">
                <h1><i class="fas fa-database"></i> Backup Database</h1>
                <p>Kelola backup database sistem OSCE/SOCA</p>
            </div>
            <div class="user-info">
                <span class="user-name"><i class="fas fa-user-shield"></i> <?php echo htmlspecialchars($_SESSION['user_name'] ?? 'Admin'); ?></span>
                <a href="../logout.php" class="btn-logout"><i class="fas fa-sign-out-alt"></i> Logout</a>
            </div>
        </div>
        
        <?php if ($message): ?>
            <div class="alert alert-<?php echo $message_type; ?>">
                <i class="fas <?php echo $message_type == 'success' ? 'fa-check-circle' : 'fa-exclamation-triangle'; ?>"></i>
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>
        
        <!-- Statistik -->
        <?php
        $total_backups = count($backup_files);
        $total_size = 0;
        foreach ($backup_files as $file) {
            $total_size += filesize($file);
        }
        $total_size_mb = round($total_size / 1048576, 2);
        $latest_backup = !empty($backup_files) ? $backup_files[0] : null;
        ?>
        
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-number"><?php echo $total_backups; ?></div>
                <div class="stat-label">Total Backup</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $total_size_mb; ?> MB</div>
                <div class="stat-label">Total Ukuran</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">
                    <?php
                    if ($latest_backup) {
                        echo date('d/m/Y H:i', filemtime($latest_backup));
                    } else {
                        echo '-';
                    }
                    ?>
                </div>
                <div class="stat-label">Backup Terakhir</div>
            </div>
        </div>
        
        <div class="card">
            <div class="card-header">
                <h2><i class="fas fa-plus-circle"></i> Buat Backup Baru</h2>
            </div>
            <div class="card-body">
                <form method="POST">
                    <button type="submit" name="create_backup" class="btn btn-primary">
                        <i class="fas fa-database"></i> Buat Backup Sekarang
                    </button>
                </form>
                <p style="margin-top: 10px; color: #6c757d; font-size: 0.85rem;">
                    <i class="fas fa-info-circle"></i> Backup akan disimpan dalam format .sql (atau .sql.gz jika kompresi tersedia)
                </p>
            </div>
        </div>
        
        <div class="card">
            <div class="card-header">
                <h2><i class="fas fa-file-archive"></i> Daftar Backup</h2>
            </div>
            <div class="card-body">
                <?php if (empty($backup_files)): ?>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i>
                        Belum ada file backup. Klik tombol "Buat Backup Sekarang" untuk memulai.
                    </div>
                <?php else: ?>
                    <div class="table-container">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Nama File</th>
                                    <th>Ukuran</th>
                                    <th>Tanggal Dibuat</th>
                                    <th>Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($backup_files as $file): ?>
                                    <?php
                                    $filename = basename($file);
                                    $size = filesize($file);
                                    $size_mb = round($size / 1048576, 2);
                                    $size_unit = $size_mb >= 1 ? $size_mb . ' MB' : round($size / 1024, 2) . ' KB';
                                    $modified = date('d/m/Y H:i:s', filemtime($file));
                                    $is_gz = pathinfo($filename, PATHINFO_EXTENSION) == 'gz';
                                    ?>
                                    <tr>
                                        <td>
                                            <i class="fas <?php echo $is_gz ? 'fa-file-archive' : 'fa-file-code'; ?>"></i>
                                            <?php echo htmlspecialchars($filename); ?>
                                        </td>
                                        <td class="file-size"><?php echo $size_unit; ?></td>
                                        <td><?php echo $modified; ?></td>
                                        <td class="action-buttons">
                                            <a href="?download=<?php echo urlencode($filename); ?>" class="btn btn-primary btn-sm">
                                                <i class="fas fa-download"></i> Download
                                            </a>
                                            <button onclick="showRestoreModal('<?php echo htmlspecialchars($filename); ?>')" class="btn btn-warning btn-sm">
                                                <i class="fas fa-undo-alt"></i> Restore
                                            </button>
                                            <a href="?delete=<?php echo urlencode($filename); ?>" 
                                               class="btn btn-danger btn-sm"
                                               onclick="return confirm('Yakin ingin menghapus backup <?php echo htmlspecialchars($filename); ?>?')">
                                                <i class="fas fa-trash"></i> Hapus
                                            </a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        
        <div class="card">
            <div class="card-header">
                <h2><i class="fas fa-broom"></i> Bersihkan Backup Lama</h2>
            </div>
            <div class="card-body">
                <form method="POST" class="form-inline">
                    <div class="form-group" style="display: inline-block; margin-right: 10px;">
                        <label style="display: inline-block; margin-right: 10px;">Hapus backup lebih dari</label>
                        <input type="number" name="days" value="30" min="1" style="width: 80px; padding: 8px;" class="form-control">
                        <span>hari</span>
                    </div>
                    <button type="submit" name="clean_backups" class="btn btn-secondary" onclick="return confirm('Yakin ingin menghapus backup lama?')">
                        <i class="fas fa-trash-alt"></i> Bersihkan
                    </button>
                </form>
                <p style="margin-top: 10px; color: #6c757d; font-size: 0.85rem;">
                    <i class="fas fa-info-circle"></i>
                    Backup otomatis dihapus setelah 30 hari secara default. Anda bisa mengubah jumlah hari di atas.
                </p>
            </div>
        </div>
        
        <div class="info-box">
            <h4><i class="fas fa-lightbulb"></i> Tips Penting:</h4>
            <ul>
                <li>Buat backup secara rutin, minimal 1 minggu sekali atau sebelum melakukan perubahan besar</li>
                <li>Download backup dan simpan di tempat yang aman (cloud storage, drive eksternal)</li>
                <li>Backup otomatis dihapus setelah 30 hari untuk menghemat ruang penyimpanan</li>
                <li>File backup bisa digunakan untuk restore database jika terjadi masalah atau kerusakan data</li>
                <li><strong>Peringatan:</strong> Fitur Restore akan menimpa data yang ada saat ini! Pastikan Anda telah membuat backup terbaru sebelum melakukan restore.</li>
            </ul>
        </div>
    </div>
    
    <!-- Modal Restore -->
    <div id="restoreModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3><i class="fas fa-exclamation-triangle"></i> Konfirmasi Restore Database</h3>
            </div>
            <div class="modal-body">
                <p><strong>Peringatan!</strong> Restore database akan menghapus semua data saat ini dan menggantinya dengan data dari file backup.</p>
                <p>Pastikan Anda:</p>
                <ul>
                    <li>Telah membuat backup terbaru dari data saat ini</li>
                    <li>File backup yang akan direstore valid</li>
                    <li>Memahami bahwa proses ini tidak dapat dibatalkan</li>
                </ul>
                <p>File backup: <strong id="restoreFileName"></strong></p>
            </div>
            <div class="modal-footer">
                <button onclick="closeRestoreModal()" class="btn btn-secondary">Batal</button>
                <form method="POST" id="restoreForm">
                    <input type="hidden" name="restore_file" id="restoreFileInput">
                                    <button type="submit" name="restore_backup" class="btn btn-danger">
                        <i class="fas fa-undo-alt"></i> Ya, Restore Sekarang
                    </button>
                </form>
            </div>
        </div>
    </div>
    
    <script>
        function showRestoreModal(filename) {
            document.getElementById('restoreFileName').textContent = filename;
            document.getElementById('restoreFileInput').value = filename;
            document.getElementById('restoreModal').classList.add('show');
        }
        
        function closeRestoreModal() {
            document.getElementById('restoreModal').classList.remove('show');
        }
        
        // Tutup modal jika klik di luar
        window.onclick = function(event) {
            const modal = document.getElementById('restoreModal');
            if (event.target === modal) {
                closeRestoreModal();
            }
        }
    </script>
</body>
</html>