<?php
require_once '../config.php';

if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] ?? '') !== 'admin') {
    http_response_code(403);
    echo 'Forbidden';
    exit;
}

@set_time_limit(0);
$mysqli->set_charset('utf8');

$db_name = DB_NAME;
$timestamp = date('Ymd_His');
$filename = $db_name . '_backup_' . $timestamp . '.sql';

$sql_dump = "-- NextHM Database Backup\n";
$sql_dump .= "-- Database: `" . $db_name . "`\n";
$sql_dump .= "-- Generated: " . date('Y-m-d H:i:s') . "\n\n";
$sql_dump .= "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\n";
$sql_dump .= "SET time_zone = \"+00:00\";\n\n";
$sql_dump .= "/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\n";
$sql_dump .= "/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\n";
$sql_dump .= "/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\n";
$sql_dump .= "/*!40101 SET NAMES utf8 */;\n\n";

$tables_result = $mysqli->query("SHOW TABLES");
if (!$tables_result) {
    http_response_code(500);
    echo 'Failed to fetch tables: ' . $mysqli->error;
    exit;
}

$tables = [];
while ($row = $tables_result->fetch_row()) {
    $tables[] = $row[0];
}

foreach ($tables as $table) {
    $create_result = $mysqli->query("SHOW CREATE TABLE `" . $table . "`");
    if (!$create_result) {
        continue;
    }
    $create_row = $create_result->fetch_assoc();
    if (!$create_row || !isset($create_row['Create Table'])) {
        continue;
    }

    $sql_dump .= "-- --------------------------------------------------------\n";
    $sql_dump .= "-- Table structure for table `" . $table . "`\n";
    $sql_dump .= "-- --------------------------------------------------------\n\n";
    $sql_dump .= "DROP TABLE IF EXISTS `" . $table . "`;\n";
    $sql_dump .= $create_row['Create Table'] . ";\n\n";

    $data_result = $mysqli->query("SELECT * FROM `" . $table . "`");
    if (!$data_result || $data_result->num_rows === 0) {
        continue;
    }

    $sql_dump .= "-- Dumping data for table `" . $table . "`\n";
    while ($data_row = $data_result->fetch_assoc()) {
        $columns = [];
        $values = [];

        foreach ($data_row as $column => $value) {
            $columns[] = "`" . $column . "`";
            if (is_null($value)) {
                $values[] = "NULL";
            } else {
                $values[] = "'" . $mysqli->real_escape_string($value) . "'";
            }
        }

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

$sql_dump .= "/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\n";
$sql_dump .= "/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\n";
$sql_dump .= "/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;\n";

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

echo $sql_dump;
exit;
?>
