<?php
/**
 * RESET DATABASE MODULE + BACKUP INTEGRATION
 * Dilengkapi dengan progress bar backup & reset dalam satu halaman
 */

// Aktifkan error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Mulai session
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ==============================================
// KONFIGURASI PATH
// ==============================================
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../includes/functions.php';

// Fungsi kompatibel untuk PHP 7
if (!function_exists('str_ends_with')) {
    function str_ends_with($haystack, $needle) {
        return substr($haystack, -strlen($needle)) === $needle;
    }
}

// Fungsi untuk mendapatkan NPSN dari database
function getNPSN($pdo) {
    try {
        $stmt = $pdo->query("SELECT npsn FROM pengaturan LIMIT 1");
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result && $result['npsn'] ? $result['npsn'] : 'NOSN';
    } catch (Exception $e) {
        return 'NOSN';
    }
}

// Fungsi untuk mendapatkan statistik tabel
function getTableStats($pdo) {
    $stats = [];
    $tables = ['siswa', 'guru', 'kelas', 'mata_pelajaran', 'nilai', 'absensi', 'users'];
    
    foreach ($tables as $table) {
        try {
            $stmt = $pdo->query("SHOW TABLES LIKE '$table'");
            if ($stmt->rowCount() > 0) {
                $count = $pdo->query("SELECT COUNT(*) FROM `$table`")->fetchColumn();
                $stats[$table] = $count;
            } else {
                $stats[$table] = 0;
            }
        } catch(PDOException $e) {
            $stats[$table] = 0;
        }
    }
    return $stats;
}

// ==================== PROSES BACKUP AJAX ====================
if (isset($_GET['ajax_backup']) && $_GET['ajax_backup'] == 1) {
    header('Content-Type: application/json');
    
    try {
        $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4", DB_USER, DB_PASS);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        $step = $_GET['step'] ?? '';
        $process_id = $_GET['process_id'] ?? session_id();
        
        if ($step == 'start') {
            $_SESSION['backup_progress_' . $process_id] = [
                'status' => 'processing',
                'percent' => 0,
                'message' => 'Memulai proses backup...'
            ];
            
            // Ambil semua tabel
            $tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
            $total_tables = count($tables);
            
            // Dapatkan NPSN
            $npsn = getNPSN($pdo);
            $date = date('Ymd');
            $time = date('His');
            $filename = "Backup_{$npsn}_{$date}_{$time}.sql";
            
            $sql_lines = [];
            $sql_lines[] = "-- Backup Database - Sebelum Reset";
            $sql_lines[] = "-- NPSN: $npsn";
            $sql_lines[] = "-- Tanggal: " . date('d/m/Y H:i:s');
            $sql_lines[] = "-- =========================================\n";
            $sql_lines[] = "SET NAMES utf8mb4;";
            $sql_lines[] = "SET FOREIGN_KEY_CHECKS=0;\n";
            
            $_SESSION['backup_progress_' . $process_id] = [
                'status' => 'processing',
                'percent' => 5,
                'message' => 'Mempersiapkan struktur backup...'
            ];
            
            $current_table = 0;
            $sql_content = implode("\n", $sql_lines);
            
            foreach ($tables as $table) {
                $current_table++;
                $percent = 5 + round(($current_table / $total_tables) * 70);
                
                $_SESSION['backup_progress_' . $process_id] = [
                    'status' => 'processing',
                    'percent' => $percent,
                    'current_table' => $table,
                    'message' => "Memproses tabel: $table ($current_table/$total_tables)"
                ];
                
                // DROP dan CREATE TABLE
                $create = $pdo->query("SHOW CREATE TABLE `$table`")->fetch(PDO::FETCH_NUM);
                $sql_content .= "\n-- --------------------------------------------------------\n";
                $sql_content .= "-- Tabel: `$table`\n";
                $sql_content .= "-- --------------------------------------------------------\n";
                $sql_content .= "DROP TABLE IF EXISTS `$table`;\n";
                $sql_content .= $create[1] . ";\n\n";
                
                // Ambil data
                $stmt = $pdo->query("SELECT * FROM `$table`");
                $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                if (!empty($rows)) {
                    $values = [];
                    foreach ($rows as $row) {
                        $escaped = [];
                        foreach ($row as $v) {
                            if ($v === null) {
                                $escaped[] = 'NULL';
                            } else {
                                $escaped[] = $pdo->quote($v);
                            }
                        }
                        $values[] = "(" . implode(", ", $escaped) . ")";
                    }
                    $sql_content .= "INSERT INTO `$table` VALUES \n" . implode(",\n", $values) . ";\n\n";
                }
                
                $_SESSION['backup_sql_' . $process_id] = $sql_content;
            }
            
            $sql_content .= "\nSET FOREIGN_KEY_CHECKS=1;\n";
            
            $_SESSION['backup_progress_' . $process_id] = [
                'status' => 'processing',
                'percent' => 85,
                'message' => 'Menyimpan file backup...'
            ];
            
            $_SESSION['backup_sql_' . $process_id] = $sql_content;
            $_SESSION['backup_filename_' . $process_id] = $filename;
            
            $_SESSION['backup_progress_' . $process_id] = [
                'status' => 'completed',
                'percent' => 100,
                'message' => 'Backup selesai! File siap diunduh.',
                'filename' => $filename
            ];
            
            echo json_encode(['success' => true, 'completed' => true, 'filename' => $filename]);
            exit;
        }
        
        $progress = $_SESSION['backup_progress_' . $process_id] ?? ['status' => 'initializing', 'percent' => 0, 'message' => 'Memulai...'];
        echo json_encode($progress);
        exit;
        
    } catch (Exception $e) {
        echo json_encode(['error' => $e->getMessage()]);
        exit;
    }
}

