<?php

/**
 * Front Controller — Gmind Institute
 *
 * This is the main entry point for the application.
 * All requests are routed through this file via Apache/LiteSpeed mod_rewrite
 * or FallbackResource directive.
 * Deployed at: https://advaysingh.co.in/gmind
 *
 * For shared hosting, the public directory contents are placed at the root
 * level, with app/, config/, vendor/ etc. in the same directory.
 */

// ─── Error Display (Early — before config loads) ────────────────────────────
error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');

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

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

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

require __DIR__ . '/config/database.php';
require __DIR__ . '/config/app.php';
require __DIR__ . '/config/auth.php';

// ─── 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);

session_name(SESSION_NAME);
session_start();

// ─── Error Reporting ─────────────────────────────────────────────────────────

if (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');
}

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

$router = require __DIR__ . '/routes/web.php';

// Get the URI — supports both FallbackResource (REQUEST_URI) and RewriteRule ($_GET['route'])
if (isset($_GET['route']) && $_GET['route'] !== '') {
    // Method 1: RewriteRule set ?route= in query string
    $uri = $_GET['route'];
} else {
    // Method 2: FallbackResource — parse from REQUEST_URI
    $uri = $_SERVER['REQUEST_URI'] ?? '/';
}

// Parse only the path portion (remove query string)
$uri = parse_url($uri, PHP_URL_PATH) ?? '/';

// Strip the base path from the URI if present (for subdirectory installs)
$basePath = rtrim(BASE_PATH, '/');
if ($basePath !== '' && str_starts_with($uri, $basePath)) {
    $uri = substr($uri, strlen($basePath));
    if ($uri === false || $uri === '') {
        $uri = '/';
    }
}

// Remove trailing slash (except for root '/')
if ($uri !== '/') {
    $uri = rtrim($uri, '/');
}

// Ensure URI starts with /
if (!str_starts_with($uri, '/')) {
    $uri = '/' . $uri;
}

// Set proper HTTP status code (FallbackResource sends 404 by default)
if (http_response_code() === 404) {
    http_response_code(200);
}

$method = $_SERVER['REQUEST_METHOD'];

$router->dispatch($uri, $method);
