<?php
require_once '../core/bootstrap.php';

// --- Admin Authentication & Authorization ---
// Only allow Super Admins to download backups for security
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'super_admin') {
    header('Location: dashboard.php');
    exit();
}

// Database configuration
$host = DB_HOST;
$user = DB_USER;
$pass = DB_PASS;
$name = DB_NAME;

// Get all tables
$tables = [];
$db = new Database();
$db->query('SHOW TABLES');
$result = $db->resultSet();

foreach ($result as $row) {
    $tables[] = reset($row);
}

$return = "";

// Cycle through each table
foreach ($tables as $table) {
    $db->query('SELECT * FROM ' . $table);
    $num_fields = $db->columnCount();
    $result = $db->resultSet(null, PDO::FETCH_NUM); // Fetch as numeric array

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

    foreach ($result as $row) {
        $return .= "INSERT INTO " . $table . " VALUES(";
        for ($j = 0; $j < $num_fields; $j++) {
            $row[$j] = addslashes($row[$j]);
            $row[$j] = str_replace("\n", "\\n", $row[$j]);
            if (isset($row[$j])) {
                $return .= '"' . $row[$j] . '"';
            } else {
                $return .= '""';
            }
            if ($j < ($num_fields - 1)) {
                $return .= ',';
            }
        }
        $return .= ");\n";
    }
    $return .= "\n\n\n";
}

// Save file
$filename = 'db-backup-' . time() . '-' . (md5(implode(',', $tables))) . '.sql';
$handle = fopen($filename, 'w+');
fwrite($handle, $return);
fclose($handle);

// Force Download
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($filename));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
ob_clean();
flush();
readfile($filename);
unlink($filename); // Delete file after download
exit;
?>