// ==================== DOWNLOAD BACKUP ====================
if (isset($_GET['download_backup']) && isset($_GET['process_id'])) {
    $process_id = $_GET['process_id'];
    if (isset($_SESSION['backup_sql_' . $process_id]) && isset($_SESSION['backup_filename_' . $process_id])) {
        $sql = $_SESSION['backup_sql_' . $process_id];
        $filename = $_SESSION['backup_filename_' . $process_id];
        
        unset($_SESSION['backup_sql_' . $process_id]);
        unset($_SESSION['backup_filename_' . $process_id]);
        unset($_SESSION['backup_progress_' . $process_id]);
        
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-Length: ' . strlen($sql));
        ob_clean();
        echo $sql;
        exit;
    }
}

// ==================== PROSES RESET AJAX ====================
if (isset($_GET['ajax_reset']) && $_GET['ajax_reset'] == 1) {
    header('Content-Type: application/json');
    
    $process_id = $_GET['process_id'] ?? session_id();
    $step = $_GET['step'] ?? '';
    
    if ($step == 'start') {
        try {
            $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4", DB_USER, DB_PASS);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            
            $_SESSION['reset_progress_' . $process_id] = [
                'status' => 'processing',
                'percent' => 0,
                'message' => 'Memulai proses reset database...'
            ];
            
            $pdo->exec("SET FOREIGN_KEY_CHECKS = 0");
            
            $tables = [
                'nilai_psaj' => 'Data Nilai PSAJ',
                'nilai_ekstra' => 'Data Nilai Ekstrakurikuler',
                'catatan_rapor' => 'Catatan Rapor',
                'absensi' => 'Data Absensi',
                'nilai' => 'Data Nilai',
                'bk_kelas' => 'Data BK Kelas',
                'pengampu' => 'Data Pengampu',
                'ekstrakurikuler' => 'Data Ekstrakurikuler',
                'dapodik_log' => 'Log Dapodik',
                'siswa' => 'Data Siswa',
                'guru' => 'Data Guru',
                'kelas' => 'Data Kelas',
                'mata_pelajaran' => 'Data Mata Pelajaran',
                'users' => 'Data Users',
                'pengaturan' => 'Data Pengaturan'
            ];
            
            $total_tables = count($tables);
            $current = 0;
            
            foreach ($tables as $table => $description) {
                $current++;
                $percent = round(($current / $total_tables) * 70);
                
                $_SESSION['reset_progress_' . $process_id] = [
                    'status' => 'processing',
                    'percent' => $percent,
                    'message' => "Mengosongkan $description..."
                ];
                
                $check = $pdo->query("SHOW TABLES LIKE '$table'");
                if ($check->rowCount() > 0) {
                    $pdo->exec("TRUNCATE TABLE `$table`");
                    $pdo->exec("ALTER TABLE `$table` AUTO_INCREMENT = 1");
                }
            }
            
            $_SESSION['reset_progress_' . $process_id] = [
                'status' => 'processing',
                'percent' => 75,
                'message' => 'Menyiapkan data default...'
            ];
            
            $check = $pdo->query("SHOW TABLES LIKE 'pengaturan'");
            if ($check->rowCount() > 0) {
                $count = $pdo->query("SELECT COUNT(*) FROM pengaturan")->fetchColumn();
                if ($count == 0) {
                    $pdo->exec("INSERT INTO `pengaturan` (`id`, `nama_sekolah`, `nss`, `npsn`, `alamat`, `kecamatan`, `telepon`, `email`, `website`, `logo_sekolah`, `kepala_sekolah`, `nip_kepsek`, `formula_rata_sumatif`, `formula_sts`, `formula_sas`, `formula_jumlah_sumatif`, `tahun_ajaran_aktif`, `semester_aktif`, `logo`, `updated_at`, `psaj_bobot_tertulis`, `psaj_bobot_praktik`, `psaj_bobot_proyek`, `psaj_bobot_portofolio`, `psaj_bobot_presentasi`, `dapodik_ip`, `dapodik_port`, `dapodik_token`) VALUES
                        (1, 'NAMA SEKOLAH', '', '', '', '', '', '', '', '', '', '', 50.00, 25.00, 25.00, 5, '2025/2026', '1', NULL, NOW(), 40.00, 20.00, 15.00, 15.00, 10.00, 'localhost', '5774', '')");
                }
            }
            
            $_SESSION['reset_progress_' . $process_id] = [
                'status' => 'processing',
                'percent' => 85,
                'message' => 'Membuat user admin default...'
            ];
            
            $check = $pdo->query("SELECT COUNT(*) FROM users WHERE username = 'admin'")->fetchColumn();
            if ($check == 0) {
                $hashed_password = password_hash('admin123', PASSWORD_DEFAULT);
                $pdo->exec("INSERT INTO `users` (`id`, `username`, `password`, `nama_lengkap`, `role`, `email`, `telepon`, `foto`, `status`, `created_at`, `updated_at`, `guru_id`) VALUES
                    (1, 'admin', '$hashed_password', 'Administrator', 'admin', NULL, NULL, NULL, 'aktif', NOW(), NOW(), NULL)");
            }
            
            $_SESSION['reset_progress_' . $process_id] = [
                'status' => 'processing',
                'percent' => 95,
                'message' => 'Finalisasi...'
            ];
            
            $pdo->exec("SET FOREIGN_KEY_CHECKS = 1");
            
            $_SESSION['reset_progress_' . $process_id] = [
                'status' => 'completed',
                'percent' => 100,
                'message' => 'Reset database berhasil diselesaikan!'
            ];
            
            echo json_encode(['success' => true, 'completed' => true]);
            exit;
            
        } catch(Exception $e) {
            if (isset($pdo)) $pdo->exec("SET FOREIGN_KEY_CHECKS = 1");
            echo json_encode(['error' => $e->getMessage()]);
            exit;
        }
    }
    
    $progress = $_SESSION['reset_progress_' . $process_id] ?? ['status' => 'initializing', 'percent' => 0, 'message' => 'Memulai...'];
    echo json_encode($progress);
    exit;
}

// Cek apakah user sudah memulai proses backup
$backup_started = isset($_GET['start_backup']) && $_GET['start_backup'] == 1;

// ==================== INFO DATABASE ====================
try {
    $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4", DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stats = getTableStats($pdo);
    $total_records = array_sum($stats);
    $npsn = getNPSN($pdo);
} catch (Exception $e) {
    $stats = [];
    $total_records = 0;
    $npsn = 'NOSN';
}

include '../../templates/header.php';
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reset Database + Backup Terintegrasi</title>
    <link rel="stylesheet" href="<?= BASE_URL ?>/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 { font-size: 28px; margin-bottom: 10px; }
        .header p { font-size: 14px; opacity: 0.9; }
        
        .content { padding: 30px; }
        
        /* Info Card Styles */
        .info-card {
            background: #e7f3ff;
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 25px;
            border-left: 5px solid #007bff;
        }
        
        .info-card h3 {
            color: #007bff;
            margin-bottom: 15px;
        }
        
        .info-card ul {
            margin-left: 20px;
            color: #333;
        }
        
        .info-card ul li {
            margin-bottom: 10px;
        }
        
        .warning-card {
            background: #fff3cd;
            border-left: 5px solid #ffc107;
            margin-bottom: 25px;
            padding: 20px;
            border-radius: 12px;
        }
        
        .warning-card h3 {
            color: #856404;
            margin-bottom: 10px;
        }
        
        .step-list {
            list-style: none;
            padding: 0;
        }
        
        .step-list li {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 12px;
            background: #f8f9fa;
            margin-bottom: 10px;
            border-radius: 8px;
        }
        
        .step-number {
            width: 35px;
            height: 35px;
            background: #007bff;
            color: white;
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
        }
        
        /* Progress Container Styles */
        .progress-container {
            background: #f8f9fa;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
            border: 2px solid #e9ecef;
        }
        
        .progress-header { text-align: center; margin-bottom: 20px; }
        .progress-header h3 { color: #333; margin-bottom: 10px; }
        
        .progress-bar-wrapper {
            background: #e9ecef;
            border-radius: 50px;
            overflow: hidden;
            height: 40px;
            margin: 20px 0;
        }
        
        .progress-bar-fill {
            background: linear-gradient(90deg, #28a745, #20c997);
            width: 0%;
            height: 100%;
            border-radius: 50px;
            transition: width 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: flex-end;
            padding-right: 15px;
            color: white;
            font-weight: bold;
            font-size: 14px;
        }
        
        .progress-percent {
            text-align: center;
            font-size: 24px;
            font-weight: bold;
            color: #28a745;
            margin: 15px 0;
        }
        
        .progress-status-card {
            background: #e7f3ff;
            border-radius: 10px;
            padding: 15px;
            margin-top: 20px;
        }
        
        .progress-status-item {
            display: flex;
            justify-content: space-between;
            padding: 8px;
            border-bottom: 1px solid #dee2e6;
        }
        
        .progress-status-item:last-child { border-bottom: none; }
        .progress-status-item .label { font-weight: 600; color: #495057; }
        .progress-status-item .value { color: #007bff; font-family: monospace; }
        
        .progress-icon { text-align: center; font-size: 50px; margin-bottom: 20px; }
        
        .danger-box {
            background: #f8d7da;
            border-left: 4px solid #dc3545;
            padding: 20px;
            margin-bottom: 25px;
            border-radius: 8px;
        }
        
        .danger-box h3 { color: #721c24; margin-bottom: 10px; }
        .danger-box ul { margin-left: 20px; color: #721c24; }
        .danger-box ul li { margin-bottom: 5px; }
        
        .stats-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 25px;
            background: #f8f9fa;
            border-radius: 8px;
            overflow: hidden;
        }
        
        .stats-table th, .stats-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #dee2e6;
        }
        
        .stats-table th { background: #dc3545; color: white; font-weight: 600; }
        
        .count-badge {
            display: inline-block;
            background: #28a745;
            color: white;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: bold;
        }
        
        .count-badge.warning { background: #dc3545; }
        
        .form-group { margin-bottom: 20px; }
        label { display: block; margin-bottom: 8px; font-weight: 600; color: #333; }
        
        input[type="text"] {
            width: 100%;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
        }
        
        input[type="text"]:focus { outline: none; border-color: #dc3545; }
        
        .button-group {
            display: flex;
            gap: 15px;
            margin-top: 25px;
        }
        
        .btn {
            flex: 1;
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }
        
        .btn:hover { transform: translateY(-2px); }
        
        .btn-danger {
            background: linear-gradient(135deg, #dc3545, #c82333);
            color: white;
        }
        
        .btn-danger:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
        }
        
        .btn-success {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #007bff, #0056b3);
            color: white;
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .info-box {
            background: #d1ecf1;
            border-left: 4px solid #17a2b8;
            padding: 15px;
            margin-top: 20px;
            border-radius: 8px;
        }
        
        .info-box p { margin: 5px 0; color: #0c5460; }
        
        .footer {
            background: #f8f9fa;
            padding: 20px;
            text-align: center;
            color: #6c757d;
            font-size: 12px;
        }
        
        .step-indicator {
            display: flex;
            justify-content: space-between;
            margin-bottom: 30px;
            padding: 0 20px;
        }
        
        .step {
            text-align: center;
            flex: 1;
            position: relative;
        }
        
        .step .step-circle {
            width: 40px;
            height: 40px;
            background: #dee2e6;
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            color: #6c757d;
        }
        
        .step.active .step-circle {
            background: #28a745;
            color: white;
        }
        
        .step.completed .step-circle {
            background: #28a745;
            color: white;
        }
        
        .step .step-label {
            font-size: 12px;
            margin-top: 8px;
            color: #6c757d;
        }
        
        .step.active .step-label { color: #28a745; font-weight: bold; }
        
        .result-container {
            text-align: center;
            padding: 20px;
        }
        
        .btn-download {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            padding: 12px 30px;
            border-radius: 50px;
            display: inline-block;
            margin: 20px 0;
            text-decoration: none;
        }
        
        .data-summary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 25px;
            display: flex;
            justify-content: space-around;
            text-align: center;
        }
        
        .data-summary-item {
            flex: 1;
        }
        
        .data-summary-number {
            font-size: 28px;
            font-weight: bold;
        }
        
        .data-summary-label {
            font-size: 12px;
            opacity: 0.8;
            margin-top: 5px;
        }
        
        @media (max-width: 768px) {
            .content { padding: 20px; }
            .button-group { flex-direction: column; }
            .step .step-label { font-size: 10px; }
            .data-summary { flex-direction: column; gap: 15px; }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1><i class="fas fa-trash-alt"></i> RESET DATABASE</h1>
        <p>Reset total database dengan backup otomatis - Aman & Terpercaya</p>
    </div>
    
    <div class="content">
        
        <?php if (!$backup_started && !isset($_GET['show_progress'])): ?>
        
        <!-- ==================== HALAMAN INFO AWAL ==================== -->
        
        <!-- Data Summary -->
        <div class="data-summary">
            <div class="data-summary-item">
                <div class="data-summary-number"><?= number_format($total_records) ?></div>
                <div class="data-summary-label">Total Data</div>
            </div>
            <div class="data-summary-item">
                <div class="data-summary-number"><?= date('d/m/Y') ?></div>
                <div class="data-summary-label">Tanggal</div>
            </div>
            <div class="data-summary-item">
                <div class="data-summary-number">NPSN: <?= htmlspecialchars($npsn) ?></div>
                <div class="data-summary-label">Nomor Pokok Sekolah</div>
            </div>
        </div>
        
        <!-- Info Card -->
        <div class="info-card">
            <h3><i class="fas fa-info-circle"></i> Panduan Reset Database</h3>
            <p>Reset database akan menghapus SEMUA data yang ada di sistem. Ikuti langkah-langkah berikut dengan seksama:</p>
        </div>
        
        <!-- Step List -->
        <ul class="step-list">
            <li>
                <span class="step-number">1</span>
                <span><strong>Klik tombol "Mulai Backup"</strong> - Sistem akan melakukan backup otomatis semua data database</span>
            </li>
            <li>
                <span class="step-number">2</span>
                <span><strong>Tunggu proses backup selesai</strong> - Progress bar akan menampilkan status backup</span>
            </li>
            <li>
                <span class="step-number">3</span>
                <span><strong>Download file backup</strong> - Simpan file backup (.sql) di tempat yang aman</span>
            </li>
            <li>
                <span class="step-number">4</span>
                <span><strong>Konfirmasi Reset</strong> - Ketik YES_RESET_ALL untuk mengaktifkan tombol reset</span>
            </li>
            <li>
                <span class="step-number">5</span>
                <span><strong>Klik "RESET SEMUA DATA"</strong> - Proses reset akan berjalan dan database menjadi seperti baru</span>
            </li>
        </ul>
        
        <!-- Warning Card -->
        <div class="warning-card">
            <h3><i class="fas fa-exclamation-triangle"></i> ⚠️ Peringatan Penting!</h3>
            <ul style="margin-left: 20px; margin-bottom: 0;">
                <li>Data yang sudah dihapus <strong>TIDAK DAPAT DIKEMBALIKAN</strong> tanpa backup</li>
                <li>Pastikan Anda <strong>menyimpan file backup</strong> sebelum melanjutkan reset</li>
                <li>Reset hanya boleh dilakukan oleh <strong>Administrator</strong></li>
                <li>Setelah reset, semua pengaturan akan kembali ke <strong>default</strong></li>
            </ul>
        </div>
        
        <!-- Statistik Data yang Akan Dihapus -->
        <h3 style="margin-bottom: 15px;"><i class="fas fa-chart-bar"></i> 📊 Data yang Akan Dihapus</h3>
        <table class="stats-table">
            <thead>
                <tr>
                    <th>No</th>
                    <th>Tabel</th>
                    <th>Deskripsi</th>
                    <th>Jumlah Data</th>
                </tr>
            </thead>
            <tbody>
                <tr><td>1</td><td><code>siswa</code></td><td>Data Siswa (Master)</td>
                    <td><span class="count-badge <?php echo ($stats['siswa'] ?? 0) > 0 ? 'warning' : ''; ?>"><?php echo number_format($stats['siswa'] ?? 0); ?> record</span></td></tr>
                <tr><td>2</td><td><code>guru</code></td><td>Data Guru (Master)</td>
                    <td><span class="count-badge <?php echo ($stats['guru'] ?? 0) > 0 ? 'warning' : ''; ?>"><?php echo number_format($stats['guru'] ?? 0); ?> record</span></td></tr>
                <tr><td>3</td><td><code>kelas</code></td><td>Data Kelas (Master)</td>
                    <td><span class="count-badge <?php echo ($stats['kelas'] ?? 0) > 0 ? 'warning' : ''; ?>"><?php echo number_format($stats['kelas'] ?? 0); ?> record</span></td></tr>
                <tr><td>4</td><td><code>mata_pelajaran</code></td><td>Data Mata Pelajaran (Master)</td>
                    <td><span class="count-badge <?php echo ($stats['mata_pelajaran'] ?? 0) > 0 ? 'warning' : ''; ?>"><?php echo number_format($stats['mata_pelajaran'] ?? 0); ?> record</span></td></tr>
                <tr><td>5</td><td><code>nilai</code></td><td>Data Nilai (Transaksional)</td>
                    <td><span class="count-badge <?php echo ($stats['nilai'] ?? 0) > 0 ? 'warning' : ''; ?>"><?php echo number_format($stats['nilai'] ?? 0); ?> record</span></td></tr>
                <tr><td>6</td><td><code>absensi</code></td><td>Data Absensi (Transaksional)</td>
                    <td><span class="count-badge <?php echo ($stats['absensi'] ?? 0) > 0 ? 'warning' : ''; ?>"><?php echo number_format($stats['absensi'] ?? 0); ?> record</span></td></tr>
                <tr><td>7</td><td><code>users</code></td><td>Data User (Akan direset ke default)</td>
                    <td><span class="count-badge warning"><?php echo number_format($stats['users'] ?? 0); ?> record</span></td></tr>
            </tbody>
            <tfoot>
                <tr style="background: #f8d7da; font-weight: bold;">
                    <td colspan="3" style="text-align: right;">TOTAL SELURUH DATA:</td>
                    <td><span class="count-badge warning"><?php echo number_format($total_records); ?> record</span></td>
                </tr>
            </tfoot>
        </table>
        
        <!-- Tombol Mulai Backup -->
        <div class="button-group">
            <a href="?start_backup=1" class="btn btn-primary">
                <i class="fas fa-database"></i> 🚀 Mulai Backup & Reset
            </a>
            <a href="<?= BASE_URL ?>/index.php" class="btn btn-secondary">
                <i class="fas fa-times"></i> ❌ Batal
            </a>
        </div>
        
        <div class="info-box" style="margin-top: 20px;">
            <p><strong><i class="fas fa-question-circle"></i> Perlu bantuan?</strong></p>
            <p>Pastikan Anda sudah memahami risiko reset database. Jika ragu, konsultasikan dengan administrator.</p>
        </div>
        
        <?php elseif ($backup_started || isset($_GET['show_progress'])): ?>
        
        <!-- ==================== PROGRESS BACKUP & RESET ==================== -->
        
        <!-- Step Indicator -->
        <div class="step-indicator" id="stepIndicator">
            <div class="step" id="step1">
                <div class="step-circle">1</div>
                <div class="step-label">Backup Database</div>
            </div>
            <div class="step" id="step2">
                <div class="step-circle">2</div>
                <div class="step-label">Reset Database</div>
            </div>
            <div class="step" id="step3">
                <div class="step-circle">3</div>
                <div class="step-label">Selesai</div>
            </div>
        </div>
        
        <!-- Backup Progress Container -->
        <div id="backupContainer" class="progress-container">
            <div class="progress-icon">
                <i class="fas fa-database fa-3x" style="color: #28a745;"></i>
            </div>
            <div class="progress-header">
                <h3>📦 Backup Database - Tahap 1 dari 2</h3>
                <p>Membackup data sebelum reset... (WAJIB)</p>
            </div>
            <div class="progress-bar-wrapper">
                <div class="progress-bar-fill" id="backupProgressBar">
                    <span id="backupProgressText">0%</span>
                </div>
            </div>
            <div class="progress-percent" id="backupPercentDisplay">0%</div>
            <div class="progress-status-card">
                <div class="progress-status-item">
                    <span class="label"><i class="fas fa-info-circle"></i> Status:</span>
                    <span class="value" id="backupStatusLabel">Memulai...</span>
                </div>
                <div class="progress-status-item">
                    <span class="label"><i class="fas fa-table"></i> Tabel Diproses:</span>
                    <span class="value" id="backupCurrentTable">-</span>
                </div>
                <div class="progress-status-item">
                    <span class="label"><i class="fas fa-comment"></i> Pesan:</span>
                    <span class="value" id="backupMessage">-</span>
                </div>
            </div>
        </div>
        
        <!-- Reset Progress Container (Awalnya hidden) -->
        <div id="resetContainer" class="progress-container" style="display: none;">
            <div class="progress-icon">
                <i class="fas fa-trash-alt fa-3x" style="color: #dc3545;"></i>
            </div>
            <div class="progress-header">
                <h3>🔄 Reset Database - Tahap 2 dari 2</h3>
                <p>Menghapus semua data... (Proses tidak dapat dibatalkan)</p>
            </div>
            <div class="progress-bar-wrapper">
                <div class="progress-bar-fill" id="resetProgressBar">
                    <span id="resetProgressText">0%</span>
                </div>
            </div>
            <div class="progress-percent" id="resetPercentDisplay">0%</div>
            <div class="progress-status-card">
                <div class="progress-status-item">
                    <span class="label"><i class="fas fa-info-circle"></i> Status:</span>
                    <span class="value" id="resetStatusLabel">Memulai...</span>
                </div>
                <div class="progress-status-item">
                    <span class="label"><i class="fas fa-comment"></i> Pesan:</span>
                    <span class="value" id="resetMessage">-</span>
                </div>
            </div>
        </div>
        
        <!-- Result Container -->
        <div id="resultContainer" style="display: none;">
            <div class="result-container">
                <i class="fas fa-check-circle" style="font-size: 60px; color: #28a745;"></i>
                <h3 style="margin: 20px 0;">✅ Proses Selesai!</h3>
                <p id="resultMessage"></p>
                <a href="#" id="downloadBackupLink" class="btn-download">
                    <i class="fas fa-download"></i> Download File Backup
                </a>
                <div style="margin-top: 20px; display: flex; gap: 10px; justify-content: center;">
                    <a href="reset.php" class="btn btn-secondary">Reset Lagi</a>
                    <a href="<?= BASE_URL ?>/index.php" class="btn btn-success">Kembali ke Dashboard</a>
                </div>
            </div>
        </div>
        
        <!-- Form Reset (Awalnya hidden, muncul setelah backup selesai) -->
        <div id="resetFormContainer" style="display: none;">
            <div class="danger-box">
                <h3><i class="fas fa-exclamation-triangle"></i> 🔴 PERINGATAN SUPER PENTING!</h3>
                <ul>
                    <li><strong>SEMUA DATA akan dihapus</strong> termasuk data master</li>
                    <li>Data yang dihapus <strong>TIDAK DAPAT DIKEMBALIKAN</strong> kecuali dari backup</li>
                    <li>Database akan menjadi <strong>SEPERTI BARU</strong></li>
                    <li>Aksi ini <strong>TIDAK DAPAT DIBATALKAN</strong></li>
                </ul>
            </div>
            
            <div class="info-box">
                <p><strong><i class="fas fa-check-circle"></i> ✅ Backup telah berhasil dilakukan!</strong></p>
                <p>Silakan konfirmasi untuk melanjutkan ke proses RESET DATABASE.</p>
            </div>
            
            <div class="form-group">
                <label>Ketik <strong style="color: #dc3545;">YES_RESET_ALL</strong> untuk mengkonfirmasi reset total database:</label>
                <input type="text" id="confirmReset" placeholder="Ketik YES_RESET_ALL di sini" autocomplete="off">
            </div>
            
            <div class="button-group">
                <button type="button" class="btn btn-danger" id="executeResetBtn" disabled>
                    <i class="fas fa-trash-alt"></i> 🔥 RESET SEMUA DATA
                </button>
                <button type="button" class="btn btn-secondary" onclick="window.location.href='reset.php'">
                    <i class="fas fa-times"></i> ❌ Batal
                </button>
            </div>
        </div>
        
        <?php endif; ?>
        
    </div>
    
    <div class="footer">
        <p><i class="fas fa-shield-alt"></i> Backup otomatis dilakukan sebelum reset - Data aman!</p>
    </div>
</div>

<?php if ($backup_started || isset($_GET['show_progress'])): ?>
<script>
// Variabel global
let backupProcessId = 'backup_' + Date.now();
let resetProcessId = 'reset_' + Date.now();
let backupInterval;
let resetInterval;
let isBackupCompleted = false;
let isResetCompleted = false;
let backupFilename = '';

// ==================== PROSES BACKUP ====================
function updateBackupProgress() {
    if (isBackupCompleted) return;
    
    fetch(`reset.php?ajax_backup=1&process_id=${backupProcessId}&step=check&t=${Date.now()}`)
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                console.error('Error:', data.error);
                return;
            }
            
            const percent = data.percent || 0;
            const progressBar = document.getElementById('backupProgressBar');
            const progressText = document.getElementById('backupProgressText');
            const percentDisplay = document.getElementById('backupPercentDisplay');
            const statusLabel = document.getElementById('backupStatusLabel');
            const currentTable = document.getElementById('backupCurrentTable');
            const messageSpan = document.getElementById('backupMessage');
            
            if (progressBar) progressBar.style.width = percent + '%';
            if (progressText) progressText.innerHTML = percent + '%';
            if (percentDisplay) percentDisplay.innerHTML = percent + '%';
            
            if (data.status === 'processing') {
                if (statusLabel) {
                    statusLabel.innerHTML = '<i class="fas fa-spinner fa-pulse"></i> Sedang diproses';
                    statusLabel.style.color = '#ffc107';
                }
                if (currentTable && data.current_table) currentTable.innerHTML = data.current_table;
                if (messageSpan && data.message) messageSpan.innerHTML = data.message;
            } else if (data.status === 'completed') {
                isBackupCompleted = true;
                clearInterval(backupInterval);
                backupFilename = data.filename;
                
                if (statusLabel) {
                    statusLabel.innerHTML = '<i class="fas fa-check-circle"></i> Backup Selesai!';
                    statusLabel.style.color = '#28a745';
                }
                if (messageSpan && data.message) messageSpan.innerHTML = data.message;
                
                // Update step indicator
                document.getElementById('step1').classList.add('completed');
                document.getElementById('step2').classList.add('active');
                
                // Tampilkan form reset
                setTimeout(() => {
                    document.getElementById('backupContainer').style.display = 'none';
                    document.getElementById('resetFormContainer').style.display = 'block';
                }, 500);
            } else if (data.status === 'error') {
                isBackupCompleted = true;
                clearInterval(backupInterval);
                if (statusLabel) {
                    statusLabel.innerHTML = '<i class="fas fa-times-circle"></i> Error';
                    statusLabel.style.color = '#dc3545';
                }
                if (messageSpan && data.message) messageSpan.innerHTML = data.message;
            }
        })
        .catch(error => console.error('Fetch error:', error));
}

function startBackup() {
    fetch(`reset.php?ajax_backup=1&process_id=${backupProcessId}&step=start&t=${Date.now()}`)
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                document.getElementById('backupMessage').innerHTML = 'Error: ' + data.error;
                return;
            }
            backupInterval = setInterval(updateBackupProgress, 500);
        })
        .catch(error => console.error('Start fetch error:', error));
}

// ==================== PROSES RESET ====================
function updateResetProgress() {
    if (isResetCompleted) return;
    
    fetch(`reset.php?ajax_reset=1&process_id=${resetProcessId}&step=check&t=${Date.now()}`)
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                console.error('Error:', data.error);
                return;
            }
            
            const percent = data.percent || 0;
            const progressBar = document.getElementById('resetProgressBar');
            const progressText = document.getElementById('resetProgressText');
            const percentDisplay = document.getElementById('resetPercentDisplay');
            const statusLabel = document.getElementById('resetStatusLabel');
            const messageSpan = document.getElementById('resetMessage');
            
            if (progressBar) progressBar.style.width = percent + '%';
            if (progressText) progressText.innerHTML = percent + '%';
            if (percentDisplay) percentDisplay.innerHTML = percent + '%';
            
            if (data.status === 'processing') {
                if (statusLabel) {
                    statusLabel.innerHTML = '<i class="fas fa-spinner fa-pulse"></i> Sedang diproses';
                    statusLabel.style.color = '#ffc107';
                }
                if (messageSpan && data.message) messageSpan.innerHTML = data.message;
            } else if (data.status === 'completed') {
                isResetCompleted = true;
                clearInterval(resetInterval);
                
                if (statusLabel) {
                    statusLabel.innerHTML = '<i class="fas fa-check-circle"></i> Selesai!';
                    statusLabel.style.color = '#28a745';
                }
                if (messageSpan && data.message) messageSpan.innerHTML = data.message;
                
                // Update step indicator
                document.getElementById('step2').classList.add('completed');
                document.getElementById('step3').classList.add('active');
                
                setTimeout(() => {
                    document.getElementById('resetContainer').style.display = 'none';
                    document.getElementById('resultContainer').style.display = 'block';
                    
                    let resultHtml = `Reset database berhasil diselesaikan!<br><br>
                        Database sekarang kosong dan siap digunakan untuk sekolah baru.<br><br>
                        <strong>Informasi Login Default:</strong><br>
                        Username: <code>admin</code><br>
                        Password: <code>admin123</code><br><br>
                        File backup: <strong><code>${backupFilename}</code></strong>`;
                    
                    document.getElementById('resultMessage').innerHTML = resultHtml;
                    document.getElementById('downloadBackupLink').href = `reset.php?download_backup=1&process_id=${backupProcessId}`;
                }, 500);
            } else if (data.status === 'error') {
                isResetCompleted = true;
                clearInterval(resetInterval);
                if (statusLabel) {
                    statusLabel.innerHTML = '<i class="fas fa-times-circle"></i> Error';
                    statusLabel.style.color = '#dc3545';
                }
                if (messageSpan && data.message) messageSpan.innerHTML = data.message;
            }
        })
        .catch(error => console.error('Fetch error:', error));
}

function startReset() {
    document.getElementById('resetFormContainer').style.display = 'none';
    document.getElementById('resetContainer').style.display = 'block';
    
    fetch(`reset.php?ajax_reset=1&process_id=${resetProcessId}&step=start&t=${Date.now()}`)
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                document.getElementById('resetMessage').innerHTML = 'Error: ' + data.error;
                return;
            }
            resetInterval = setInterval(updateResetProgress, 500);
        })
        .catch(error => console.error('Start fetch error:', error));
}

// ==================== EVENT HANDLER ====================
document.addEventListener('DOMContentLoaded', function() {
    // Mulai backup otomatis saat halaman dimuat (setelah user klik Mulai Backup)
    startBackup();
    
    // Validasi input konfirmasi reset
    const confirmInput = document.getElementById('confirmReset');
    const resetBtn = document.getElementById('executeResetBtn');
    
    if (confirmInput) {
        confirmInput.addEventListener('input', function(e) {
            this.value = this.value.toUpperCase();
            if (this.value === 'YES_RESET_ALL') {
                resetBtn.disabled = false;
                resetBtn.style.opacity = '1';
            } else {
                resetBtn.disabled = true;
                resetBtn.style.opacity = '0.5';
            }
        });
    }
    
    if (resetBtn) {
        resetBtn.addEventListener('click', function() {
            let confirmValue = document.getElementById('confirmReset').value;
            if (confirmValue !== 'YES_RESET_ALL') {
                alert('Harap ketik "YES_RESET_ALL" untuk mengkonfirmasi reset total database!');
                return;
            }
            
            let confirmationMessage = '⚠️ PERINGATAN SUPER PENTING! ⚠️\n\n';
            confirmationMessage += 'Anda akan menghapus SEMUA DATA.\n\n';
            confirmationMessage += 'Data yang dihapus TIDAK DAPAT DIKEMBALIKAN!\n\n';
            confirmationMessage += 'Apakah Anda YAKIN ingin melanjutkan?\n';
            confirmationMessage += 'Klik OK untuk melanjutkan, CANCEL untuk membatalkan.';
            
            if (confirm(confirmationMessage)) {
                startReset();
            }
        });
    }
});
</script>
<?php endif; ?>

</body>
</html>