<?php
/**
 * SisPen Snesaka - Backup & Restore Database
 * Dilengkapi dengan Progress Bar (Kompatibel PHP 7.x)
 */
require_once '../../includes/functions.php';
requireAdmin();

$pageTitle  = 'Backup & Restore';
$activeMenu = 'backup';

$dbHost = DB_HOST ?? 'localhost';
$dbUser = DB_USER ?? 'root';
$dbPass = DB_PASS ?? '';
$dbName = DB_NAME ?? 'sispenra';

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

if (!function_exists('str_starts_with')) {
    function str_starts_with($haystack, $needle) {
        return substr($haystack, 0, 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';
    }
}

// ==================== PROSES RESTORE AJAX (DILUAR action=backup) ====================
if (isset($_GET['ajax_restore']) && $_GET['ajax_restore'] == 1) {
    header('Content-Type: application/json');
    
    try {
        $pdo = new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf8mb4", $dbUser, $dbPass);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        $step = $_GET['step'] ?? '';
        $process_id = $_GET['process_id'] ?? session_id();
        
        if ($step == 'start') {
            $_SESSION['restore_progress_' . $process_id] = [
                'status' => 'processing',
                'percent' => 0,
                'message' => 'Memulai proses restore...'
            ];
            
            // Ambil file yang diupload dari session
            if (!isset($_SESSION['restore_sql_content_' . $process_id])) {
                throw new Exception('Tidak ada file SQL yang diupload.');
            }
            
            $sql = $_SESSION['restore_sql_content_' . $process_id];
            
            $_SESSION['restore_progress_' . $process_id] = [
                'status' => 'processing',
                'percent' => 10,
                'message' => 'Memproses file SQL...'
            ];
            
            // Split SQL statements
            $pdo->exec("SET FOREIGN_KEY_CHECKS=0");
            
            // Parse statements dengan lebih baik
            $statements = [];
            $current_stmt = '';
            $lines = explode("\n", $sql);
            $total_lines = count($lines);
            
            foreach ($lines as $index => $line) {
                $line = trim($line);
                if (empty($line) || str_starts_with($line, '--')) {
                    continue;
                }
                
                $current_stmt .= $line . "\n";
                
                if (substr(trim($line), -1) === ';') {
                    $stmt = trim($current_stmt);
                    if (!empty($stmt)) {
                        $statements[] = rtrim($stmt, ';');
                    }
                    $current_stmt = '';
                }
                
                // Update progress parsing
                if ($index % 100 == 0 && $total_lines > 0) {
                    $percent = 10 + round(($index / $total_lines) * 20);
                    $_SESSION['restore_progress_' . $process_id] = [
                        'status' => 'processing',
                        'percent' => $percent,
                        'message' => "Memparsing file SQL... (" . round(($index/$total_lines)*100) . "%)"
                    ];
                }
            }
            
            if (!empty($current_stmt)) {
                $stmt = trim($current_stmt);
                if (!empty($stmt)) {
                    $statements[] = rtrim($stmt, ';');
                }
            }
            
            $total_statements = count($statements);
            $_SESSION['restore_progress_' . $process_id] = [
                'status' => 'processing',
                'percent' => 30,
                'message' => "Menjalankan $total_statements perintah SQL..."
            ];
            
            $success_count = 0;
            $error_count = 0;
            $errors = [];
            
            for ($i = 0; $i < $total_statements; $i++) {
                $stmt = $statements[$i];
                if (empty(trim($stmt))) continue;
                
                $percent = 30 + round(($i / $total_statements) * 65);
                $_SESSION['restore_progress_' . $process_id] = [
                    'status' => 'processing',
                    'percent' => $percent,
                    'message' => "Menjalankan query " . ($i + 1) . " dari $total_statements..."
                ];
                
                try {
                    $pdo->exec($stmt);
                    $success_count++;
                } catch (PDOException $e) {
                    $error_count++;
                    $errors[] = "Error pada query ke-" . ($i + 1) . ": " . substr($e->getMessage(), 0, 150);
                }
            }
            
            $pdo->exec("SET FOREIGN_KEY_CHECKS=1");
            
            // Hapus SQL content dari session
            unset($_SESSION['restore_sql_content_' . $process_id]);
            
            $_SESSION['restore_progress_' . $process_id] = [
                'status' => 'completed',
                'percent' => 100,
                'message' => "Restore selesai! $success_count query berhasil, $error_count error.",
                'success_count' => $success_count,
                'error_count' => $error_count,
                'errors' => $errors
            ];
            
            echo json_encode(['success' => true, 'completed' => true]);
            exit;
        }
        
        // Return progress
        $progress = $_SESSION['restore_progress_' . $process_id] ?? ['status' => 'initializing', 'percent' => 0, 'message' => 'Memulai...'];
        echo json_encode($progress);
        exit;
        
    } catch (Exception $e) {
        echo json_encode(['error' => $e->getMessage()]);
        exit;
    }
}

// ==================== PROSES BACKUP ====================
if (isset($_GET['action']) && $_GET['action'] === 'backup') {
    
    // AJAX untuk progress backup
    if (isset($_GET['ajax']) && $_GET['ajax'] == 1) {
        header('Content-Type: application/json');
        
        try {
            $pdo = new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf8mb4", $dbUser, $dbPass);
            $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 SisPen Snesaka";
                $sql_lines[] = "-- NPSN: $npsn";
                $sql_lines[] = "-- Tanggal: " . date('d/m/Y H:i:s');
                $sql_lines[] = "-- Database: $dbName";
                $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) * 85);
                    
                    $_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";
                    }
                    
                    // Simpan progress ke session
                    $_SESSION['backup_sql_' . $process_id] = $sql_content;
                }
                
                $sql_content .= "\nSET FOREIGN_KEY_CHECKS=1;\n";
                
                $_SESSION['backup_progress_' . $process_id] = [
                    'status' => 'processing',
                    'percent' => 95,
                    'message' => 'Menyimpan file backup...'
                ];
                
                // Simpan ke session untuk diunduh
                $_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;
            }
            
            // Return progress
            $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 file setelah backup selesai
    if (isset($_GET['download']) && 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];
            
            // Hapus dari session setelah diunduh
            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));
            header('Pragma: no-cache');
            ob_clean();
            echo $sql;
            exit;
        }
    }
    
    // Tampilkan halaman dengan progress bar backup
    $show_backup_progress = true;
    $backup_process_id = uniqid('backup_');
}

