<?php
header('Content-Type: application/json');

try {
    require_once '../config/db.php';

    // Check file upload
    if (!isset($_FILES['backup']) || $_FILES['backup']['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('No file uploaded or upload error occurred');
    }

    // Read and validate JSON
    $jsonData = file_get_contents($_FILES['backup']['tmp_name']);
    if (empty($jsonData)) {
        throw new Exception('Empty file uploaded');
    }

    $data = json_decode($jsonData, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Invalid JSON format');
    }

    // Disable foreign key checks temporarily
    $pdo->exec('SET FOREIGN_KEY_CHECKS = 0');
    
    // Start transaction
    $pdo->beginTransaction();

    try {
        // Import tables in correct order
        foreach ($data['order'] as $table) {
            $tableData = $data['tables'][$table];
            
            // Create or replace table
            $pdo->exec("DROP TABLE IF EXISTS `$table`");
            $pdo->exec($tableData['structure']);

            // Insert data if exists
            if (!empty($tableData['data'])) {
                foreach ($tableData['data'] as $row) {
                    $columns = array_keys($row);
                    $values = array_values($row);
                    $placeholders = str_repeat('?,', count($values) - 1) . '?';
                    
                    $sql = "INSERT INTO `$table` (`" . implode('`, `', $columns) . "`) VALUES ($placeholders)";
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute($values);
                }
            }
        }

        // Re-enable foreign key checks
        $pdo->exec('SET FOREIGN_KEY_CHECKS = 1');
        
        // Commit transaction
        $pdo->commit();

        echo json_encode([
            'success' => true,
            'message' => 'Database imported successfully! Tables created/updated: ' . count($data['order'])
        ]);

    } catch (Exception $e) {
        // Rollback on error
        $pdo->rollBack();
        throw $e;
    }

} catch (Exception $e) {
    // Re-enable foreign key checks
    if (isset($pdo)) {
        $pdo->exec('SET FOREIGN_KEY_CHECKS = 1');
    }

    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>