<?php
require_once 'cors.php';
setupCORS(); // Call the CORS setup function first

require_once 'bd/myData.php';
require_once 'auth.php';

try {
    // Get POST data
    $input = json_decode(file_get_contents('php://input'), true);
    $format = $input['format'] ?? 'sql';
    $selectedTables = $input['tables'] ?? [];
    
    connect();
    global $pdo, $bd;

    // Validate selected tables against actual database tables
    $stmt = $pdo->query("SHOW TABLES");
    $actualTables = $stmt->fetchAll(PDO::FETCH_COLUMN);
    $selectedTables = array_intersect($selectedTables, $actualTables);

    if (empty($selectedTables)) {
        throw new Exception('No valid tables selected for export');
    }

    // Clear any existing output buffers
    while (ob_get_level()) {
        ob_end_clean();
    }

    // Set appropriate headers based on format
    switch ($format) {
        case 'json':
            header('Content-Type: application/json; charset=utf-8');
            header('Content-Disposition: attachment; filename=database_export_' . date('Y-m-d_H-i-s') . '.json');
            break;
        case 'csv':
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename=database_export_' . date('Y-m-d_H-i-s') . '.csv');
            break;
        default:
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename=backup_' . $bd . '_' . date('Y-m-d_H-i-s') . '.sql');
            break;
    }

    // Reset CORS headers after setting content headers
    header('Access-Control-Allow-Origin: http://localhost:3000');
    header('Access-Control-Allow-Credentials: true');
    
    // Your existing export logic remains the same
    switch ($format) {
        case 'json':
            $database = array();
            foreach ($selectedTables as $table) {
                $stmt = $pdo->query("SELECT * FROM `$table`");
                $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                $stmt = $pdo->query("SHOW CREATE TABLE `$table`");
                $tableStructure = $stmt->fetch(PDO::FETCH_ASSOC);
                
                $database[$table] = [
                    'structure' => $tableStructure['Create Table'],
                    'data' => $rows
                ];
            }
            
            echo json_encode($database, JSON_PRETTY_PRINT);
            break;

        case 'csv':
            foreach ($selectedTables as $table) {
                echo "### Table: $table ###\n";
                
                $stmt = $pdo->query("DESCRIBE `$table`");
                $columns = $stmt->fetchAll(PDO::FETCH_COLUMN);
                
                echo implode(',', array_map(function($value) {
                    return '"' . str_replace('"', '""', $value) . '"';
                }, $columns)) . "\n";
                
                $stmt = $pdo->query("SELECT * FROM `$table`");
                while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
                    echo implode(',', array_map(function($value) {
                        if ($value === null) return '""';
                        return '"' . str_replace('"', '""', $value) . '"';
                    }, $row)) . "\n";
                }
                echo "\n";
            }
            break;

        default:
            echo "-- Partial Database Backup\n";
            echo "-- Database: " . $bd . "\n";
            echo "-- Generated on: " . date('Y-m-d H:i:s') . "\n";
            echo "-- Server version: " . $pdo->getAttribute(PDO::ATTR_SERVER_VERSION) . "\n\n";
            
            echo "SET FOREIGN_KEY_CHECKS=0;\n";
            echo "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\n";
            echo "START TRANSACTION;\n\n";

            foreach ($selectedTables as $table) {
                $stmt = $pdo->query("
                    SELECT 
                        TABLE_NAME,
                        COLUMN_NAME,
                        REFERENCED_TABLE_NAME,
                        REFERENCED_COLUMN_NAME
                    FROM
                        INFORMATION_SCHEMA.KEY_COLUMN_USAGE
                    WHERE
                        REFERENCED_TABLE_NAME IS NOT NULL
                        AND TABLE_NAME = '$table'
                ");
                $dependencies = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                echo "\nDROP TABLE IF EXISTS `$table`;\n";
                $stmt = $pdo->query("SHOW CREATE TABLE `$table`");
                $row = $stmt->fetch(PDO::FETCH_NUM);
                echo $row[1] . ";\n\n";
                
                $stmt = $pdo->query("SELECT * FROM `$table`");
                $rows = $stmt->fetchAll(PDO::FETCH_NUM);
                
                if (!empty($rows)) {
                    $values = array();
                    foreach ($rows as $row) {
                        $row = array_map(function($value) use ($pdo) {
                            if ($value === null) return 'NULL';
                            return $pdo->quote($value);
                        }, $row);
                        $values[] = '(' . implode(',', $row) . ')';
                    }
                    
                    foreach (array_chunk($values, 1000) as $chunk) {
                        echo "INSERT INTO `$table` VALUES\n" . implode(",\n", $chunk) . ";\n";
                    }
                }
            }
            
            echo "\nSET FOREIGN_KEY_CHECKS=1;\n";
            echo "COMMIT;\n";
            break;
    }
    
} catch (Exception $e) {
    // Clear any output buffers
    while (ob_get_level()) {
        ob_end_clean();
    }
    
    // Reset headers for error response
    header('HTTP/1.1 500 Internal Server Error');
    header('Content-Type: application/json');
    header('Access-Control-Allow-Origin: http://localhost:3000');
    header('Access-Control-Allow-Credentials: true');
    
    echo json_encode([
        'error' => $e->getMessage(),
        'details' => 'Check server logs for more information'
    ]);
} finally {
    if (isset($pdo)) {
        disconnect();
    }
}