// ==================== PROSES UPLOAD FILE RESTORE ====================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['sql_file'])) {
    $file = $_FILES['sql_file'];
    
    if ($file['error'] !== UPLOAD_ERR_OK) {
        setFlash('danger', 'Upload gagal.');
        header('Location: backup.php');
        exit;
    }
    
    // Cek ekstensi file
    $filename = strtolower($file['name']);
    if (substr($filename, -4) !== '.sql') {
        setFlash('danger', 'File harus berformat .sql');
        header('Location: backup.php');
        exit;
    }
    
    $sql = file_get_contents($file['tmp_name']);
    if (empty(trim($sql))) {
        setFlash('danger', 'File SQL kosong.');
        header('Location: backup.php');
        exit;
    }
    
    // Simpan SQL content ke session untuk diproses via AJAX
    $restore_process_id = uniqid('restore_');
    $_SESSION['restore_sql_content_' . $restore_process_id] = $sql;
    $_SESSION['restore_process_id'] = $restore_process_id;
    
    // Redirect ke halaman dengan progress bar restore
    header("Location: backup.php?restore_process=1&process_id=" . $restore_process_id);
    exit;
}

// ==================== TAMPILAN PROGRESS RESTORE ====================
if (isset($_GET['restore_process']) && isset($_GET['process_id'])) {
    $show_restore_progress = true;
    $restore_process_id = $_GET['process_id'];
}

