<?php
require_once 'db_config.php';

header('Content-Type: application/json');

try {
    $tables = [];
    $result = $db->query("SHOW TABLES");
    while ($row = $result->fetch(PDO::FETCH_NUM)) {
        $tables[] = $row[0];
    }

    $sqlScript = "";
    foreach ($tables as $table) {
        $result = $db->query("SELECT * FROM $table");
        $numColumns = $result->columnCount();

        $sqlScript .= "DROP TABLE IF EXISTS $table;";
        $row2 = $db->query("SHOW CREATE TABLE $table")->fetch(PDO::FETCH_NUM);
        $sqlScript .= "\n\n" . $row2[1] . ";\n\n";

        while ($row = $result->fetch(PDO::FETCH_NUM)) {
            $sqlScript .= "INSERT INTO $table VALUES(";
            for ($j = 0; $j < $numColumns; $j++) {
                $row[$j] = $row[$j];
                
                if (isset($row[$j])) {
                    $sqlScript .= '"' . addslashes($row[$j]) . '"';
                } else {
                    $sqlScript .= '""';
                }
                if ($j < ($numColumns - 1)) {
                    $sqlScript .= ',';
                }
            }
            $sqlScript .= ");\n";
        }
        $sqlScript .= "\n"; 
    }

    $backup_file_name = 'database_backup_' . date('Y-m-d_H-i-s') . '.sql';
    $backup_path = 'backups/' . $backup_file_name;
    
    if (!is_dir('backups')) {
        mkdir('backups', 0777, true);
    }
    
    file_put_contents($backup_path, $sqlScript);

    echo json_encode(['success' => true, 'file' => $backup_file_name]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Backup failed: ' . $e->getMessage()]);
}
?>
