<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'config.php';

// =========================
// CEK TOKEN
// =========================
if (!isset($_GET['token']) || $_GET['token'] !== BACKUP_TOKEN) {
    http_response_code(403);
    exit('Akses ditolak');
}

// =========================
// KONEKSI DATABASE
// =========================
$conn = new mysqli(
    "localhost",
    "zrlghzjw_bws",
    "Fendy!3707",
    "zrlghzjw_db_surat"
);

if ($conn->connect_error) {
    die("Koneksi gagal : " . $conn->connect_error);
}

$conn->set_charset("utf8mb4");

// =========================
// HEADER DOWNLOAD
// =========================
$filename = "db_" . date("Ymd_His") . ".sql";

header("Content-Type: application/sql");
header("Content-Disposition: attachment; filename=\"$filename\"");

// Header file SQL
echo "-- PETESA Backup\n";
echo "-- " . date("Y-m-d H:i:s") . "\n\n";

// Ambil semua tabel
$tables = [];

$result = $conn->query("SHOW TABLES");

while ($row = $result->fetch_array()) {
    $tables[] = $row[0];
}

foreach ($tables as $table) {

    echo "\n\n";
    echo "-- ==============================\n";
    echo "-- Table : $table\n";
    echo "-- ==============================\n\n";

    // Struktur tabel
    $create = $conn->query("SHOW CREATE TABLE `$table`")->fetch_assoc();

    echo "DROP TABLE IF EXISTS `$table`;\n";
    echo $create['Create Table'] . ";\n\n";

    // Isi tabel
    $rows = $conn->query("SELECT * FROM `$table`");

    while ($data = $rows->fetch_assoc()) {

        $values = [];

        foreach ($data as $value) {

            if (is_null($value)) {
                $values[] = "NULL";
            } else {
                $values[] = "'" . $conn->real_escape_string($value) . "'";
            }

        }

        echo "INSERT INTO `$table` VALUES (" . implode(",", $values) . ");\n";

    }

    echo "\n";

}

$conn->close();