<?php
/**
 * FreeCMS — Forum Platform
 *
 * @author    MAKATANGA
 * @license   MIT
 */

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

use App\Core\Dotenv;
use App\Core\Request;
use App\Core\Session;

// Redirect to installer if not installed
if (!file_exists(__DIR__ . '/../install.lock') && !file_exists(__DIR__ . '/../.env')) {
    header('Location: /install.php');
    exit;
}

// Load Environment Variables
Dotenv::load(__DIR__ . '/../.env');

// Start Session
Session::start();
\App\Helpers\Lang::load();

// Handle Request
$request = new Request();
$router = require_once __DIR__ . '/../config/routes.php';

try {
    $response = $router->handle($request);
    $response->send();
} catch (\Exception $e) {
    error_log($e->getMessage() . ' ' . $e->getTraceAsString());
    if (($_ENV['APP_ENV'] ?? 'production') === 'development') {
        echo "<h1>Error</h1><p>{$e->getMessage()}</p><pre>{$e->getTraceAsString()}</pre>";
    } else {
        http_response_code(500);
        echo "Internal Server Error";
    }
}
