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

if (!isset($_POST['query'])) {
    echo json_encode([
        'success' => false,
        'error' => 'No query specified'
    ]);
    exit;
}

try {
    if (!isset($_SESSION['current_db_file'])) {
        throw new Exception('Database connection not selected');
    }

    require_once $_SESSION['current_db_file'];
    
    if (!isset($pdo)) {
        throw new Exception('Database connection failed');
    }

    $query = $_POST['query'];
    $results = $pdo->query($query)->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'success' => true,
        'results' => $results
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}