<?php
// One-click full database backup (Section 18, C2, Phase 11). Generated
// entirely via PDO — no mysqldump/shell dependency, so this works on
// shared hosting where a shell isn't available. A plain link download
// (browser handles Content-Disposition natively); no fetch/JS needed.

require_once __DIR__ . '/../includes/auth.php';
require_login();
require_admin(); // Backup is Motaher-only (Section 3 role split).

$db = get_db();
$tables = $db->query('SHOW TABLES')->fetchAll(PDO::FETCH_COLUMN);

header('Content-Type: application/sql; charset=utf-8');
header('Content-Disposition: attachment; filename="backup_' . date('Y-m-d') . '.sql"');

echo "-- 月账 Monthly Ledger — full backup\n";
echo "-- Generated " . date('Y-m-d H:i:s') . "\n";
echo "-- Restore: create an empty database, then import this file directly\n";
echo "-- (it includes CREATE TABLE statements — no need to run schema.sql first).\n\n";
echo "SET NAMES utf8mb4;\nSET FOREIGN_KEY_CHECKS = 0;\n\n";

foreach ($tables as $table) {
    $createRow = $db->query("SHOW CREATE TABLE `$table`")->fetch();
    echo "DROP TABLE IF EXISTS `$table`;\n";
    echo $createRow['Create Table'] . ";\n\n";

    $rows = $db->query("SELECT * FROM `$table`")->fetchAll(PDO::FETCH_ASSOC);
    if ($rows) {
        $columns = array_keys($rows[0]);
        $columnList = '`' . implode('`, `', $columns) . '`';
        $valueLines = [];
        foreach ($rows as $row) {
            $values = array_map(
                fn ($v) => $v === null ? 'NULL' : $db->quote((string) $v),
                array_values($row)
            );
            $valueLines[] = '(' . implode(', ', $values) . ')';
        }
        echo "INSERT INTO `$table` ($columnList) VALUES\n" . implode(",\n", $valueLines) . ";\n\n";
    }
}

echo "SET FOREIGN_KEY_CHECKS = 1;\n";
