<?php

use Illuminate\Foundation\Application;
use Illuminate\Http\Request;

define('LARAVEL_START', microtime(true));

// If the framework fails to bootstrap (common on shared hosting), Laravel's
// normal logging may not be available. We log a minimal message to the server
// error log to make HTTP 500 diagnosable without SSH.
ini_set('log_errors', '1');

try {
    // Determine if the application is in maintenance mode...
    if (file_exists($maintenance = __DIR__.'/../storage/framework/maintenance.php')) {
        require $maintenance;
    }

    // Register the Composer autoloader...
    $autoloadPath = __DIR__.'/../vendor/autoload.php';
    if (! file_exists($autoloadPath)) {
        http_response_code(500);
        error_log('Laravel bootstrap failed: vendor/autoload.php not found. Did you upload vendor/ or run composer install?');
        echo 'Error 500: dependencias no instaladas (falta vendor/).';
        exit;
    }

    require $autoloadPath;

    // Bootstrap Laravel and handle the request...
    /** @var Application $app */
    $app = require_once __DIR__.'/../bootstrap/app.php';

    $app->handleRequest(Request::capture());
} catch (Throwable $e) {
    http_response_code(500);

    $errorId = bin2hex(random_bytes(6));
    $errorMessage = sprintf(
        '[%s] Laravel bootstrap failed: %s in %s:%d',
        $errorId,
        $e->getMessage(),
        $e->getFile(),
        $e->getLine(),
    );

    $trace = $e->getTraceAsString();
    $fullMessage = $errorMessage . "\n" . $trace;

    error_log($fullMessage);

    // Best-effort local log (may fail if permissions are wrong).
    $bootstrapLogPath = __DIR__ . '/../storage/logs/bootstrap.log';
    @file_put_contents(
        $bootstrapLogPath,
        '[' . date('Y-m-d H:i:s') . "] " . $fullMessage . "\n\n",
        FILE_APPEND
    );

    echo 'Error 500: fallo al iniciar la aplicación. Código: ' . $errorId;
        echo  'fullMessage'.$fullMessage; 

}
