<?php
session_start();
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

// ULTIMATE: MAXIMUM CACHE BUSTING
header('Cache-Control: no-cache, no-store, must-revalidate, max-age=0, public, private');
header('Pragma: no-cache, no-store');
header('Expires: 0');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('ETag: "' . microtime(true) . '"');
header('Vary: *');
header('X-Cache-Control: no-cache');

$page_title = 'Backup Data';
include 'includes/header.php';

$backupDir = 'backup_data';
if (!file_exists($backupDir)) {
    mkdir($backupDir, 0777, true);
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['delete_all'])) {
        $files = glob($backupDir . '/*.zip');
        foreach ($files as $file) {
            if (is_file($file)) {
                unlink($file);
            }
        }
        $message = "✅ Semua backup berhasil dihapus!";
        $messageType = 'success';
    } elseif (isset($_POST['delete_backup'])) {
        $file = $backupDir . '/' . basename($_POST['delete_backup']);
        if (file_exists($file)) {
            unlink($file);
            $message = "✅ Backup berhasil dihapus!";
            $messageType = 'success';
        }
    } elseif (isset($_POST['restore_backup'])) {
        $backupFile = basename($_POST['restore_backup']);
        $file = $backupDir . '/' . $backupFile;

        if (file_exists($file)) {
            $zip = new ZipArchive;
            if ($zip->open($file) === TRUE) {
                $safetyBackup = $backupDir . '/safety_before_restore_' . date('Y-m-d_H-i-s') . '.zip';
                $safetyZip = new ZipArchive();
                if ($safetyZip->open($safetyBackup, ZipArchive::CREATE) === TRUE) {
                    if (file_exists('data/transactions.json')) {
                        $safetyZip->addFile('data/transactions.json', 'transactions.json');
                    }
                    if (file_exists('data/reminders.json')) {
                        $safetyZip->addFile('data/reminders.json', 'reminders.json');
                    }
                    $safetyZip->close();
                }

                $zip->extractTo('data/');
                $zip->close();

                $message = "✅ Data berhasil di-restore dari: " . htmlspecialchars($backupFile);
                $messageType = 'success';
            } else {
                $message = "❌ Gagal membuka file backup!";
                $messageType = 'error';
            }
        } else {
            $message = "❌ File backup tidak ditemukan!";
            $messageType = 'error';
        }
    }
}

clearstatcache();
$backups = glob($backupDir . '/*.zip');
if ($backups === false) $backups = [];
rsort($backups);

// Generate unique ID untuk bypass cache
$uniqueId = time() . '_' . microtime(true) * 10000;
?>

