<?php
require_once '../config/database.php';
require_once '../config/auth_enhanced.php';

if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized access']);
    exit;
}

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

try {
    if (!isset($_FILES['backup_file']) || $_FILES['backup_file']['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('No backup file uploaded or upload error occurred');
    }
    
    $uploadedFile = $_FILES['backup_file'];
    $filename = $uploadedFile['name'];
    
    // Validate file extension
    if (!preg_match('/\.sql$/i', $filename)) {
        throw new Exception('Invalid file type. Only .sql files are allowed');
    }
    
    // Read the SQL file content
    $sqlContent = file_get_contents($uploadedFile['tmp_name']);
    if ($sqlContent === false) {
        throw new Exception('Failed to read backup file');
    }
    
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Disable foreign key checks temporarily
    $pdo->exec("SET FOREIGN_KEY_CHECKS = 0");
    
    // Split SQL content into individual statements
    $statements = preg_split('/;\s*$/m', $sqlContent);
    $statements = array_filter($statements, function($stmt) {
        return trim($stmt) !== '' && !preg_match('/^--/', trim($stmt));
    });
    
    $executedStatements = 0;
    $pdo->beginTransaction();
    
    try {
        foreach ($statements as $statement) {
            $statement = trim($statement);
            if (!empty($statement)) {
                $pdo->exec($statement);
                $executedStatements++;
            }
        }
        
        $pdo->commit();
        
        // Re-enable foreign key checks
        $pdo->exec("SET FOREIGN_KEY_CHECKS = 1");
        
        echo json_encode([
            'success' => true,
            'message' => 'Database restored successfully',
            'statements_executed' => $executedStatements,
            'restored_at' => date('Y-m-d H:i:s')
        ]);
        
    } catch (Exception $e) {
        $pdo->rollback();
        throw new Exception('Restore failed: ' . $e->getMessage());
    }
    
} catch (Exception $e) {
    // Re-enable foreign key checks even on error
    if (isset($pdo)) {
        try {
            $pdo->exec("SET FOREIGN_KEY_CHECKS = 1");
        } catch (Exception $cleanupError) {
            // Log cleanup error but don't override main error
            error_log("Failed to re-enable foreign key checks: " . $cleanupError->getMessage());
        }
    }
    
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
