<?php
header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Test: Try to include config
$configPath = __DIR__ . '/../../config/database.php';
if (!file_exists($configPath)) {
    $configPath = __DIR__ . '/../../../config/database.php';
}
if (!file_exists($configPath)) {
    die(json_encode(['success' => false, 'message' => 'Config not found']));
}

$config = require $configPath;

// Get JSON input for dbname if provided
$jsonInput = json_decode(file_get_contents('php://input'), true);
$targetDb = $jsonInput['dbname'] ?? $_POST['dbname'] ?? $config['dbname'];

// Connect directly with PDO
try {
    $dsn = "mysql:host={$config['host']};dbname={$targetDb};charset={$config['charset']}";
    $pdo = new PDO($dsn, $config['user'], $config['pass'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
} catch (PDOException $e) {
    die(json_encode(['success' => false, 'message' => 'DB Connection failed to ' . $targetDb . ': ' . $e->getMessage()]));
}

$action = $_GET['action'] ?? '';

switch ($action) {
    case 'list':
        try {
            $stmt = $pdo->query("SELECT * FROM Roles ORDER BY designation");
            $result = $stmt->fetchAll();
            echo json_encode(['success' => true, 'data' => $result]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'execute_sql':
        $sql = $_POST['sql'] ?? $jsonInput['sql'] ?? '';
        $params = $_POST['params'] ?? $jsonInput['params'] ?? [];
        
        if (empty($sql)) {
            echo json_encode(['success' => false, 'message' => 'SQL vide']);
            exit;
        }
        
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            
            $response = ['success' => true, 'message' => 'Requête exécutée'];
            
            // Si c'est un SELECT, on retourne les données (trim pour ignorer espaces/newlines)
            $trimmedSql = ltrim($sql);
            $firstWord = strtoupper(explode(' ', $trimmedSql)[0]);
            if (in_array($firstWord, ['SELECT', 'DESCRIBE', 'SHOW'])) {
                $response['data'] = $stmt->fetchAll();
            }
            
            echo json_encode($response);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Erreur SQL: ' . $e->getMessage()]);
        }
        break;
        
    default:
        echo json_encode(['success' => false, 'message' => 'Action non reconnue']);
}