<div class="container">
    <div class="card">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h2 style="margin: 0;">🗄️ Manajemen Backup</h2>
            <button onclick="forceReloadPage()" class="btn btn-primary" style="padding: 10px 20px; background: #2196F3; color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: bold; font-size: 14px;">
                Refresh
            </button>
        </div>

        <div id="messageContainer">
            <?php if (!empty($message)): ?>
                <div style="padding: 15px; background: <?php echo $messageType === 'success' ? '#4CAF50' : '#f44336'; ?>; color: white; border-radius: 8px; margin-bottom: 20px;">
                    <?php echo $message; ?>
                </div>
            <?php endif; ?>
        </div>

        <div style="margin-bottom: 20px; padding: 15px; background: #e3f2fd; border-left: 4px solid #2196F3; border-radius: 4px;">
            <p style="margin: 0; color: #1565c0;">
                <strong>ℹ️ Info:</strong> Backup otomatis dibuat setiap kali Anda menambah data baru.
              <br><strong>ℹ️ Info:</strong> Hapus Semua Backup Biar Tidak Penuh
                <br><strong>📊 Total backup:</strong> <span id="backupCount"><?php echo count($backups); ?></span> file
               
            </p>
        </div>

        <div id="backupContainer">
            <?php if (count($backups) > 0): ?>
                <form method="POST" style="margin-bottom: 20px;" onsubmit="return confirm('⚠️ Yakin ingin menghapus SEMUA backup?');">
                    <button type="submit" name="delete_all" class="btn btn-danger" style="background: #f44336; color: white; padding: 10px 20px; border: none; border-radius: 8px; cursor: pointer; font-weight: bold;">
                        🗑️ Hapus Semua Backup
                    </button>
                </form>

                <div style="overflow-x: auto;">
                    <table style="width: 100%; border-collapse: collapse;" id="backupTable">
                        <thead>
                            <tr style="background: #f5f5f5;">
                                <th style="padding: 12px; text-align: left; border-bottom: 2px solid #ddd;">Nama File</th>
                                <th style="padding: 12px; text-align: left; border-bottom: 2px solid #ddd;">Tanggal</th>
                                <th style="padding: 12px; text-align: left; border-bottom: 2px solid #ddd;">Ukuran</th>
                                <th style="padding: 12px; text-align: center; border-bottom: 2px solid #ddd;">Aksi</th>
                            </tr>
                        </thead>
                        <tbody id="backupTableBody">
                            <?php foreach ($backups as $backup): 
                                $filename = basename($backup);
                                $filesize = filesize($backup);
                                $filedate = date('d/m/Y H:i:s', filemtime($backup));
                            ?>
                            <tr style="border-bottom: 1px solid #eee;">
                                <td style="padding: 12px; font-size: 0.9em;"><code style="background: #f5f5f5; padding: 4px 8px; border-radius: 4px;"><?php echo htmlspecialchars($filename); ?></code></td>
                                <td style="padding: 12px;"><?php echo $filedate; ?></td>
                                <td style="padding: 12px;"><?php echo number_format($filesize / 1024, 2); ?> KB</td>
                                <td style="padding: 12px; text-align: center;">
                                    <form method="POST" style="display: inline;">
                                        <button type="submit" name="restore_backup" value="<?php echo htmlspecialchars($filename); ?>" class="btn btn-primary" style="padding: 6px 12px; margin-right: 5px; background: #2196F3; color: white; border: none; border-radius: 4px; cursor: pointer;" onclick="return confirm('♻️ Restore backup ini?');">♻️ Restore</button>
                                    </form>
                                    <form method="POST" style="display: inline;">
                                        <button type="submit" name="delete_backup" value="<?php echo htmlspecialchars($filename); ?>" class="btn btn-danger" style="padding: 6px 12px; background: #ff9800; color: white; border: none; border-radius: 4px; cursor: pointer;" onclick="return confirm('🗑️ Hapus backup ini?');">🗑️ Hapus</button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div style="text-align: center; padding: 40px; color: #999;">
                    <p style="font-size: 48px; margin: 0;">📦</p>
                    <p style="font-size: 16px; margin-top: 10px;">Belum ada backup tersedia</p>
                    <p style="font-size: 14px; color: #aaa;">Backup akan dibuat otomatis saat Anda menambah data baru</p>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

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

<script>
    let lastBackupCount = <?php echo count($backups); ?>;
    const PAGE_UNIQUE_ID = '<?php echo $uniqueId; ?>';

    // ULTIMATE: Force reload page tanpa cache
    function forceReloadPage() {
        console.log('[BACKUP] Force reload page triggered');
        // Method 1: Replace dengan query string unik
        const uniqueParam = '?bust=' + Date.now() + '_' + Math.random();
        window.location.href = window.location.pathname + uniqueParam;
    }

    // Fungsi refresh list otomatis
    async function refreshBackupList() {
        try {
            const now = Date.now();
            const nonce = Math.random();
            // Triple cache busting
            const url = `api-backup.php?t=${now}&n=${nonce}&_=${nonce}&bust=${Math.random()}`;

            const response = await fetch(url, {
                method: 'GET',
                cache: 'reload', // FORCE reload, tidak cache
                headers: {
                    'Cache-Control': 'no-cache, no-store, must-revalidate',
                    'Pragma': 'no-cache',
                    'Expires': '0',
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-Random-Token': Math.random().toString(36)
                }
            });

            if (!response.ok) return;

            const html = await response.text();
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = html;

            const newTableBody = tempDiv.querySelector('#backupTableBody');
            const newCount = tempDiv.querySelector('#backupCount');

            if (newCount) {
                const currentCount = parseInt(newCount.textContent) || 0;
                const countEl = document.getElementById('backupCount');

                if (currentCount !== lastBackupCount) {
                    console.log('[BACKUP] New backup detected:', lastBackupCount, '→', currentCount);
                    countEl.textContent = currentCount;
                    lastBackupCount = currentCount;

                    if (newTableBody) {
                        const oldBody = document.getElementById('backupTableBody');
                        if (oldBody) {
                            oldBody.innerHTML = newTableBody.innerHTML;
                            console.log('[BACKUP] Table updated!');
                        }
                    }
                }
            }
        } catch (error) {
            console.error('Error refreshing:', error);
        }
    }

    // Auto-refresh setiap 1 detik
    setInterval(refreshBackupList, 1000);

    // Initial refresh after 500ms
    setTimeout(refreshBackupList, 500);

    console.log('[BACKUP] Ultimate refresh system loaded');
</script>

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