<?php
session_start();
if (!isset($_SESSION['username'])) {
    echo "<script>window.top.location.href='index.php';</script>"; // Redirect parent window to login page
    exit();
}


$host = "localhost";
$username = "tnyowsjv_lamile";
$password = "2wTFC65&*9masqx6%@r4";
$database = "tnyowsjv_crudalamile";

// Connect to database
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$conn->set_charset("utf8");

// Get all tables
$tables = [];
$result = $conn->query("SHOW TABLES");
while ($row = $result->fetch_array()) {
    $tables[] = $row[0];
}

// Start dump
$dump = "-- Database: `$database`\n";
$dump .= "-- Exported on: " . date("Y-m-d H:i:s") . "\n\n";

foreach ($tables as $table) {
    // Drop if exists
    $dump .= "DROP TABLE IF EXISTS `$table`;\n";

    // Table creation
    $res = $conn->query("SHOW CREATE TABLE `$table`");
    $row = $res->fetch_assoc();
    $dump .= $row['Create Table'] . ";\n\n";

    // Data insertions
    $res = $conn->query("SELECT * FROM `$table`");
    while ($row = $res->fetch_assoc()) {
        $values = array_map(function ($v) use ($conn) {
            return isset($v) ? "'" . $conn->real_escape_string($v) . "'" : "NULL";
        }, $row);
        $dump .= "INSERT INTO `$table` VALUES (" . implode(", ", $values) . ");\n";
    }

    $dump .= "\n";
}

// Send headers and dump content for download
$filename = "backup_" . $database . "_" . date("Y-m-d_H-i-s") . ".sql";

header('Content-Type: application/sql');
header("Content-Disposition: attachment; filename=\"$filename\"");
header('Content-Length: ' . strlen($dump));
header('Pragma: no-cache');
header('Expires: 0');

echo $dump;
exit;
?>
