<?php

declare(strict_types=1);

require_once __DIR__ . '/../vendor/autoload.php';

use Dotenv\Dotenv;

$dotenv = Dotenv::createImmutable(dirname(__DIR__));
$dotenv->safeLoad();

define('BASE_PATH', dirname(__DIR__));
define('STORAGE_PATH', BASE_PATH . '/storage');
define('APP_ENV', $_ENV['APP_ENV'] ?? 'development');
define('APP_DEBUG', filter_var($_ENV['APP_DEBUG'] ?? true, FILTER_VALIDATE_BOOLEAN));

date_default_timezone_set('America/Lima');

$allowedOrigins = [
    $_ENV['APP_URL'] ?? 'http://localhost:8000',
    'http://localhost:5173',
    'http://localhost:5174',
    'http://localhost:4173',
    'https://italvettools.com',
    'https://app.italvettools.com',
    'https://www.italvettools.com',
];

$origin = $_SERVER['HTTP_ORIGIN'] ?? '';

if (in_array($origin, $allowedOrigins)) {
    header('Access-Control-Allow-Origin: ' . $origin);
    header('Access-Control-Allow-Credentials: true');
} else {
    header('Access-Control-Allow-Origin: ' . $allowedOrigins[0]);
}

header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('Referrer-Policy: strict-origin-when-cross-origin');
header('X-Robots-Tag: noindex, nofollow');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

if (APP_DEBUG) {
    error_reporting(E_ALL);
    ini_set('display_errors', '1');
} else {
    error_reporting(0);
    ini_set('display_errors', '0');
}

set_exception_handler(function (Throwable $e) {
    $status = $e->getCode() ?: 500;
    if ($status < 100 || $status > 599) {
        $status = 500;
    }

    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');

    $body = [
        'success' => false,
        'message' => APP_DEBUG ? $e->getMessage() : 'Error interno del servidor',
    ];

    if (APP_DEBUG) {
        $body['file'] = $e->getFile();
        $body['line'] = $e->getLine();
        $body['trace'] = explode("\n", $e->getTraceAsString());
    }

    echo json_encode($body, JSON_UNESCAPED_UNICODE);
});

require_once __DIR__ . '/../routes/api.php';
