<?php
error_reporting(E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED);
ini_set("display_errors", "1");
ini_set("display_startup_errors", "1");

// Capturar errores fatales
register_shutdown_function(function () {
    $err = error_get_last();
    if ($err && in_array($err["type"], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
        if (!headers_sent()) { http_response_code(200); }
        $msg = "FATAL: " . $err["message"] . " in " . $err["file"] . ":" . $err["line"];
        error_log($msg);
        include __DIR__ . "/_error.php";
    }
});

if (PHP_VERSION_ID < 70400) {
    http_response_code(200);
    die("PHP 7.4+ requerido. Version actual: " . PHP_VERSION);
}

define("START_TIME", microtime(true));
define("PUBLIC_PATH", __DIR__);

// Ruta al directorio privado (descomentar y editar si es necesario)
// define("PRIVATE_PATH", "/home/tu_usuario/private");

if (defined("PRIVATE_PATH")) {
    $privatePath = PRIVATE_PATH;
} else {
    $parentDir = dirname(__DIR__);
    $privatePaths = array(
        $parentDir . "/private",
        $parentDir . "/ganadera_private",
        dirname($parentDir) . "/private",
        dirname($parentDir) . "/ganadera_private",
        __DIR__ . "/../private",
        __DIR__ . "/private",
    );
    $privatePath = null;
    foreach ($privatePaths as $path) {
        if (is_dir($path) && file_exists($path . "/app/Core/Application.php")) {
            $privatePath = realpath($path);
            break;
        }
    }
}

if (!$privatePath || !is_dir($privatePath)) {
    http_response_code(200);
    include __DIR__ . "/_error.php";
    exit;
}

define("BASE_PATH", $privatePath);

$scriptDir = str_replace("\\", "/", dirname($_SERVER["SCRIPT_NAME"]));
$baseUrl = ($scriptDir !== "/" && $scriptDir !== "\\") ? rtrim($scriptDir, "/") : "";
define("BASE_URL", $baseUrl);

$rawUri = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
if (preg_match("#/install(\.php)?$#", $rawUri) && file_exists(__DIR__ . "/install.php")) {
    if (substr($rawUri, -4) !== ".php") {
        header("Location: " . $baseUrl . "/install.php");
        exit;
    }
}

$requestUri = $rawUri;
if (BASE_URL !== "" && strpos($requestUri, BASE_URL) === 0) {
    $requestUri = substr($requestUri, strlen(BASE_URL));
    if (!$requestUri) { $requestUri = "/"; }
    $_SERVER["REQUEST_URI"] = $requestUri;
}

if (!file_exists(BASE_PATH . "/config/installed.php")) {
    if (file_exists(__DIR__ . "/install.php")) {
        header("Location: " . BASE_URL . "/install.php");
        exit;
    }
    die("Sistema no instalado.");
}

require_once BASE_PATH . "/app/Core/Autoloader.php";
\App\Core\Autoloader::register();

$config = require BASE_PATH . "/config/app.php";
$config["app"]["base_url"] = BASE_URL;
$config["app"]["public_path"] = PUBLIC_PATH;

date_default_timezone_set($config["app"]["timezone"]);

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");

if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
    http_response_code(204);
    exit;
}

session_name($config["session"]["name"]);
session_set_cookie_params(array(
    "lifetime" => $config["session"]["lifetime"],
    "path"     => BASE_URL ? BASE_URL : "/",
    "secure"   => $config["session"]["secure"],
    "httponly"  => $config["session"]["httponly"],
    "samesite"  => $config["session"]["samesite"],
));
session_start();

try {
    $app = new \App\Core\Application($config);
    $app->run();
} catch (\Throwable $e) {
    $logMsg = "[" . date("Y-m-d H:i:s") . "] " . $e->getMessage()
        . " in " . $e->getFile() . ":" . $e->getLine() . "\n"
        . $e->getTraceAsString() . "\n";
    $logDir = BASE_PATH . "/storage/logs";
    if (!is_dir($logDir)) { @mkdir($logDir, 0775, true); }
    @file_put_contents($logDir . "/php_errors.log", $logMsg, FILE_APPEND);
    error_log($logMsg);
    if (!headers_sent()) { http_response_code(200); }
    include __DIR__ . "/_error.php";
}
