<?php
// DAILY AUTO BACKUP

require_once __DIR__ . '/../config/db.php';
date_default_timezone_set('Asia/Beirut');

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

$date = date('Y-m-d_H-i-s');
$filename = "backup_$date.sql";
$filepath = "$backupDir/$filename";

try {
    // الحصول على جميع الجداول
    $tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);

    $sql = "-- AUTO BACKUP: $date\nSET FOREIGN_KEY_CHECKS=0;\n\n";

    foreach ($tables as $table) {

        // إنشاء الجدول
        $create = $pdo->query("SHOW CREATE TABLE `$table`")->fetch(PDO::FETCH_ASSOC);
        $sql .= "DROP TABLE IF EXISTS `$table`;\n" . $create['Create Table'] . ";\n\n";

        // البيانات
        $rows = $pdo->query("SELECT * FROM `$table`")->fetchAll(PDO::FETCH_ASSOC);
        foreach ($rows as $row) {
            $values = array_map(function($v) use($pdo) {
                return $pdo->quote($v);
            }, array_values($row));

            $sql .= "INSERT INTO `$table` VALUES (" . implode(',', $values) . ");\n";
        }

        $sql .= "\n";
    }

    $sql .= "SET FOREIGN_KEY_CHECKS=1;\n";

    file_put_contents($filepath, $sql);

    echo "Backup created: $filename\n";

} catch (Exception $e) {
    file_put_contents("$backupDir/error_log.txt", $e->getMessage());
    echo "Error: " . $e->getMessage();
}
?>
