<?php
declare(strict_types=1);

/**
 * El Captain ERP — Front Controller
 * All requests route through here.
 */

// ── Show ALL errors during startup (before ExceptionHandler takes over) ──
error_reporting(E_ALL);
ini_set('display_errors', '1');

// ── Base path resolution ──
define('BASE_PATH', dirname(__DIR__));

// ── Load .env FIRST (before anything else) ──
$envFile = BASE_PATH . '/.env';
if (file_exists($envFile)) {
    $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '' || str_starts_with($line, '#')) {
            continue;
        }
        if (str_contains($line, '=')) {
            [$key, $value] = explode('=', $line, 2);
            $key = trim($key);
            $value = trim($value);
            // Remove surrounding quotes
            if ((str_starts_with($value, '"') && str_ends_with($value, '"')) ||
                (str_starts_with($value, "'") && str_ends_with($value, "'"))) {
                $value = substr($value, 1, -1);
            }
            $_ENV[$key] = $value;
            $_SERVER[$key] = $value;
            putenv("{$key}={$value}");
        }
    }
}

// ── Autoloader (Composer) ──
require_once BASE_PATH . '/vendor/autoload.php';

// ── Security headers ──
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: strict-origin-when-cross-origin');

// ── Exception handler ──
$exHandler = new App\Core\ExceptionHandler();
$exHandler->register();

// ── Boot application ──
try {
    App\Core\DebugBar::init();
    $app = App\Core\App::getInstance();
    $app->boot();

    // ── Dispatch request ──
    $request = App\Core\Request::capture();
    $response = $app->router()->dispatch($request);
    $response->send();

} catch (\Throwable $e) {
    // If we get here during boot, show the REAL error
    $debug = ($_ENV['APP_DEBUG'] ?? 'false') === 'true'
          || (getenv('APP_DEBUG') ?: 'false') === 'true';

    if ($debug) {
        http_response_code(500);
        header('Content-Type: text/html; charset=utf-8');
        echo '<html dir="rtl"><head><meta charset="utf-8"><title>Boot Error</title>';
        echo '<style>body{font-family:monospace;background:#1a1a2e;color:#e0e0e0;padding:40px;direction:ltr;text-align:left;}';
        echo 'h1{color:#ff6b6b;}pre{background:#16213e;padding:20px;border-radius:8px;overflow-x:auto;white-space:pre-wrap;word-wrap:break-word;}';
        echo '.info{color:#4ecdc4;margin:10px 0;}</style></head><body>';
        echo '<h1>💀 BOOT FAILURE</h1>';
        echo '<p class="info">Exception: <strong>' . htmlspecialchars(get_class($e)) . '</strong></p>';
        echo '<p class="info">Message: <strong>' . htmlspecialchars($e->getMessage()) . '</strong></p>';
        echo '<p class="info">File: ' . htmlspecialchars($e->getFile()) . ':' . $e->getLine() . '</p>';
        echo '<h3>Stack Trace:</h3>';
        echo '<pre>' . htmlspecialchars($e->getTraceAsString()) . '</pre>';
        echo '<h3>Environment Check:</h3>';
        echo '<pre>';
        echo "DB_HOST: " . (getenv('DB_HOST') ?: ($_ENV['DB_HOST'] ?? 'NOT SET')) . "\n";
        echo "DB_PORT: " . (getenv('DB_PORT') ?: ($_ENV['DB_PORT'] ?? 'NOT SET')) . "\n";
        echo "DB_NAME: " . (getenv('DB_NAME') ?: ($_ENV['DB_NAME'] ?? 'NOT SET')) . "\n";
        echo "DB_USER: " . (getenv('DB_USER') ?: ($_ENV['DB_USER'] ?? 'NOT SET')) . "\n";
        echo "DB_PASS: " . (getenv('DB_PASS') ? '***SET***' : 'NOT SET') . "\n";
        echo "APP_DEBUG: " . (getenv('APP_DEBUG') ?: ($_ENV['APP_DEBUG'] ?? 'NOT SET')) . "\n";
        echo ".env exists: " . (file_exists(BASE_PATH . '/.env') ? 'YES' : 'NO') . "\n";
        echo "PHP version: " . PHP_VERSION . "\n";
        echo "Extensions: " . implode(', ', get_loaded_extensions()) . "\n";
        echo '</pre>';
        echo '</body></html>';
    } else {
        http_response_code(500);
        header('Content-Type: text/html; charset=utf-8');
        echo '<html dir="rtl"><body style="font-family:Cairo,sans-serif;text-align:center;padding:100px;background:#f9fafb;">';
        echo '<h1 style="color:#dc2626;">حدث خطأ في النظام</h1>';
        echo '<p style="color:#6b7280;">يرجى التواصل مع مسئول النظام</p>';
        echo '</body></html>';
    }
    exit(1);
}