<?php
session_start();
require __DIR__ . '/includes/admin_lib.php';


if (!$CAN_VIEW) { http_response_code(403); echo "<h1>Access Denied</h1>"; exit; }

$dataDir = realpath(__DIR__ . '/../data');
if ($dataDir === false) { echo "<h1>Missing /data</h1>"; exit; }

function zip_dir(string $dir, string $zipPath): bool {
  if (!class_exists('ZipArchive')) return false;
  $zip = new ZipArchive();
  if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) return false;

  $dir = rtrim($dir, DIRECTORY_SEPARATOR);
  $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS));
  foreach ($it as $file) {
    $filePath = (string)$file;
    $local = substr($filePath, strlen($dir) + 1);
    $zip->addFile($filePath, 'data/' . $local);
  }
  $zip->close();
  return true;
}

if (isset($_GET['download']) && $CAN_EDIT) {
  $tmp = sys_get_temp_dir() . '/almostheaven_data_backup_' . date('Ymd_His') . '.zip';
  if (!zip_dir($dataDir, $tmp)) {
    header('Content-Type: text/plain; charset=utf-8');
    echo "ZipArchive is not available on this server."; exit;
  }
  header('Content-Type: application/zip');
  header('Content-Disposition: attachment; filename="almostheaven_data_backup_' . date('Ymd_His') . '.zip"');
  readfile($tmp);
  @unlink($tmp);
  exit;
}

$restoreMsg = trim((string)($_GET['msg'] ?? '')) ?: null;
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['restore']) && $CAN_EDIT) {
  if (!class_exists('ZipArchive')) {
    smurf_redirect_self(['msg'=>'ZipArchive is not available on this server.']);
  } elseif (!isset($_FILES['zip']) || $_FILES['zip']['error'] !== UPLOAD_ERR_OK) {
    smurf_redirect_self(['msg'=>'Upload failed.']);
  } else {
    $zip = new ZipArchive();
    if ($zip->open($_FILES['zip']['tmp_name']) !== true) {
      smurf_redirect_self(['msg'=>'Could not open zip.']);
    } else {
      // Extract ONLY data/* into /data
      $ok = true;
      for ($i=0; $i<$zip->numFiles; $i++) {
        $name = $zip->getNameIndex($i);
        if ($name === false) continue;
        $name = str_replace('\\','/',$name);
        if (!str_starts_with($name, 'data/')) continue;
        $rel = substr($name, 5);
        if ($rel === '' || str_contains($rel, '..')) { $ok=false; break; }
        $dest = $dataDir . DIRECTORY_SEPARATOR . $rel;
        if (str_ends_with($name, '/')) {
          @mkdir($dest, 0775, true);
        } else {
          @mkdir(dirname($dest), 0775, true);
          copy('zip://' . $_FILES['zip']['tmp_name'] . '#' . $name, $dest);
        }
      }
      $zip->close();
      smurf_redirect_self(['msg'=>($ok ? 'Restore complete.' : 'Restore failed: invalid paths detected.')]);
    }
  }
}
include __DIR__ . '/includes/admin_header.php';
?>
<section class="content-card">
  <h1 class="admin-title">🧰 Backup / Restore</h1>
  <p style="opacity:.85;">One-click backup of <code>/data/*</code>. Restore from a backup zip if something breaks.</p>

  <div style="margin:10px 0 18px;">
    <a class="admin-btn" href="index.php">Back</a>
  </div>

  <?php if ($restoreMsg): ?>
    <div class="content-card" style="border-color:rgba(255,215,120,.55);"><?= htmlspecialchars($restoreMsg) ?></div>
  <?php endif; ?>

  <div class="admin-grid-2">
    <div class="content-card" style="text-align:left;">
      <h3 style="margin-top:0;">Download Backup</h3>
      <?php if ($CAN_EDIT): ?>
        <a class="admin-btn" href="backup.php?download=1">Download /data backup zip</a>
      <?php else: ?>
        <p style="opacity:.8;">You have view-only access.</p>
      <?php endif; ?>
      <p style="opacity:.75;margin-top:10px;">Tip: keep a few backups locally before making big changes.</p>
    </div>

    <div class="content-card" style="text-align:left;">
      <h3 style="margin-top:0;">Restore Backup</h3>
      <?php if ($CAN_EDIT): ?>
        <form method="post" action="backup.php" enctype="multipart/form-data" onsubmit="return confirm('Restore will overwrite files in /data. Continue?');">
          <label class="admin-label">Upload backup zip</label>
          <input class="admin-input" type="file" name="zip" accept=".zip" required>
          <button class="admin-btn" type="submit" name="restore" value="1">Restore Now</button>
        </form>
      <?php else: ?>
        <p style="opacity:.8;">You have view-only access.</p>
      <?php endif; ?>
    </div>
  </div>
</section>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
