<?php
/**
 * Bootstrap del sistema
 * Inicializa autoload, variables de entorno y configuración base
 */

// Definir directorio raíz del proyecto
define('ROOT_PATH', dirname(__DIR__));
define('PUBLIC_PATH', ROOT_PATH . '/public');
define('STORAGE_PATH', ROOT_PATH . '/storage');
define('CONFIG_PATH', ROOT_PATH . '/config');

// Autoload de Composer
require_once ROOT_PATH . '/vendor/autoload.php';

// Cargar variables de entorno
$dotenv = Dotenv\Dotenv::createImmutable(ROOT_PATH);
$dotenv->load();

// Configuración de errores según ambiente
if ($_ENV['APP_ENV'] === 'production') {
    ini_set('display_errors', '0');
    error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
} else {
    ini_set('display_errors', '1');
    error_reporting(E_ALL);
}

// Configuración de zona horaria
date_default_timezone_set('America/Bogota');

// Detectar HTTPS incluyendo proxies/load balancers
$isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
        || (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https')
        || (!empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] === 'on')
        || ($_SERVER['SERVER_PORT'] ?? 80) == 443;

// Configuración de sesiones
ini_set('session.cookie_httponly', '1');
ini_set('session.use_strict_mode', '1');
ini_set('session.cookie_samesite', 'Lax');
ini_set('session.cookie_secure', $isHttps ? '1' : '0');

// Iniciar sesión si no está iniciada
if (session_status() === PHP_SESSION_NONE) {
    session_name($_ENV['SESSION_COOKIE_NAME'] ?? 'contract_session');
    session_start();
}

// Headers de seguridad
header('X-Frame-Options: SAMEORIGIN');
header('X-Content-Type-Options: nosniff');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: strict-origin-when-cross-origin');

// Función helper para paths
function storage_path($path = '') {
    return STORAGE_PATH . ($path ? '/' . ltrim($path, '/') : '');
}

function config_path($path = '') {
    return CONFIG_PATH . ($path ? '/' . ltrim($path, '/') : '');
}

function public_path($path = '') {
    return PUBLIC_PATH . ($path ? '/' . ltrim($path, '/') : '');
}

function base_url($path = '') {
    return rtrim($_ENV['APP_URL'], '/') . ($path ? '/' . ltrim($path, '/') : '');
}

function asset_url($path) {
    return base_url('public/assets/' . ltrim($path, '/'));
}

// Datos de la empresa (disponibles en todo el sistema)
require_once CONFIG_PATH . '/company-data.php';
