<?php
/**
 * API Admin - Entry Point
 * Painel de Gerenciamento de Sites e Configurações
 * 
 * ARQUITETURA MODULAR:
 * - /core         → Classes utilitárias (Request, Response, Router)
 * - /middleware   → Autenticação e autorização
 * - /controllers  → Lógica de negócio separada por domínio
 * 
 * @version 2.0.0
 */

// ===============================
// CONFIGURAÇÕES INICIAIS
// ===============================

// Remover headers que expõem informações do servidor
header_remove('X-Powered-By');
ini_set('expose_php', 'off');

// Headers CORS e JSON
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

// Preflight request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit(0);
}

// ===============================
// AUTOLOADER
// ===============================

spl_autoload_register(function ($class) {
    // Mapear namespaces para diretórios
    $namespaceMap = [
        'Core\\' => __DIR__ . '/core/',
        'Middleware\\' => __DIR__ . '/middleware/',
        'Controllers\\' => __DIR__ . '/controllers/',
    ];
    
    foreach ($namespaceMap as $namespace => $dir) {
        if (strpos($class, $namespace) === 0) {
            $relativeClass = substr($class, strlen($namespace));
            $file = $dir . str_replace('\\', '/', $relativeClass) . '.php';
            
            if (file_exists($file)) {
                require_once $file;
                return true;
            }
        }
    }
    
    return false;
});

// ===============================
// DEPENDÊNCIAS
// ===============================

// Carregar configuração do banco de dados (funções globais)
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/controllers/TrackController.php';
require_once __DIR__ . '/controllers/ApiKeyController.php';

// Iniciar sessão
session_start();

// ===============================
// IMPORTAR CLASSES
// ===============================

use Core\Request;
use Core\Response;
use Core\Router;

// ===============================
// TRATAMENTO DE ERROS
// ===============================

// TEMPORÁRIO: Ativar debug
define('DEBUG', true);
error_reporting(E_ALL);
ini_set('display_errors', 0); // Alterado para 0 para não quebrar JSON

set_exception_handler(function (Throwable $e) {
    error_log("API Error: " . $e->getMessage() . "\n" . $e->getTraceAsString());
    
    Response::json([
        'status' => 'error',
        'message' => 'Internal server error',
        'debug' => $e->getMessage(),
        'file' => $e->getFile(),
        'line' => $e->getLine()
    ], 500);
});

// ===============================
// ROTEAMENTO
// ===============================

$method = Request::method();
$action = Request::get('action', '');

// Validar action
if (empty($action)) {
    Response::json([
        'status' => 'success',
        'message' => 'Admin API v2.0.0',
        'endpoints' => [
            'POST /admin.php?action=login' => 'Autenticar',
            'POST /admin.php?action=logout' => 'Encerrar sessão',
            'GET /admin.php?action=me' => 'Info do usuário logado',
            'GET /admin.php?action=dashboard' => 'Dashboard',
            'GET /admin.php?action=sites' => 'Listar sites',
            'GET /admin.php?action=events' => 'Listar eventos',
            'GET /admin.php?action=users' => 'Listar usuários',
            'GET|POST /admin.php?action=pix-config' => 'Config PIX',
            'POST /admin.php?action=track' => 'Track Visit',
            'GET /admin.php?action=api-keys' => 'Listar API Placas Keys',
            'POST /admin.php?action=toggle-api-key' => 'Alternar status da Key',
            'GET /admin.php?action=ip' => 'Consultar GeoIP (ip-api)',
        ]
    ]);
}

// Rota GeoIP Proxy
if ($action === 'ip' && $method === 'GET') {
    \Controllers\TrackController::getIpDetails();
    exit;
}

// Mapeamento manual para o router simplificado
if ($action === 'track') {
    // Se for requisicao de imagem (Pixel), processar via GET
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        \Controllers\TrackController::record();
        header('Content-Type: image/gif');
        echo base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
        exit;
    }
    \Controllers\TrackController::record();
    exit;
}

// API Placas Keys Actions
if ($action === 'api-keys' && $method === 'GET') {
    \Controllers\ApiKeyController::list();
    exit;
}

if ($action === 'toggle-api-key' && $method === 'POST') {
    \Controllers\ApiKeyController::toggle();
    exit;
}

// Limpar logs (apenas para super admins)
if ($action === 'clear-logs' && $method === 'POST') {
    \Controllers\DashboardController::clearLogs();
    exit;
}

// Confirmar PIX (apenas para super admins)
if ($action === 'confirm-pix' && $method === 'POST') {
    \Controllers\DashboardController::confirmPix();
    exit;
}

// Obter consulta específica
if ($action === 'get-consulta' && $method === 'GET') {
    \Controllers\DashboardController::getConsulta();
    exit;
}

// Configurações de Notificações
if ($action === 'get-notif-config' && $method === 'GET') {
    \Controllers\DashboardController::getNotifConfig();
    exit;
}

if ($action === 'save-notif-config' && $method === 'POST') {
    \Controllers\DashboardController::saveNotifConfig();
    exit;
}

// Controle de IPs
if ($action === 'get-ip-rules' && $method === 'GET') {
    \Controllers\DashboardController::getIpRules();
    exit;
}

if ($action === 'add-ip-rule' && $method === 'POST') {
    \Controllers\DashboardController::addIpRule();
    exit;
}

if ($action === 'delete-ip-rule' && $method === 'POST') {
    \Controllers\DashboardController::deleteIpRule();
    exit;
}

if ($action === 'list-data' && $method === 'GET') {
    \Controllers\DashboardController::listData();
    exit;
}

// Ações processadas pelo roteador central
$routerActions = [
    'sites', 'site', 'users', 'user', 'permissions', 'site-users', 
    'pix-config', 'pix-history', 'pix-stats', 'dashboard', 'events', 
    'api-tokens', 'api-token-item', 'api-token-test', 'security-config',
    'audit-logs', 'security-logs', 'sites/regenerate-key', 'api-token'
];

if (in_array($action, $routerActions) || strpos($action, '/') !== false) {
    try {
        Router::dispatch($action, $method);
        exit;
    } catch (Throwable $e) {
        error_log("Router Error ($action): " . $e->getMessage());
        Response::json(['status' => 'error', 'message' => $e->getMessage()], 500);
    }
}

// Despachar para o router (Fallback)
try {
    Router::dispatch($action, $method);
} catch (Throwable $e) {
    error_log("Router Error: " . $e->getMessage() . " in " . $e->getFile() . ":" . $e->getLine());
    Response::json([
        'status' => 'error',
        'message' => 'Failed to process request',
        'debug' => $e->getMessage(),
        'file' => basename($e->getFile()),
        'line' => $e->getLine()
    ], 500);
}