// ==================== INFO DATABASE ====================
try {
    $pdo = new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf8mb4", $dbUser, $dbPass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
    $dbSize = $pdo->query("
        SELECT ROUND(SUM(data_length + index_length)/1024/1024, 2) as size
        FROM information_schema.tables
        WHERE table_schema = '$dbName'
    ")->fetchColumn();
    $npsn = getNPSN($pdo);
    $dbInfo = array('tables' => count($tables), 'size' => $dbSize ?: 0, 'npsn' => $npsn);
} catch (Exception $e) {
    $dbInfo = array('tables' => '?', 'size' => '?', 'npsn' => 'NOSN');
    $tables = [];
}

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

<style>
.backup-progress-container,
.restore-progress-container {
    background: var(--surface);
    border-radius: 15px;
    padding: 25px;
    margin-bottom: 20px;
    border: 2px solid var(--border);
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.progress-bar-wrapper {
    background: var(--border);
    border-radius: 50px;
    overflow: hidden;
    height: 45px;
    position: relative;
    box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);
    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;
    position: relative;
    overflow: hidden;
}

.progress-bar-fill::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent);
    animation: shimmer 1.5s infinite;
}

@keyframes shimmer {
    0% { transform: translateX(-100%); }
    100% { transform: translateX(100%); }
}

.progress-percent {
    text-align: center;
    font-size: 28px;
    font-weight: bold;
    color: #28a745;
    margin: 15px 0;
}

.progress-status-card {
    background: var(--surface-2);
    border-radius: 10px;
    padding: 15px;
    margin-top: 20px;
}

.progress-status-item {
    display: flex;
    justify-content: space-between;
    padding: 10px;
    border-bottom: 1px solid var(--border);
}

.progress-status-item:last-child {
    border-bottom: none;
}

.progress-status-item .label {
    font-weight: 600;
    color: var(--text-muted);
}

.progress-status-item .value {
    color: var(--primary);
    font-family: monospace;
    word-break: break-word;
    text-align: right;
    max-width: 60%;
}

.progress-icon {
    text-align: center;
    font-size: 50px;
    margin-bottom: 20px;
}

.result-container {
    text-align: center;
    padding: 20px;
}

.btn-download {
    background: linear-gradient(135deg, #28a745, #20c997);
    color: white;
    border: none;
    padding: 12px 30px;
    border-radius: 50px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    margin: 20px 0;
    display: inline-block;
    text-decoration: none;
}

.btn-download:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(40,167,69,0.3);
}

.error-list {
    max-height: 200px;
    overflow-y: auto;
    font-size: 12px;
    background: #fee2e2;
    border-radius: 8px;
    padding: 10px;
    margin-top: 15px;
}

.error-item {
    color: #dc3545;
    padding: 5px;
    border-bottom: 1px solid #fecaca;
}
</style>

<?php if (isset($show_backup_progress) && $show_backup_progress): ?>
<!-- Progress Bar Backup -->
<div class="backup-progress-container" id="backupProgressContainer">
    <div class="progress-icon" id="progressIcon">
        <i class="fas fa-database fa-3x" style="color: var(--primary);"></i>
    </div>
    <div class="progress-header" style="text-align: center;">
        <h3>Sedang Membackup Database...</h3>
        <p>Mohon tunggu, proses backup sedang berjalan</p>
    </div>
    <div class="progress-bar-wrapper">
        <div class="progress-bar-fill" id="progressBar">
            <span id="progressText">0%</span>
        </div>
    </div>
    <div class="progress-percent" id="percentDisplay">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="statusLabel">Memulai...</span>
        </div>
        <div class="progress-status-item">
            <span class="label"><i class="fas fa-table"></i> Tabel Sedang Diproses:</span>
            <span class="value" id="currentTable">-</span>
        </div>
        <div class="progress-status-item">
            <span class="label"><i class="fas fa-comment"></i> Pesan:</span>
            <span class="value" id="message">-</span>
        </div>
    </div>
</div>

