<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Database;
use App\Core\View;
use App\Services\SqlConsoleService;

/**
 * Controla o SQL Console seguro.
 */
class SqlConsoleController
{
    // -------------------------------------------------------------------------
    // GET /sql-console — página do console
    // -------------------------------------------------------------------------

    public function index(): void
    {
        if (!Database::estaConfigurado()) {
            header('Location: /configurar');
            exit;
        }
        Auth::verificarOuRedirecionar();

        $config = $this->carregarConfig();
        $status = Database::verificar();

        View::render('sqlconsole/index', [
            'titulo'  => 'SQL Console — Premium Express Gestão',
            'config'  => $config,
            'conexao' => $status,
        ]);
    }

    // -------------------------------------------------------------------------
    // POST /sql-console/executar — executa SQL e retorna JSON
    // -------------------------------------------------------------------------

    public function executar(): void
    {
        header('Content-Type: application/json; charset=UTF-8');

        if (!Auth::estaLogado()) {
            echo json_encode(['sucesso' => false, 'erro' => 'Não autorizado.'], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
            return;
        }

        $sql = trim($_POST['sql'] ?? '');

        if (empty($sql)) {
            echo json_encode(['sucesso' => false, 'erro' => 'Nenhuma consulta enviada.'], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
            return;
        }

        $svc      = new SqlConsoleService();
        $resultado = $svc->executar($sql);

        echo json_encode($resultado, JSON_UNESCAPED_UNICODE | JSON_PARTIAL_OUTPUT_ON_ERROR);
    }

    // -------------------------------------------------------------------------
    // Interno
    // -------------------------------------------------------------------------

    private function carregarConfig(): array
    {
        $path = dirname(__DIR__, 2) . '/config/database.php';
        return file_exists($path) ? (require $path) : [];
    }
}
