<?php
require 'db.php';
require 'auth.php';
require_login();
require_admin();

$message = '';
$messageType = '';

// Debug: Log all POST data
if (!empty($_POST)) {
    error_log("BACKUP-RESTORE POST DATA: " . print_r($_POST, true));
    
    // Additional debug for delete_backup specifically
    if (isset($_POST['delete_backup'])) {
        error_log("DELETE BACKUP: POST received - filename: " . ($_POST['backup_file'] ?? 'NOT SET'));
    }
}

// Handle Backup
if (isset($_POST['backup'])) {
    try {
        $backupDir = __DIR__ . DIRECTORY_SEPARATOR . 'backups';
        if (!is_dir($backupDir)) {
            mkdir($backupDir, 0755, true);
        }
        
        $timestamp = date('Y-m-d_H-i-s');
        $backupFile = $backupDir . DIRECTORY_SEPARATOR . "backup_$timestamp.sqlite";
        
        if (copy($dbFile, $backupFile)) {
            $message = "Backup berhasil dibuat: backup_$timestamp.sqlite";
            $messageType = 'success';
            
            // Log backup activity
            error_log("BACKUP: Created by " . (current_user()['nama_lengkap'] ?? current_user()['username']) . " at " . date('Y-m-d H:i:s'));
        } else {
            $message = "Gagal membuat backup";
            $messageType = 'danger';
        }
    } catch (Exception $e) {
        $message = "Error: " . $e->getMessage();
        $messageType = 'danger';
    }
}

// Handle Restore
if (isset($_POST['restore']) && isset($_FILES['restore_file'])) {
    try {
        $uploadedFile = $_FILES['restore_file'];
        
        if ($uploadedFile['error'] !== UPLOAD_ERR_OK) {
            throw new Exception("Error uploading file");
        }
        
        if (pathinfo($uploadedFile['name'], PATHINFO_EXTENSION) !== 'sqlite') {
            throw new Exception("File harus berformat .sqlite");
        }
        
        // Verify it's a valid SQLite file
        $tempDb = new PDO('sqlite:' . $uploadedFile['tmp_name']);
        $tables = $tempDb->query("SELECT name FROM sqlite_master WHERE type='table'")->fetchAll();
        $tempDb = null;
        
        $requiredTables = ['peminjaman', 'users', 'settings'];
        $foundTables = array_column($tables, 'name');
        
        foreach ($requiredTables as $table) {
            if (!in_array($table, $foundTables)) {
                throw new Exception("File backup tidak valid: tabel '$table' tidak ditemukan");
            }
        }
        
        // Create backup of current database before restore
        $currentBackup = __DIR__ . DIRECTORY_SEPARATOR . 'backups' . DIRECTORY_SEPARATOR . 'before_restore_' . date('Y-m-d_H-i-s') . '.sqlite';
        copy($dbFile, $currentBackup);
        
        // Restore database
        if (move_uploaded_file($uploadedFile['tmp_name'], $dbFile)) {
            $message = "Database berhasil di-restore. Backup database lama disimpan sebagai: " . basename($currentBackup);
            $messageType = 'success';
            
            // Log restore activity
            error_log("RESTORE: Database restored by " . (current_user()['nama_lengkap'] ?? current_user()['username']) . " at " . date('Y-m-d H:i:s'));
            
            // Redirect to refresh database connection
            header("Location: backup-restore.php?restored=1");
            exit;
        } else {
            throw new Exception("Gagal memindahkan file backup");
        }
    } catch (Exception $e) {
        $message = "Error restore: " . $e->getMessage();
        $messageType = 'danger';
    }
}

// Handle Download Backup
if (isset($_GET['download'])) {
    $filename = basename($_GET['download']);
    $filepath = __DIR__ . DIRECTORY_SEPARATOR . 'backups' . DIRECTORY_SEPARATOR . $filename;
    
    if (file_exists($filepath) && strpos($filename, 'backup_') === 0) {
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-Length: ' . filesize($filepath));
        readfile($filepath);
        exit;
    } else {
        $message = "File backup tidak ditemukan";
        $messageType = 'danger';
    }
}

