<?php
declare(strict_types=1);

ob_start();

if (session_status() === PHP_SESSION_NONE) {
    $isSecure = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on';
    session_set_cookie_params([
        'lifetime' => 86400,
        'path'     => '/',
        'domain'   => '',
        'secure'   => $isSecure,
        'httponly' => true,
        'samesite' => 'Strict'
    ]);
    session_start();
}

if (empty($_SESSION['csrf_token'])) {
    try {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    } catch (Throwable $e) {
        $_SESSION['csrf_token'] = sha1(uniqid((string)mt_rand(), true));
    }
}

ini_set('display_errors', '1');
ini_set('log_errors', '1');
ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
error_reporting(E_ALL);

// 1. SEGURIDAD
require_once __DIR__ . '/../files/guardiankey.php';
require_once __DIR__ . '/../db/db_connection.php';
require_once __DIR__ . '/security.php';

// 2. BRANDING Y DATOS DEL NEGOCIO (Solo datos, nada de lógica)
$brandingFile = __DIR__ . '/../brand/branding.php';
if (file_exists($brandingFile)) {
    require_once $brandingFile;
}
require_once __DIR__ . '/business-information.php';

// 3. CONFIGURACIÓN DEL SISTEMA (Aquí entra tu nueva lógica)
require_once __DIR__ . '/timezone.php';
require_once __DIR__ . '/formatters.php';
require_once __DIR__ . '/image_optimizer.php';
require_once __DIR__ . '/modules.php'; // <--- NUEVO: Carga la lógica de ocultar secciones

// 4. PERMISOS Y ROLES
$ALL_PERMISSIONS_CONFIG = require __DIR__ . '/permissions.php';
$DEFAULT_ROLES          = require __DIR__ . '/roles.php';

$user_role_key = $_SESSION['role'] ?? '';
$user_role_id  = $_SESSION['role_id'] ?? null;
$is_owner      = ($user_role_key === 'owner');

$current_user_permissions = [];

if (!$is_owner) {
    $loaded_from_db = false;
    if ($user_role_id) {
        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("Error cargando permisos DB: " . $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. IDIOMAS
$lang_code = $_SESSION['lang'] ?? 'es'; 
$base_lang_dir = __DIR__ . '/lang/main/';       
$user_lang_dir = __DIR__ . "/lang/{$lang_code}/"; 

$TRANSLATIONS = [];

if (is_dir($base_lang_dir)) {
    $files = glob($base_lang_dir . '*.php');
    if ($files) {
        foreach ($files as $file) {
            $filename = basename($file);
            $base_trans = require $file;
            if (!is_array($base_trans)) continue;

            $user_file = $user_lang_dir . $filename;
            if ($lang_code && file_exists($user_file)) {
                $user_trans = require $user_file;
                if (is_array($user_trans)) {
                    $base_trans = array_merge($base_trans, $user_trans);
                }
            }
            $TRANSLATIONS = array_merge($TRANSLATIONS, $base_trans);
        }
    }
}

// HELPERS GLOBALES
if (!function_exists('can')) {
    function can($permission_key) {
        global $current_user_permissions, $is_owner;
        if ($is_owner) return true;
        return !empty($current_user_permissions[$permission_key]);
    }
}

if (!function_exists('__')) {
    function __($key) {
        global $TRANSLATIONS;
        return $TRANSLATIONS[$key] ?? $key;
    }
}

if (!function_exists('__status')) {
    function __status($prefix, $db_value) {
        $normalized = strtolower(str_replace(' ', '_', trim((string)$db_value)));
        return __($prefix . '_' . $normalized);
    }
}
?>