<?php
// backup_auto.php - automatic database backup (daily)
require_once __DIR__ . '/config/db.php';

$backup_dir = __DIR__ . '/backups';
if (!is_dir($backup_dir)) mkdir($backup_dir, 0777, true);

$filename = $backup_dir . '/backup_' . date('Y-m-d_H-i-s') . '.sql';
$tables = [];
$res = $pdo->query("SHOW TABLES");
while ($row = $res->fetch(PDO::FETCH_NUM)) $tables[] = $row[0];

$sqlScript = "";
foreach ($tables as $table) {
    $stmt = $pdo->query("SHOW CREATE TABLE `$table`");
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $sqlScript .= "\n\n" . $row['Create Table'] . ";\n\n";
    $stmt2 = $pdo->query("SELECT * FROM `$table`");
    while ($r = $stmt2->fetch(PDO::FETCH_ASSOC)) {
        $vals = array_map(fn($v) => $pdo->quote($v), array_values($r));
        $sqlScript .= "INSERT INTO `$table` VALUES (" . implode(',', $vals) . ");\n";
    }
    $sqlScript .= "\n";
}
file_put_contents($filename, $sqlScript);
echo "✅ Backup created: $filename\n";