// Handle Delete All Data
if (isset($_POST['delete_all_data'])) {
    $confirmText = $_POST['confirm_delete'] ?? '';
    error_log("DELETE ALL DATA: Attempting with confirmation text: '$confirmText'");
    
    if ($confirmText === 'HAPUS SEMUA DATA') {
        try {
            // Debug logging
            error_log("DELETE ALL DATA: Process started by " . current_user()['username'] . " at " . date('Y-m-d H:i:s'));
            
            // Create backup before deleting all data
            $backupDir = __DIR__ . DIRECTORY_SEPARATOR . 'backups';
            if (!is_dir($backupDir)) {
                mkdir($backupDir, 0755, true);
            }
            
            $timestamp = date('Y-m-d_H-i-s');
            $backupFile = $backupDir . DIRECTORY_SEPARATOR . "before_delete_all_$timestamp.sqlite";
            
            if (copy($dbFile, $backupFile)) {
                // Count records before delete
                $countBefore = $db->query("SELECT COUNT(*) FROM peminjaman")->fetchColumn();
                error_log("DELETE ALL DATA: Records before delete: $countBefore");
                
                // Delete all data from peminjaman table
                $deletedCount = $db->exec("DELETE FROM peminjaman");
                
                // Count records after delete
                $countAfter = $db->query("SELECT COUNT(*) FROM peminjaman")->fetchColumn();
                error_log("DELETE ALL DATA: Records after delete: $countAfter, Deleted: $deletedCount");
                
                $message = "SEMUA DATA PEMINJAMAN BERHASIL DIHAPUS! ($deletedCount record dihapus)<br>Backup otomatis disimpan: before_delete_all_$timestamp.sqlite";
                $messageType = 'warning';
                
                // Log delete all activity
                error_log("DELETE ALL DATA: All peminjaman data deleted by " . current_user()['username'] . " at " . date('Y-m-d H:i:s'));
            } else {
                throw new Exception("Gagal membuat backup sebelum menghapus data");
            }
        } catch (Exception $e) {
            error_log("DELETE ALL DATA ERROR: " . $e->getMessage());
            $message = "Error: " . $e->getMessage();
            $messageType = 'danger';
        }
    } else {
        // Debug case where POST is set but confirmation doesn't match
        error_log("DELETE ALL DATA: Invalid confirmation text: '$confirmText'");
        $message = "Konfirmasi text tidak sesuai. Harap ketik persis: 'HAPUS SEMUA DATA' (Anda ketik: '$confirmText')";
        $messageType = 'danger';
    }
}

// Handle Delete Backup
if (isset($_POST['delete_backup'])) {
    $filename = basename($_POST['backup_file']);
    $filepath = __DIR__ . DIRECTORY_SEPARATOR . 'backups' . DIRECTORY_SEPARATOR . $filename;
    
    error_log("DELETE BACKUP: Attempting to delete file: $filename at path: $filepath");
    
    // Allow deletion of both backup_ and before_restore_ and before_delete_all_ files
    $validPrefixes = ['backup_', 'before_restore_', 'before_delete_all_'];
    $isValidFile = false;
    
    foreach ($validPrefixes as $prefix) {
        if (strpos($filename, $prefix) === 0) {
            $isValidFile = true;
            break;
        }
    }
    
    if (file_exists($filepath) && $isValidFile) {
        if (unlink($filepath)) {
            $message = "Backup $filename berhasil dihapus";
            $messageType = 'success';
            error_log("DELETE BACKUP: Successfully deleted file: $filename");
        } else {
            $message = "Gagal menghapus backup $filename";
            $messageType = 'danger';
            error_log("DELETE BACKUP: Failed to delete file: $filename");
        }
    } else {
        if (!file_exists($filepath)) {
            $message = "File backup tidak ditemukan: $filename";
            error_log("DELETE BACKUP: File not found: $filepath");
        } else {
            $message = "File tidak valid untuk dihapus: $filename";
            error_log("DELETE BACKUP: Invalid file type: $filename");
        }
        $messageType = 'danger';
    }
}

