<?php
declare(strict_types=1);

/**
 * Mystic Art Tattoo — front controller.
 * All HTTP requests route through this single entry point.
 */

define('MAT_ROOT', dirname(__DIR__));
define('MAT_PUBLIC', __DIR__);

$config = require MAT_ROOT . '/config.php';
$GLOBALS['mat_config'] = $config;

date_default_timezone_set($config['app']['timezone']);
if (function_exists('mb_internal_encoding')) { mb_internal_encoding('UTF-8'); }

ini_set('display_errors', $config['app']['debug'] ? '1' : '0');
ini_set('log_errors', '1');
ini_set('error_log', $config['data_path'] . '/logs/error.log');
error_reporting(E_ALL);

// Allow large uploads (videos)
@ini_set('upload_max_filesize', '100M');
@ini_set('post_max_size', '105M');
@ini_set('max_execution_time', '300');
@ini_set('max_input_time', '300');

// Ensure data + upload directories exist on first run
foreach (['', '/logs'] as $sub) {
    $path = $config['data_path'] . $sub;
    if (!is_dir($path)) @mkdir($path, 0755, true);
}
foreach (['', '/signatures', '/references', '/gallery', '/avatars'] as $sub) {
    $path = $config['upload_path'] . $sub;
    if (!is_dir($path)) @mkdir($path, 0755, true);
}

// Autoload (Composer if available, otherwise minimal PSR-4)
if (file_exists(MAT_ROOT . '/vendor/autoload.php')) {
    require MAT_ROOT . '/vendor/autoload.php';
} else {
    require MAT_ROOT . '/src/autoload.php';
}

require MAT_ROOT . '/src/helpers.php';

use App\Session;
use App\I18n;
use App\Router;
use App\Routes;

Session::start($config['session']);
I18n::boot();

$router = new Router();
Routes::register($router);

try {
    $router->dispatch();
} catch (\Throwable $e) {
    error_log('[FATAL] ' . $e->getMessage() . ' @ ' . $e->getFile() . ':' . $e->getLine());

    // For POST requests that crash, redirect back with a flash error so the user
    // doesn't get stuck on a 500 page with a dead CSRF token
    if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
        $_SESSION['_flash']['error'] = $config['app']['debug']
            ? $e->getMessage()
            : t('error.500.flash');
        $back = $_SERVER['HTTP_REFERER'] ?? '/';
        if (str_contains($back, $_SERVER['HTTP_HOST'] ?? 'localhost')) {
            header('Location: ' . parse_url($back, PHP_URL_PATH), true, 302);
        } else {
            header('Location: /', true, 302);
        }
        exit;
    }

    http_response_code(500);
    if ($config['app']['debug']) {
        echo '<pre>' . htmlspecialchars($e->getMessage() . "\n" . $e->getTraceAsString()) . '</pre>';
    } else {
        require MAT_ROOT . '/src/Views/errors/500.php';
    }
}
