<?php

/**
 * Front Controller — Gmind Institute
 *
 * This is the entry point for the application.
 * All requests are routed through this file via Apache/LiteSpeed mod_rewrite.
 * Deployed at: https://advaysingh.co.in/gmind/
 *
 * IMPORTANT: This file MUST be at the project root (gmind/), NOT inside a public/ subdirectory.
 */

// ─── Early Error Display (before any other code) ─────────────────────────────
// Use a conservative default; APP_DEBUG will override this after config loads.
// We log everything to error_log so we can diagnose issues even with display off.
error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('display_startup_errors', '0');
ini_set('log_errors', '1');

// ─── Define Project Root ─────────────────────────────────────────────────────
// __DIR__ resolves to the directory containing this index.php file.
// Whether deployed at /gmind/ or /gmind/public/, this ensures correct paths.
$projectRoot = __DIR__;

// If this file is inside a public/ subdirectory, go one level up
if (basename(__DIR__) === 'public') {
    $projectRoot = dirname(__DIR__);
}

// ─── Autoloader ──────────────────────────────────────────────────────────────

$autoloader = $projectRoot . '/vendor/autoload.php';
if (!file_exists($autoloader)) {
    http_response_code(500);
    echo '<h1>Setup Error</h1><p>Autoloader not found at: ' . htmlspecialchars($autoloader) . '</p>';
    echo '<p>Project root detected as: ' . htmlspecialchars($projectRoot) . '</p>';
    echo '<p>__DIR__ = ' . htmlspecialchars(__DIR__) . '</p>';
    exit;
}
require $autoloader;

// ─── Configuration ───────────────────────────────────────────────────────────

$configFiles = [
    $projectRoot . '/config/database.php',
    $projectRoot . '/config/app.php',
    $projectRoot . '/config/auth.php',
];

foreach ($configFiles as $configFile) {
    if (!file_exists($configFile)) {
        http_response_code(500);
        echo '<h1>Setup Error</h1><p>Config file not found: ' . htmlspecialchars($configFile) . '</p>';
        echo '<p>Project root: ' . htmlspecialchars($projectRoot) . '</p>';
        exit;
    }
    require $configFile;
}

// ─── Route Debug Mode ────────────────────────────────────────────────────────

if (defined('ROUTE_DEBUG') && ROUTE_DEBUG) {
    header('Content-Type: text/plain; charset=utf-8');
    echo "=== ROUTE DEBUG ===\n";
    echo '$_GET[\'route\'] = ' . var_export($_GET['route'] ?? '(not set)', true) . "\n";
    echo '$_SERVER[\'REQUEST_URI\'] = ' . var_export($_SERVER['REQUEST_URI'] ?? '(not set)', true) . "\n";
    echo '$_SERVER[\'SCRIPT_NAME\'] = ' . var_export($_SERVER['SCRIPT_NAME'] ?? '(not set)', true) . "\n";
    echo 'Project Root = ' . var_export($projectRoot, true) . "\n";
    echo "==================\n";
}

// ─── Session Configuration ───────────────────────────────────────────────────

ini_set('session.cookie_httponly', '1');
ini_set('session.use_strict_mode', '1');
ini_set('session.cookie_samesite', 'Lax');
ini_set('session.gc_maxlifetime', (string) SESSION_LIFETIME);

// Set session cookie path to the base path so it works in subdirectory
$cookiePath = defined('BASE_PATH') ? BASE_PATH : '/';
ini_set('session.cookie_path', $cookiePath);

session_name(SESSION_NAME);
session_start();

// ─── Initialize Locale (BEFORE any output) ──────────────────────────────────
// This ensures the language cookie is set before headers are sent.
// Must be called after session_start() and after config/app.php is loaded.
if (function_exists('getCurrentLocale')) {
    getCurrentLocale();
}

// ─── Error Reporting (controlled after config loads) ─────────────────────────

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

// ─── Reset HTTP Status (LiteSpeed may send 404 before our router) ────────────

if (http_response_code() === 404) {
    http_response_code(200);
}

// ─── Dispatch Request ────────────────────────────────────────────────────────

try {
    $routeFile = $projectRoot . '/routes/web.php';
    if (!file_exists($routeFile)) {
        throw new RuntimeException('Routes file not found: ' . $routeFile);
    }

    $router = require $routeFile;

    // Get the URI from the query string parameter set by .htaccess
    $uri = $_GET['route'] ?? '/';
    $method = $_SERVER['REQUEST_METHOD'];

    $router->dispatch($uri, $method);
} catch (\Throwable $e) {
    error_log('Fatal error: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
    http_response_code(500);
    if (defined('APP_DEBUG') && APP_DEBUG) {
        echo '<h1>Application Error</h1>';
        echo '<p><strong>' . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8') . '</strong></p>';
        echo '<p>File: ' . htmlspecialchars($e->getFile() . ':' . $e->getLine(), ENT_QUOTES, 'UTF-8') . '</p>';
        echo '<pre>' . htmlspecialchars($e->getTraceAsString(), ENT_QUOTES, 'UTF-8') . '</pre>';
    } else {
        echo '<h1>Something went wrong</h1><p>Please try again later.</p>';
    }
}
