<?php
declare(strict_types=1);


spl_autoload_register(function (string $class): void {
    $baseDir = dirname(__DIR__) . '/';
    $paths = [
        'Controllers\\' => 'controllers/',
        'Services\\' => 'services/',
        'Repositories\\' => 'repositories/',
        'Middleware\\' => 'middleware/',
        'Validators\\' => 'validators/',
        'Models\\' => 'models/',
        'Helpers\\' => 'helpers/',
        'Config\\' => 'config/',
    ];
    foreach ($paths as $prefix => $dir) {
        if (str_starts_with($class, $prefix)) {
            $relative = substr($class, strlen($prefix));
            $file = $baseDir . $dir . str_replace('\\', '/', $relative) . '.php';
            if (is_file($file)) require_once $file;
        }
    }
});

use Helpers\Response;
use Config\Env;

Env::load(dirname(__DIR__) . '/.env');

ini_set('display_errors', Env::get('APP_DEBUG', 'false') === 'true' ? '1' : '0');
error_reporting(E_ALL);

set_exception_handler(function (Throwable $e): void {
    error_log($e->getMessage() . PHP_EOL . $e->getTraceAsString());
    Response::error('Internal server error', 500, Env::get('APP_DEBUG', 'false') === 'true' ? ['detail' => $e->getMessage()] : []);
});

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