<?php
require_once __DIR__ . '/lib/functions.php';
mdw_require_login();
$message = '';
$created = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {
    $created = mdw_create_backup_zip($message);
    if ($created) mdw_flash($message); else mdw_flash($message ?: 'Backup failed.', 'error');
    header('Location: backup.php'); exit;
}
if (isset($_GET['download'])) {
    $name = basename((string)$_GET['download']);
    $file = mdw_storage_path('backups') . '/' . $name;
    if (is_file($file)) {
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename="' . $name . '"');
        header('Content-Length: ' . filesize($file));
        readfile($file);
        exit;
    }
    mdw_flash('Backup file was not found.', 'error');
    header('Location: backup.php'); exit;
}
$backupDir = mdw_storage_path('backups');
$files = is_dir($backupDir) ? array_values(array_filter(scandir($backupDir), fn($f) => str_ends_with($f, '.zip'))) : [];
rsort($files);
mdw_render_header('Backups');
?>
<section class="panel">
  <h2>Admin Backups</h2>
  <p class="muted">Create a ZIP backup of MDW Admin data, saved documents, document exports, and uploads. This does not back up Ecommerce Templates, ClearChat, or config.php.</p>
  <form method="post"><input type="hidden" name="action" value="create"><button class="button" type="submit">Create Backup Now</button></form>
</section>
<section class="panel" style="margin-top:20px">
  <h2>Available Backups</h2>
  <?php if (!$files): ?><p class="muted">No backups have been created yet.</p><?php else: ?>
  <table><thead><tr><th>Backup File</th><th>Size</th><th>Modified</th><th>Action</th></tr></thead><tbody>
  <?php foreach ($files as $f): $path=$backupDir.'/'.$f; ?>
    <tr><td><strong><?php echo mdw_h($f); ?></strong></td><td><?php echo number_format(filesize($path)/1024, 1); ?> KB</td><td><?php echo date('M j, Y g:i A', filemtime($path)); ?></td><td><a class="button" href="backup.php?download=<?php echo urlencode($f); ?>">Download</a></td></tr>
  <?php endforeach; ?>
  </tbody></table><?php endif; ?>
</section>
<section class="panel" style="margin-top:20px"><h2>Organized Storage</h2><div class="file-list"><code>documents/templates/</code><code>documents/saved/</code><code>documents/invoices/</code><code>documents/exports/</code><code>documents/archive/</code><code>uploads/</code><code>backups/</code><code>logs/</code><code>tmp/</code></div></section>
<?php mdw_render_footer(); ?>
