<?php
declare(strict_types=1);

// 1. CONFIGURACIÓN DE ENTORNO Y HEADERS
ob_start(); 
ini_set('display_errors', '0');
ini_set('log_errors', '1');

ini_set('error_log', __DIR__ . '/../logs/api_errors.log'); 
error_reporting(E_ALL);

header('Content-Type: application/json; charset=utf-8');
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");

// 2. INICIO DE SESIÓN SEGURO
if (session_status() === PHP_SESSION_NONE) {
    $isSecure = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on';
    session_set_cookie_params([
        'lifetime' => 86400,
        'path'     => '/',
        'secure'   => $isSecure,
        'httponly' => true,
        'samesite' => 'Strict'
    ]);
    session_start();
}

// 3. CARGA DE DEPENDENCIAS CRÍTICAS
try {
    require_once __DIR__ . '/../db/db_connection.php';
    require_once __DIR__ . '/../files/guardiankey.php';
    require_once __DIR__ . '/security.php'; 
    require_once __DIR__ . '/modules.php';
    
    $DEFAULT_ROLES = require __DIR__ . '/roles.php';
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'msg_core_load_error', 'debug' => $e->getMessage()]);
    exit;
}

// 4. LÓGICA DE PERMISOS (CAPA 2)
$current_user_permissions = [];
$user_role_key = $_SESSION['role'] ?? '';
$user_role_id  = $_SESSION['role_id'] ?? null;
$is_owner      = ($user_role_key === 'owner');

if (!$is_owner) {
    $loaded_from_db = false;
    
    if ($user_role_id && isset($pdo)) {
        try {
            $stmtRole = $pdo->prepare("SELECT permissions FROM roles WHERE id = ? LIMIT 1");
            $stmtRole->execute([$user_role_id]);
            $roleData = $stmtRole->fetch(PDO::FETCH_ASSOC);
            
            if ($roleData && !empty($roleData['permissions'])) {
                $current_user_permissions = json_decode($roleData['permissions'], true) ?? [];
                $loaded_from_db = true;
            }
        } catch (Exception $e) {
            error_log("API Permission Load Error: " . $e->getMessage());
        }
    }

    if (!$loaded_from_db && !empty($user_role_key) && isset($DEFAULT_ROLES[$user_role_key])) {
        $current_user_permissions = $DEFAULT_ROLES[$user_role_key]['permissions'];
    }
}

// 5. FUNCIONES MAESTRAS DEL API
if (!function_exists('sendResponse')) {
    function sendResponse(bool $success, string $messageKey, mixed $data = [], int $httpCode = 200): void
    {
        if (ob_get_length()) ob_clean();
        
        http_response_code($httpCode);
        
        echo json_encode([
            'success' => $success,
            'message' => $messageKey, 
            'data'    => $data
        ]);
        exit; 
    }
}

if (!function_exists('can')) {
    function can(string $permission_key): bool {
        global $current_user_permissions, $is_owner;
        
        if ($is_owner) return true; 
        return !empty($current_user_permissions[$permission_key]);
    }
}

if (!function_exists('get_current_user_id')) {
    function get_current_user_id(): int {
        return isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : 0;
    }
}

// 6. MANEJADOR GLOBAL DE EXCEPCIONES
set_exception_handler(function ($e) {
    error_log("Uncaught API Exception: " . $e->getMessage() . " in " . $e->getFile() . ":" . $e->getLine());
    sendResponse(false, 'msg_error_internal', [], 500);
});
?>