// Get list of backup files
$backupDir = __DIR__ . DIRECTORY_SEPARATOR . 'backups';
$backupFiles = [];
if (is_dir($backupDir)) {
    $files = scandir($backupDir);
    foreach ($files as $file) {
        if (strpos($file, 'backup_') === 0 || strpos($file, 'before_restore_') === 0) {
            $filepath = $backupDir . DIRECTORY_SEPARATOR . $file;
            $backupFiles[] = [
                'name' => $file,
                'size' => filesize($filepath),
                'date' => filemtime($filepath)
            ];
        }
    }
    // Sort by date, newest first
    usort($backupFiles, function($a, $b) {
        return $b['date'] - $a['date'];
    });
}

// Get database statistics
try {
    $stats = [
        'peminjaman' => $db->query("SELECT COUNT(*) FROM peminjaman")->fetchColumn(),
        'users' => $db->query("SELECT COUNT(*) FROM users")->fetchColumn(),
        'settings' => $db->query("SELECT COUNT(*) FROM settings")->fetchColumn(),
    ];
    $dbSize = filesize($dbFile);
} catch (Exception $e) {
    $stats = ['error' => $e->getMessage()];
    $dbSize = 0;
}

if (isset($_GET['restored'])) {
    $message = "Database berhasil di-restore!";
    $messageType = 'success';
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Backup & Restore Database</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <style>
        body { background: #f5f7fb; }
        .stat-card { transition: transform 0.2s; }
        .stat-card:hover { transform: translateY(-2px); }
    </style>
</head>
<body>
    <div class="container py-4">
        <!-- Header -->
        <div class="row mb-4">
            <div class="col">
                <div class="d-flex justify-content-between align-items-center">
                    <div class="d-flex align-items-center">
                        <img src="gambar/Logo_pnwtp.png" alt="Logo PN Watampone" width="80" height="80" class="me-3">
                        <div>
                            <h1 class="h3 mb-0"><i class="fa fa-database text-primary"></i> Backup & Restore Database</h1>
                            <p class="text-muted mb-0">Pengadilan Negeri Watampone - Kelola backup dan restore data aplikasi</p>
                        </div>
                    </div>
                    <div>
                        <a href="admin.php" class="btn btn-outline-secondary"><i class="fa fa-arrow-left"></i> Kembali</a>
                    </div>
                </div>
            </div>
        </div>

        <!-- Alert Messages -->
        <?php if ($message): ?>
        <div class="row mb-4">
            <div class="col">
                <div class="alert alert-<?= $messageType ?> alert-dismissible fade show">
                    <i class="fa fa-<?= $messageType === 'success' ? 'check-circle' : 'exclamation-triangle' ?>"></i>
                    <?= htmlspecialchars($message) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Database Statistics -->
        <div class="row mb-4">
            <div class="col">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title"><i class="fa fa-chart-bar text-info"></i> Statistik Database</h5>
                        <div class="row">
                            <div class="col-md-3">
                                <div class="stat-card text-center p-3 border rounded">
                                    <div class="h4 text-primary"><?= number_format($stats['peminjaman'] ?? 0) ?></div>
                                    <small class="text-muted">Data Peminjaman</small>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="stat-card text-center p-3 border rounded">
                                    <div class="h4 text-success"><?= number_format($stats['users'] ?? 0) ?></div>
                                    <small class="text-muted">User Accounts</small>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="stat-card text-center p-3 border rounded">
                                    <div class="h4 text-warning"><?= number_format($stats['settings'] ?? 0) ?></div>
                                    <small class="text-muted">Settings</small>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="stat-card text-center p-3 border rounded">
                                    <div class="h4 text-info"><?= number_format($dbSize / 1024, 1) ?> KB</div>
                                    <small class="text-muted">Database Size</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Backup Section -->
            <div class="col-md-4 mb-4">
                <div class="card h-100">
                    <div class="card-header bg-primary text-white">
                        <h5 class="card-title mb-0"><i class="fa fa-download"></i> Backup Database</h5>
                    </div>
                    <div class="card-body">
                        <p class="card-text">Buat backup database untuk keamanan data. Backup akan disimpan dengan timestamp.</p>
                        
                        <div class="alert alert-info">
                            <i class="fa fa-info-circle"></i>
                            <strong>Tips:</strong>
                            <ul class="mb-0 mt-2">
                                <li>Buat backup secara berkala (mingguan/bulanan)</li>
                                <li>Simpan backup di lokasi yang aman</li>
                                <li>Test restore backup secara berkala</li>
                            </ul>
                        </div>
                        
                        <form method="POST">
                            <div class="d-grid">
                                <button type="submit" name="backup" class="btn btn-primary btn-lg" onclick="return confirm('Buat backup database sekarang?')">
                                    <i class="fa fa-download"></i> Buat Backup Sekarang
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Restore Section -->
            <div class="col-md-4 mb-4">
                <div class="card h-100">
                    <div class="card-header bg-warning text-dark">
                        <h5 class="card-title mb-0"><i class="fa fa-upload"></i> Restore Database</h5>
                    </div>
                    <div class="card-body">
                        <p class="card-text">Restore database dari file backup. <strong>HATI-HATI:</strong> Data saat ini akan diganti!</p>
                        
                        <div class="alert alert-warning">
                            <i class="fa fa-exclamation-triangle"></i>
                            <strong>Peringatan:</strong>
                            <ul class="mb-0 mt-2">
                                <li>Database saat ini akan di-backup otomatis</li>
                                <li>Data saat ini akan diganti dengan data backup</li>
                                <li>Proses ini tidak dapat dibatalkan</li>
                            </ul>
                        </div>
                        
                        <form method="POST" enctype="multipart/form-data">
                            <div class="mb-3">
                                <label class="form-label">Pilih File Backup (.sqlite)</label>
                                <input type="file" name="restore_file" class="form-control" accept=".sqlite" required>
                            </div>
                            <div class="d-grid">
                                <button type="submit" name="restore" class="btn btn-warning btn-lg" onclick="return confirm('PERINGATAN: Data saat ini akan diganti dengan data backup. Yakin ingin melanjutkan?')">
                                    <i class="fa fa-upload"></i> Restore Database
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Delete All Data Section -->
            <div class="col-md-4 mb-4">
                <div class="card h-100 border-danger">
                    <div class="card-header bg-danger text-white">
                        <h5 class="card-title mb-0"><i class="fa fa-trash-alt"></i> Hapus Semua Data</h5>
                    </div>
                    <div class="card-body">
                        <p class="card-text"><strong>BAHAYA:</strong> Hapus seluruh data peminjaman berkas dari sistem!</p>
                        
                        <div class="alert alert-danger">
                            <i class="fa fa-exclamation-triangle"></i>
                            <strong>PERINGATAN KERAS:</strong>
                            <ul class="mb-0 mt-2">
                                <li><strong>SEMUA data peminjaman akan dihapus permanen</strong></li>
                                <li>Backup otomatis akan dibuat sebelum hapus</li>
                                <li>Data user dan settings tidak terpengaruh</li>
                                <li><strong>Proses ini TIDAK dapat dibatalkan!</strong></li>
                            </ul>
                        </div>
                        
                        <form method="POST" id="deleteAllForm">
                            <div class="mb-3">
                                <label class="form-label text-danger"><strong>Ketik: "HAPUS SEMUA DATA" untuk konfirmasi</strong></label>
                                <input type="text" name="confirm_delete" id="confirm_delete" class="form-control" placeholder="Ketik persis: HAPUS SEMUA DATA" required autocomplete="off">
                            </div>
                            <div class="d-grid">
                                <button type="submit" name="delete_all_data" class="btn btn-danger btn-lg" id="deleteAllBtn" 
                                        onclick="return confirm('YAKIN HAPUS SEMUA DATA? Aksi ini tidak dapat dibatalkan!')">
                                    <i class="fa fa-trash-alt"></i> HAPUS SEMUA DATA
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Backup Files List -->
        <div class="row">
            <div class="col">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0"><i class="fa fa-folder text-success"></i> Daftar File Backup</h5>
                    </div>
                    <div class="card-body">
                        <?php if (empty($backupFiles)): ?>
                            <div class="text-center py-4">
                                <i class="fa fa-folder-open fa-3x text-muted mb-3"></i>
                                <p class="text-muted">Belum ada file backup. Buat backup pertama Anda!</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Nama File</th>
                                            <th>Ukuran</th>
                                            <th>Tanggal Dibuat</th>
                                            <th>Aksi</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($backupFiles as $backup): ?>
                                        <tr>
                                            <td>
                                                <i class="fa fa-file-archive text-primary"></i>
                                                <strong><?= htmlspecialchars($backup['name']) ?></strong>
                                                <?php if (strpos($backup['name'], 'before_restore_') === 0): ?>
                                                    <span class="badge bg-warning ms-2">Auto Backup</span>
                                                <?php elseif (strpos($backup['name'], 'before_delete_all_') === 0): ?>
                                                    <span class="badge bg-danger ms-2">Before Delete</span>
                                                <?php endif; ?>
                                            </td>
                                            <td><?= number_format($backup['size'] / 1024, 1) ?> KB</td>
                                            <td><?= date('d/m/Y H:i:s', $backup['date']) ?></td>
                                            <td>
                                                <div class="btn-group btn-group-sm">
                                                    <a href="?download=<?= urlencode($backup['name']) ?>" class="btn btn-outline-primary" title="Download">
                                                        <i class="fa fa-download"></i>
                                                    </a>
                                                    <form method="POST" style="display: inline;" onsubmit="return confirmDelete('<?= htmlspecialchars($backup['name']) ?>')">
                                                        <input type="hidden" name="backup_file" value="<?= htmlspecialchars($backup['name']) ?>">
                                                        <button type="submit" name="delete_backup" class="btn btn-outline-danger" title="Hapus">
                                                            <i class="fa fa-trash"></i>
                                                        </button>
                                                    </form>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Security Notice -->
        <div class="row mt-4">
            <div class="col">
                <div class="card border-info">
                    <div class="card-body">
                        <h6 class="card-title text-info"><i class="fa fa-shield-alt"></i> Catatan Keamanan</h6>
                        <ul class="small mb-0">
                            <li>File backup berisi semua data termasuk password user (dalam bentuk hash)</li>
                            <li>Simpan file backup di lokasi yang aman dan terlindungi</li>
                            <li>Jangan bagikan file backup kepada orang yang tidak berwenang</li>
                            <li>Lakukan backup secara berkala untuk menghindari kehilangan data</li>
                            <li>Test proses restore secara berkala untuk memastikan backup berfungsi</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Enable/disable delete all button based on confirmation text
        document.getElementById('confirm_delete').addEventListener('input', function() {
            const confirmText = this.value;
            const deleteBtn = document.getElementById('deleteAllBtn');
            
            console.log('Input changed to:', confirmText);
            
            if (confirmText === 'HAPUS SEMUA DATA') {
                deleteBtn.disabled = false;
                deleteBtn.classList.remove('btn-secondary');
                deleteBtn.classList.add('btn-danger');
                console.log('Button enabled');
            } else {
                deleteBtn.disabled = true;
                deleteBtn.classList.remove('btn-danger');
                deleteBtn.classList.add('btn-secondary');
                console.log('Button disabled');
            }
        });
        
        // Confirmation for backup file deletion
        function confirmDelete(filename) {
            const message = `Apakah Anda yakin ingin menghapus file backup ini?\n\nFile: ${filename}\n\n⚠️ File backup yang dihapus tidak dapat dikembalikan!`;
            
            return confirm(message);
        }
    </script>

    <!-- Footer -->
    <footer class="bg-primary text-white text-center py-3 mt-5">
      <div class="container">
        <p class="mb-0">©2025 by Pn Watampone, Dibuat oleh Fahrurrasyid, A.Md.T CPNS Mahkamah Agung RI Angkatan 2024</p>
      </div>
    </footer>

</body>
</html>
