<?php
// api/backup.php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

requireRole('admin'); // Security check handled by session usually, but since this is direct file access, we need to init session

if (!hasRole('admin')) {
    die("Access Denied");
}

// Configuration
$backup_file = 'backup_' . date('Y-m-d_H-i-s') . '.sql';

// Headers to force download
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($backup_file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');

// Generate SQL
echo "-- WCS Admin Backup\n";
echo "-- Date: " . date('Y-m-d H:i:s') . "\n\n";

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

foreach ($tables as $table) {
    echo "-- Table: $table\n";
    
    // Check if View
    $isView = false;
    $createStmt = $pdo->query("SHOW CREATE TABLE `$table`")->fetch(PDO::FETCH_NUM);
    $createSql = $createStmt[1];
    
    if (stripos($createSql, 'CREATE VIEW') !== false || stripos($createSql, 'ALGORITHM') !== false) {
        $isView = true;
    }

    if ($isView) {
        echo "DROP VIEW IF EXISTS `$table`;\n";
        echo $createSql . ";\n\n";
        // Do NOT export data for views
    } else {
        echo "DROP TABLE IF EXISTS `$table`;\n";
        echo $createSql . ";\n\n";
        
        // Data
        $rows = $pdo->query("SELECT * FROM `$table`");
        while ($row = $rows->fetch(PDO::FETCH_ASSOC)) {
            echo "INSERT INTO `$table` VALUES (";
            $vals = [];
            foreach ($row as $key => $val) {
                 if ($val === null) {
                     $vals[] = "NULL";
                 } else {
                     $vals[] = $pdo->quote($val);
                 }
            }
            // Fix: Handle empty tables or weird types? usually quote handles it.
            echo implode(",", $vals);
            echo ");\n";
        }
    }
    echo "\n";
}
exit;
?>
