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

// Check if admin is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

// Get all tables
$tables = [];
$stmt = $pdo->query("SHOW TABLES");
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
    $tables[] = $row[0];
}

$backup = "-- Database Backup\n";
$backup .= "-- Generated: " . date('Y-m-d H:i:s') . "\n";
$backup .= "-- Host: " . DB_HOST . "\n";
$backup .= "-- Database: " . DB_NAME . "\n\n";
$backup .= "SET FOREIGN_KEY_CHECKS=0;\n\n";

foreach ($tables as $table) {
    // Get create table syntax
    $stmt = $pdo->query("SHOW CREATE TABLE $table");
    $create = $stmt->fetch(PDO::FETCH_ASSOC);
    $backup .= "-- Table structure for table `$table`\n";
    $backup .= "DROP TABLE IF EXISTS `$table`;\n";
    $backup .= $create['Create Table'] . ";\n\n";
    
    // Get data
    $stmt = $pdo->query("SELECT * FROM $table");
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (count($rows) > 0) {
        $backup .= "-- Dumping data for table `$table`\n";
        
        foreach ($rows as $row) {
            $columns = array_keys($row);
            $values = array_map(function($value) use ($pdo) {
                if ($value === null) return 'NULL';
                return $pdo->quote($value);
            }, array_values($row));
            
            $backup .= "INSERT INTO `$table` (`" . implode('`, `', $columns) . "`) VALUES (" . implode(', ', $values) . ");\n";
        }
        $backup .= "\n";
    }
}

$backup .= "SET FOREIGN_KEY_CHECKS=1;\n";

// Set headers for download
header('Content-Type: application/sql');
header('Content-Disposition: attachment; filename="backup_' . date('Y-m-d_H-i-s') . '.sql"');
header('Content-Length: ' . strlen($backup));

echo $backup;
exit;
?>