<?php

namespace App\Controllers;

use App\Core\Database;
use App\Core\View;
use App\Services\TabelasService;

/**
 * Controla o explorador de tabelas do banco Firebird.
 */
class TabelasController
{
    // -------------------------------------------------------------------------
    // GET /tabelas — página principal do explorador
    // -------------------------------------------------------------------------

    public function index(): void
    {
        // Limpa opcache para que edições no index.php sejam aplicadas imediatamente
        if (function_exists('opcache_reset')) opcache_reset();

        // Se não houver configuração, redireciona para o setup
        if (!Database::estaConfigurado()) {
            header('Location: /configurar');
            exit;
        }

        $status = Database::verificar();

        View::render('tabelas/index', [
            'titulo'  => 'Explorador de Tabelas — Premium Express Gestão',
            'conexao' => $status,
            'config'  => $this->carregarConfig(),
        ]);
    }

    // -------------------------------------------------------------------------
    // GET /tabelas/listar — lista todas as tabelas (JSON, AJAX)
    // -------------------------------------------------------------------------

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

        try {
            $svc     = new TabelasService();
            $tabelas = $svc->listarTabelas();

            echo json_encode([
                'success' => true,
                'total'   => count($tabelas),
                'tabelas' => $tabelas,
            ], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);

        } catch (\Throwable $e) {
            http_response_code(500);
            echo json_encode([
                'success'  => false,
                'mensagem' => $e->getMessage(),
            ], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
        }
    }

    // -------------------------------------------------------------------------
    // GET /tabelas/info/:nome — detalhes de uma tabela (JSON, AJAX)
    // -------------------------------------------------------------------------

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

        // Sanitiza o nome da tabela (apenas alfanumérico + underscore + $)
        $nome = strtoupper(preg_replace('/[^A-Z0-9_$]/i', '', $nome));

        if (empty($nome)) {
            http_response_code(400);
            echo json_encode(['success' => false, 'mensagem' => 'Nome de tabela inválido.']);
            return;
        }

        try {
            $svc     = new TabelasService();
            $detalhe = $svc->detalheTabela($nome);
            $preview = $svc->preview($nome, 5);

            echo json_encode([
                'success'         => true,
                'tabela'          => $nome,
                'total_registros' => $detalhe['total_registros'],
                'colunas'         => $detalhe['colunas'],
                'preview'         => $preview,
            ], JSON_UNESCAPED_UNICODE | JSON_PARTIAL_OUTPUT_ON_ERROR);

        } catch (\Throwable $e) {
            http_response_code(500);
            echo json_encode([
                'success'  => false,
                'mensagem' => $e->getMessage(),
            ], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
        }
    }

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

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