<?php
/**
 * ===========================================
 * FLOWBOT DCI - MAIN ENTRY POINT
 * ===========================================
 * All requests go through this file
 */

declare(strict_types=1);

// Error handling - controlled by config (SEC-005: don't expose in production)
ini_set('log_errors', '1');

// No time limit
set_time_limit(0);

// Define base paths
define('BASE_PATH', dirname(__DIR__));
define('PUBLIC_PATH', __DIR__);

// ===========================================
// STEP 1: Check required PHP extensions
// ===========================================
$requiredExtensions = ['curl', 'pdo', 'pdo_mysql', 'dom', 'json', 'mbstring'];
$missingExtensions = [];

foreach ($requiredExtensions as $ext) {
    if (!extension_loaded($ext)) {
        $missingExtensions[] = $ext;
    }
}

if (!empty($missingExtensions)) {
    http_response_code(500);
    echo "<h1>Missing PHP Extensions</h1>";
    echo "<p>The following required extensions are not installed:</p>";
    echo "<ul>";
    foreach ($missingExtensions as $ext) {
        echo "<li><strong>{$ext}</strong></li>";
    }
    echo "</ul>";
    echo "<p>Please install these extensions and restart your web server.</p>";
    exit(1);
}

// ===========================================
// STEP 2: Check required files exist
// ===========================================
$requiredFiles = [
    'autoload' => BASE_PATH . '/src/autoload.php',
    'config' => BASE_PATH . '/config/config.php',
];

foreach ($requiredFiles as $name => $path) {
    if (!file_exists($path)) {
        http_response_code(500);
        echo "<h1>Missing Required File</h1>";
        echo "<p>Cannot find: <code>{$path}</code></p>";
        echo "<p>Current BASE_PATH: <code>" . BASE_PATH . "</code></p>";
        echo "<p>File exists check: " . (file_exists($path) ? 'YES' : 'NO') . "</p>";
        exit(1);
    }
}

// ===========================================
// STEP 3: Load autoloader
// ===========================================
try {
    require BASE_PATH . '/src/autoload.php';
} catch (\Throwable $e) {
    http_response_code(500);
    echo "<h1>Autoloader Error</h1>";
    echo "<p><strong>Error:</strong> " . htmlspecialchars($e->getMessage()) . "</p>";
    echo "<p><strong>File:</strong> " . htmlspecialchars($e->getFile()) . ":" . $e->getLine() . "</p>";
    exit(1);
}

// ===========================================
// STEP 4: Load configuration
// ===========================================
try {
    $config = require BASE_PATH . '/config/config.php';

    if (!is_array($config)) {
        throw new \Exception("Configuration must return an array");
    }
} catch (\Throwable $e) {
    http_response_code(500);
    echo "<h1>Configuration Error</h1>";
    echo "<p><strong>Error:</strong> " . htmlspecialchars($e->getMessage()) . "</p>";
    echo "<p><strong>File:</strong> " . htmlspecialchars($e->getFile()) . ":" . $e->getLine() . "</p>";
    exit(1);
}

// ===========================================
// STEP 5: Check temp directory
// ===========================================
$tempDir = BASE_PATH . '/temp';
if (!is_dir($tempDir)) {
    if (!@mkdir($tempDir, 0755, true)) {
        http_response_code(500);
        echo "<h1>Cannot Create Temp Directory</h1>";
        echo "<p>Failed to create: <code>{$tempDir}</code></p>";
        echo "<p>Please create this directory manually with write permissions.</p>";
        exit(1);
    }
}

if (!is_writable($tempDir)) {
    http_response_code(500);
    echo "<h1>Temp Directory Not Writable</h1>";
    echo "<p>Directory <code>{$tempDir}</code> is not writable.</p>";
    echo "<p>Please set permissions: <code>chmod 755 {$tempDir}</code></p>";
    exit(1);
}

// ===========================================
// STEP 6: Initialize and run application
// ===========================================
try {
    // Check if Application class exists
    if (!class_exists('\\FlowbotDCI\\Core\\Application')) {
        throw new \Exception("Application class not found. Check autoloader and namespace.");
    }

    $app = new \FlowbotDCI\Core\Application($config);
    $app->initialize();
    $app->handleRequest();

} catch (\Throwable $e) {
    // Handle ALL errors (Exception and Error)
    http_response_code(500);

    // SEC-005: Only show detailed errors in debug mode
    // Check config, env variable, or explicit debug flag
    $isDebug = ($config['app']['debug'] ?? false) ||
               (isset($_ENV['APP_DEBUG']) && $_ENV['APP_DEBUG'] === 'true') ||
               (getenv('APP_DEBUG') === 'true');

    // Always log the full error server-side
    error_log("FlowbotDCI Error: " . $e->getMessage() . " in " . $e->getFile() . ":" . $e->getLine());
    error_log("Stack trace: " . $e->getTraceAsString());

    // Generate unique error ID for support reference
    $errorId = substr(md5($e->getMessage() . $e->getFile() . time()), 0, 8);

    if ($isDebug) {
        // Development mode: show full details
        echo "<!DOCTYPE html><html><head><title>Error</title>";
        echo "<style>body{font-family:sans-serif;padding:20px;background:#1a1a2e;color:#eee;}";
        echo "h1{color:#ff6b6b;}pre{background:#16213e;padding:15px;overflow:auto;border-radius:5px;}";
        echo "code{background:#16213e;padding:2px 6px;border-radius:3px;}</style></head><body>";
        echo "<h1>Application Error</h1>";
        echo "<p><strong>Error ID:</strong> <code>{$errorId}</code></p>";
        echo "<p><strong>Message:</strong> " . htmlspecialchars($e->getMessage()) . "</p>";
        echo "<p><strong>File:</strong> <code>" . htmlspecialchars($e->getFile()) . "</code> Line: <code>" . $e->getLine() . "</code></p>";
        echo "<h3>Stack Trace:</h3>";
        echo "<pre>" . htmlspecialchars($e->getTraceAsString()) . "</pre>";
        echo "<h3>Debug Info:</h3>";
        echo "<pre>";
        echo "PHP Version: " . PHP_VERSION . "\n";
        echo "BASE_PATH: " . BASE_PATH . "\n";
        echo "PUBLIC_PATH: " . PUBLIC_PATH . "\n";
        echo "Current Dir: " . __DIR__ . "\n";
        echo "Document Root: " . ($_SERVER['DOCUMENT_ROOT'] ?? 'N/A') . "\n";
        echo "Script Name: " . ($_SERVER['SCRIPT_NAME'] ?? 'N/A') . "\n";
        echo "</pre>";
        echo "</body></html>";
    } else {
        // SEC-005: Production mode - generic error message, no sensitive info
        echo "<!DOCTYPE html><html><head><title>Error</title>";
        echo "<style>body{font-family:sans-serif;padding:40px;background:#1a1a2e;color:#eee;text-align:center;}";
        echo "h1{color:#ff6b6b;}.box{background:#16213e;padding:30px;border-radius:10px;max-width:500px;margin:0 auto;}";
        echo ".error-id{background:#0f0f23;padding:8px 16px;border-radius:5px;font-family:monospace;}</style></head><body>";
        echo "<div class='box'>";
        echo "<h1>Something went wrong</h1>";
        echo "<p>An unexpected error occurred. Please try again later.</p>";
        echo "<p>If the problem persists, contact support with this reference:</p>";
        echo "<p class='error-id'>Error ID: {$errorId}</p>";
        echo "<p><a href='/' style='color:#3498db;'>Return to Home</a></p>";
        echo "</div>";
        echo "</body></html>";
    }
}
