<?php
session_start();

if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    http_response_code(401);
    exit;
}

// ULTIMATE: MAXIMUM CACHE BUSTING
header('Content-Type: text/html; charset=utf-8');
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');

$backupDir = 'backup_data';

// FORCE: Clear ALL PHP cache
clearstatcache(true);

// Get list of backup files - FORCE fresh read
$backups = @scandir($backupDir);
if ($backups === false) $backups = [];

// Filter hanya .zip files
$backups = array_filter($backups, function($file) use ($backupDir) {
    return is_file($backupDir . '/' . $file) && substr($file, -4) === '.zip';
});

// Map ke full path
$backups = array_map(function($file) use ($backupDir) {
    return $backupDir . '/' . $file;
}, $backups);

// Sort terbaru di depan
rsort($backups);

$tableHtml = '';
$count = count($backups);

if ($count > 0) {
    foreach ($backups as $backup) {
        $filename = basename($backup);
        // Re-check file exists dan ambil fresh stat
        if (!file_exists($backup)) continue;

        $filesize = filesize($backup);
        $filedate = date('d/m/Y H:i:s', filemtime($backup));

        $tableHtml .= '<tr style="border-bottom: 1px solid #eee;">';
        $tableHtml .= '<td style="padding: 12px; font-size: 0.9em;"><code style="background: #f5f5f5; padding: 4px 8px; border-radius: 4px;">' . htmlspecialchars($filename) . '</code></td>';
        $tableHtml .= '<td style="padding: 12px;">' . $filedate . '</td>';
        $tableHtml .= '<td style="padding: 12px;">' . number_format($filesize / 1024, 2) . ' KB</td>';
        $tableHtml .= '<td style="padding: 12px; text-align: center;">';
        $tableHtml .= '<form method="POST" style="display: inline;"><button type="submit" name="restore_backup" value="' . 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>';
        $tableHtml .= '<form method="POST" style="display: inline;"><button type="submit" name="delete_backup" value="' . 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>';
        $tableHtml .= '</td>';
        $tableHtml .= '</tr>';
    }
}
?>
<tbody id="backupTableBody">
    <?php echo $tableHtml; ?>
</tbody>
<div id="backupCount" style="display: none;"><?php echo $count; ?></div>