<div id="resultContainer" style="display: none; text-align: center;">
    <div class="result-container">
        <i class="fas fa-check-circle" style="font-size: 60px; color: #28a745;"></i>
        <h3 style="margin: 20px 0;">✅ Backup Berhasil!</h3>
        <p id="resultMessage" style="margin-bottom: 20px;"></p>
        <a href="#" id="downloadLink" class="btn-download">
            <i class="fas fa-download"></i> Download File Backup
        </a>
        <div style="margin-top: 20px;">
            <a href="backup.php" class="btn btn-secondary">Kembali ke Halaman Backup</a>
        </div>
    </div>
</div>

<script>
const backupProcessId = '<?php echo $backup_process_id; ?>';
let backupInterval;
let isBackupCompleted = false;

function updateBackupProgress() {
    if (isBackupCompleted) return;
    
    fetch(`backup.php?action=backup&ajax=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('progressBar');
            const percentDisplay = document.getElementById('percentDisplay');
            const progressText = document.getElementById('progressText');
            const statusLabel = document.getElementById('statusLabel');
            const currentTable = document.getElementById('currentTable');
            const messageSpan = document.getElementById('message');
            const progressIcon = document.getElementById('progressIcon');
            
            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 (progressIcon) progressIcon.innerHTML = '<i class="fas fa-spinner fa-pulse fa-3x" style="color: var(--primary);"></i>';
                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);
                
                if (statusLabel) {
                    statusLabel.innerHTML = '<i class="fas fa-check-circle"></i> Selesai';
                    statusLabel.style.color = '#28a745';
                }
                if (progressIcon) progressIcon.innerHTML = '<i class="fas fa-check-circle fa-3x" style="color: #28a745;"></i>';
                if (messageSpan && data.message) messageSpan.innerHTML = data.message;
                
                setTimeout(() => {
                    document.getElementById('backupProgressContainer').style.display = 'none';
                    document.getElementById('resultContainer').style.display = 'block';
                    document.getElementById('resultMessage').innerHTML = `
                        Backup database berhasil diselesaikan.<br>
                        File backup siap diunduh dengan nama:<br>
                        <strong><code>${data.filename || 'backup.sql'}</code></strong>
                    `;
                    
                    const downloadLink = document.getElementById('downloadLink');
                    downloadLink.href = `backup.php?action=backup&download=1&process_id=${backupProcessId}`;
                }, 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 (progressIcon) progressIcon.innerHTML = '<i class="fas fa-times-circle fa-3x" style="color: #dc3545;"></i>';
                if (messageSpan && data.message) messageSpan.innerHTML = data.message;
            }
        })
        .catch(error => {
            console.error('Fetch error:', error);
        });
}

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

document.addEventListener('DOMContentLoaded', startBackup);
</script>

<?php elseif (isset($show_restore_progress) && $show_restore_progress): ?>
<!-- Progress Bar Restore -->
<div class="restore-progress-container" id="restoreProgressContainer">
    <div class="progress-icon" id="restoreProgressIcon">
        <i class="fas fa-upload fa-3x" style="color: var(--warning);"></i>
    </div>
    <div class="progress-header" style="text-align: center;">
        <h3>Sedang Merestore Database...</h3>
        <p>Mohon tunggu, proses restore sedang berjalan</p>
    </div>
    <div class="progress-bar-wrapper">
        <div class="progress-bar-fill" id="restoreProgressBar">
            <span id="restoreProgressText">0%</span>
        </div>
    </div>
    <div class="progress-percent" id="restorePercentDisplay">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="restoreStatusLabel">Memulai...</span>
        </div>
        <div class="progress-status-item">
            <span class="label"><i class="fas fa-comment"></i> Pesan:</span>
            <span class="value" id="restoreMessage">-</span>
        </div>
    </div>
</div>

<div id="restoreResultContainer" 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;">✅ Restore Selesai!</h3>
        <p id="restoreResultMessage"></p>
        <div id="restoreErrors" style="display: none;"></div>
        <div style="margin-top: 20px;">
            <a href="backup.php" class="btn btn-primary">Kembali ke Halaman Backup</a>
        </div>
    </div>
</div>

<script>
const restoreProcessId = '<?php echo $restore_process_id; ?>';
let restoreInterval;
let isRestoreCompleted = false;

function updateRestoreProgress() {
    if (isRestoreCompleted) return;
    
    fetch(`backup.php?ajax_restore=1&process_id=${restoreProcessId}&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('restoreProgressBar');
            const percentDisplay = document.getElementById('restorePercentDisplay');
            const progressText = document.getElementById('restoreProgressText');
            const statusLabel = document.getElementById('restoreStatusLabel');
            const messageSpan = document.getElementById('restoreMessage');
            const progressIcon = document.getElementById('restoreProgressIcon');
            
            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 (progressIcon) progressIcon.innerHTML = '<i class="fas fa-spinner fa-pulse fa-3x" style="color: var(--warning);"></i>';
                if (messageSpan && data.message) messageSpan.innerHTML = data.message;
            } else if (data.status === 'completed') {
                isRestoreCompleted = true;
                clearInterval(restoreInterval);
                
                if (statusLabel) {
                    statusLabel.innerHTML = '<i class="fas fa-check-circle"></i> Selesai';
                    statusLabel.style.color = '#28a745';
                }
                if (progressIcon) progressIcon.innerHTML = '<i class="fas fa-check-circle fa-3x" style="color: #28a745;"></i>';
                if (messageSpan && data.message) messageSpan.innerHTML = data.message;
                
                setTimeout(() => {
                    document.getElementById('restoreProgressContainer').style.display = 'none';
                    document.getElementById('restoreResultContainer').style.display = 'block';
                    
                    let resultHtml = `${data.message}<br><br>`;
                    resultHtml += `<strong>✅ ${data.success_count || 0} query berhasil</strong><br>`;
                    if (data.error_count > 0) {
                        resultHtml += `<strong style="color: #dc3545;">❌ ${data.error_count} query gagal</strong><br><br>`;
                        if (data.errors && data.errors.length > 0) {
                            resultHtml += `<div class="error-list"><strong>Detail Error:</strong><br>`;
                            data.errors.forEach(error => {
                                resultHtml += `<div class="error-item">⚠️ ${error}</div>`;
                            });
                            resultHtml += `</div>`;
                        }
                    }
                    
                    document.getElementById('restoreResultMessage').innerHTML = resultHtml;
                }, 500);
            } else if (data.status === 'error') {
                isRestoreCompleted = true;
                clearInterval(restoreInterval);
                
                if (statusLabel) {
                    statusLabel.innerHTML = '<i class="fas fa-times-circle"></i> Error';
                    statusLabel.style.color = '#dc3545';
                }
                if (progressIcon) progressIcon.innerHTML = '<i class="fas fa-times-circle fa-3x" style="color: #dc3545;"></i>';
                if (messageSpan && data.message) messageSpan.innerHTML = data.message;
            }
        })
        .catch(error => {
            console.error('Fetch error:', error);
        });
}

