<?php
/**
 * MediFlash SOS+ Entry Point
 * Main application bootstrap file
 */

// Load environment variables if they exist
if (file_exists(__DIR__ . '/../config/env.php')) {
    require_once __DIR__ . '/../config/env.php';
}

// Load configuration
require_once __DIR__ . '/../config/config.php';

// Start session
session_start();

// Set CORS headers for API requests
header('Access-Control-Allow-Origin: ' . CORS_ALLOWED_ORIGINS);
header('Access-Control-Allow-Methods: ' . CORS_ALLOWED_METHODS);
header('Access-Control-Allow-Headers: ' . CORS_ALLOWED_HEADERS);
header('Access-Control-Allow-Credentials: true');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit();
}

// Set JSON response header for API requests
if (strpos($_SERVER['REQUEST_URI'], '/api/') !== false) {
    header('Content-Type: application/json');
}

try {
    // Initialize router
    require_once __DIR__ . '/../app/Core/Router.php';
    $router = new Router();
    
    // Load all routes
    require_once __DIR__ . '/../app/routes.php';
    
    // Handle the request
    $router->handleRequest();
    
} catch (Exception $e) {
    // Log error
    error_log("Application Error: " . $e->getMessage());
    
    // Check if it's an API request
    if (strpos($_SERVER['REQUEST_URI'], '/api/') !== false) {
        http_response_code(500);
        echo json_encode([
            'error' => 'Internal Server Error',
            'message' => APP_DEBUG ? $e->getMessage() : 'Une erreur est survenue'
        ]);
    } else {
        // Show error page for web requests
        http_response_code(500);
        echo "<!DOCTYPE html>
        <html>
        <head>
            <title>Erreur - " . APP_NAME . "</title>
            <meta charset='utf-8'>
            <meta name='viewport' content='width=device-width, initial-scale=1'>
            <style>
                body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }
                .error { color: #dc2626; margin: 20px 0; }
                .back-link { color: #0066CC; text-decoration: none; }
            </style>
        </head>
        <body>
            <h1>Une erreur est survenue</h1>
            <div class='error'>" . (APP_DEBUG ? $e->getMessage() : 'Service temporairement indisponible') . "</div>
            <a href='/' class='back-link'>← Retour à l'accueil</a>
        </body>
        </html>";
    }
}
?>