function startRestore() {
    fetch(`backup.php?ajax_restore=1&process_id=${restoreProcessId}&step=start&t=${Date.now()}`)
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                const messageSpan = document.getElementById('restoreMessage');
                if (messageSpan) messageSpan.innerHTML = 'Error: ' + data.error;
                return;
            }
            restoreInterval = setInterval(updateRestoreProgress, 500);
        })
        .catch(error => {
            console.error('Start fetch error:', error);
        });
}

document.addEventListener('DOMContentLoaded', startRestore);
</script>

<?php else: ?>
<!-- Halaman Utama Backup & Restore -->
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;max-width:1000px;">

  <!-- BACKUP -->
  <div class="card">
    <div class="card-header">
      <span class="card-title">
        <i class="fas fa-download" style="color:var(--success);margin-right:8px;"></i>
        Backup Database
      </span>
    </div>
    <div class="card-body">

      <div style="background:linear-gradient(135deg,var(--primary-dark),var(--primary));color:#fff;border-radius:10px;padding:16px;margin-bottom:20px;display:flex;gap:20px;">
        <div style="text-align:center;flex:1;">
          <div style="font-size:28px;font-weight:800;"><?= $dbInfo['tables'] ?></div>
          <div style="font-size:11px;opacity:.75;">Tabel</div>
        </div>
        <div style="width:1px;background:rgba(255,255,255,.2);"></div>
        <div style="text-align:center;flex:1;">
          <div style="font-size:28px;font-weight:800;"><?= $dbInfo['size'] ?></div>
          <div style="font-size:11px;opacity:.75;">MB Ukuran</div>
        </div>
        <div style="width:1px;background:rgba(255,255,255,.2);"></div>
        <div style="text-align:center;flex:1;">
          <div style="font-size:16px;font-weight:700;">NPSN: <?= htmlspecialchars($dbInfo['npsn']) ?></div>
          <div style="font-size:11px;opacity:.75;"><?= date('d/m/Y') ?></div>
        </div>
      </div>

      <p style="font-size:13px;color:var(--text-muted);margin-bottom:16px;">
        Unduh seluruh data database sebagai file <code>.sql</code> untuk backup.
        Format nama file: <strong>Backup_NPSN_tanggal_waktu.sql</strong>
      </p>

      <a href="?action=backup" class="btn btn-primary" style="width:100%;justify-content:center;margin-bottom:10px;">
        <i class="fas fa-database"></i>&nbsp; Backup Sekarang
      </a>

      <div style="background:#f0fdf4;border:1px solid #bbf7d0;border-radius:8px;padding:12px;font-size:12px;color:#15803d;">
        <i class="fas fa-shield-alt"></i>
        <strong>Tips keamanan:</strong> Lakukan backup rutin setiap minggu atau sebelum perubahan data besar.
      </div>
    </div>
  </div>

  <!-- RESTORE -->
  <div class="card">
    <div class="card-header">
      <span class="card-title">
        <i class="fas fa-upload" style="color:var(--warning);margin-right:8px;"></i>
        Restore Database
      </span>
    </div>
    <div class="card-body">

      <div style="background:#fff8e1;border:1px solid #ffe082;border-radius:8px;padding:12px 14px;margin-bottom:16px;font-size:12px;color:#7c5e00;">
        <i class="fas fa-exclamation-triangle"></i>
        <strong>Peringatan:</strong> Restore akan <strong>menimpa semua data saat ini</strong>.
        Pastikan Anda sudah backup terlebih dahulu!
      </div>

      <form method="POST" enctype="multipart/form-data" action="">
        <div class="form-group">
          <label class="form-label">File SQL Backup <span class="required">*</span></label>
          <input type="file" name="sql_file" class="form-control" accept=".sql" required>
          <div style="font-size:11px;color:var(--text-muted);margin-top:4px;">Hanya file <code>.sql</code> hasil backup SisPen Snesaka</div>
        </div>

        <button type="submit" name="restore_submit"
                class="btn" style="width:100%;justify-content:center;background:#f59e0b;color:#fff;border:none;"
                onclick="return confirm('⚠️ PERINGATAN!\n\nSeluruh data database akan ditimpa dengan data dari file backup.\n\nYakin ingin melanjutkan restore?')">
          <i class="fas fa-undo-alt"></i>&nbsp; Restore Sekarang
        </button>
      </form>

      <div style="margin-top:16px;padding:12px;background:var(--surface-2);border-radius:8px;font-size:12px;color:var(--text-muted);">
        <div style="font-weight:600;margin-bottom:6px;"><i class="fas fa-history"></i> Tabel yang akan di-restore:</div>
        <?php if (!empty($tables)): ?>
          <?php foreach ($tables as $t): ?>
          <span style="display:inline-block;background:var(--border);border-radius:4px;padding:2px 8px;margin:2px;font-family:monospace;"><?= htmlspecialchars($t) ?></span>
          <?php endforeach; ?>
        <?php else: ?>
          <span style="color:var(--text-muted);">Tidak dapat mengambil daftar tabel</span>
        <?php endif; ?>
      </div>
    </div>
  </div>

</div>
<?php endif; ?>

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