<?php

/**
 * Main entry point for the Birthday Reminder PWA
 * Handles routing and request dispatching
 */

// Start session with secure settings
require_once __DIR__ . '/../config/config.php';

// Start session with secure settings
ini_set('session.cookie_httponly', 1);
ini_set('session.use_only_cookies', 1);
ini_set('session.cookie_samesite', 'Strict');
ini_set('session.gc_maxlifetime', SESSION_LIFETIME);
ini_set('session.cookie_lifetime', SESSION_LIFETIME);
session_name(SESSION_NAME);
session_start();


require_once __DIR__ . '/../config/autoload.php';

// Register error handler
ErrorHandler::register();

// Set security headers
SecurityMiddleware::setSecurityHeaders();

// Get the request URI and method
$requestUri = $_SERVER['REQUEST_URI'];
$requestMethod = $_SERVER['REQUEST_METHOD'];

// Remove query string and base path
$uri = parse_url($requestUri, PHP_URL_PATH);
// Remove URL_PATH (configured in config.php) and /public from path
if (URL_PATH !== '') {
    $uri = str_replace(URL_PATH, '', $uri);
}
$uri = str_replace('/public', '', $uri);
$uri = trim($uri, '/');

// Simple routing logic
try {
    // Skip routing for uploads - serve files directly
    if (strpos($uri, 'uploads/') === 0) {
        // This should be handled by .htaccess, but as a fallback:
        $filePath = BASE_PATH . '/' . $uri;
        if (file_exists($filePath)) {
            $mimeType = mime_content_type($filePath);
            header('Content-Type: ' . $mimeType);
            readfile($filePath);
            exit;
        } else {
            http_response_code(404);
            echo "File not found";
            exit;
        }
    }

    // Default route - Open PWA home
    if (empty($uri) || $uri === 'index.php') {
        // Redirect to PWA home (works for both authenticated and non-authenticated users)
        redirect(BASE_URL . '/home');
        exit;
    }

    // Parse route
    $parts = explode('/', $uri);

    // Admin routes
    if ($parts[0] === 'admin') {
        // Special handling for auth routes
        if (isset($parts[1]) && ($parts[1] === 'login' || $parts[1] === 'logout')) {
            $controller = 'AuthController';
            $action = $parts[1];
        } else {
            // Map routes to controllers
            $routeMap = [
                'dashboard' => 'DashboardController',
                'users' => 'UserController',
                'templates' => 'TemplateController',
                'contacts' => 'ContactController',
                'notes' => 'NoteController',
                'excel' => 'ExcelController',
                'ajax' => 'AjaxController'
            ];

            $route = $parts[1] ?? 'dashboard';
            $controller = $routeMap[$route] ?? ucfirst($route) . 'Controller';
            $action = isset($parts[2]) ? $parts[2] : 'index';

            // Convert hyphenated action names to camelCase
            // e.g., process-import -> processImport
            if (strpos($action, '-') !== false) {
                $action = lcfirst(str_replace('-', '', ucwords($action, '-')));
            }
        }

        $params = array_slice($parts, ($parts[1] === 'login' || $parts[1] === 'logout') ? 2 : 3);

        // Check if controller exists
        if (class_exists($controller)) {
            $controllerInstance = new $controller();

            // Check if action exists
            if (method_exists($controllerInstance, $action)) {
                call_user_func_array([$controllerInstance, $action], $params);
            } else {
                throw new Exception("Action not found: $action");
            }
        } else {
            throw new Exception("Controller not found: $controller");
        }
    }
    // API routes
    elseif ($parts[0] === 'api') {
        header('Content-Type: application/json');

        // Parse API route: /api/resource/action or /api/resource/id
        $resource = isset($parts[1]) ? $parts[1] : '';
        $action = isset($parts[2]) ? $parts[2] : '';
        $id = isset($parts[3]) ? $parts[3] : null;

        // Route to API controller
        $apiController = new ApiController();

        // Handle notification routes
        if ($resource === 'notifications') {
            if ($action === 'subscribe' && $requestMethod === 'POST') {
                $apiController->subscribeNotifications();
            } elseif ($action === 'unsubscribe' && $requestMethod === 'POST') {
                $apiController->unsubscribeNotifications();
            } elseif ($action === 'status' && $requestMethod === 'GET') {
                $apiController->notificationStatus();
            } else {
                jsonError('Invalid API endpoint', 'NOT_FOUND', 404);
            }
        } elseif ($resource === 'search' && $requestMethod === 'GET') {
            $apiController->search();
        } elseif ($resource === 'export-contacts' && $requestMethod === 'GET') {
            $apiController->exportContacts();
        } else {
            jsonError('API resource not found', 'NOT_FOUND', 404);
        }
    }
    // PWA routes (direct routes without /pwa prefix)
    elseif (in_array($parts[0], ['login', 'logout', 'home', 'add-contact', 'templates', 'search', 'add-note', 'notes'])) {
        $route = $parts[0];

        // Map routes to controller actions
        $pwaRoutes = [
            'login' => ['controller' => 'AuthController', 'action' => 'pwaLogin'],
            'logout' => ['controller' => 'AuthController', 'action' => 'pwaLogout'],
            'home' => ['controller' => 'HomeController', 'action' => 'index'],
            'add-contact' => ['controller' => 'PwaContactController', 'action' => 'create'],
            'templates' => ['controller' => 'PwaTemplateController', 'action' => 'index'],
            'search' => ['controller' => 'PwaContactController', 'action' => 'search'],
            'add-note' => ['controller' => 'PwaNoteController', 'action' => 'create'],
            'notes' => ['controller' => 'PwaNoteController', 'action' => 'index']
        ];

        if (isset($pwaRoutes[$route])) {
            $controller = $pwaRoutes[$route]['controller'];
            $action = $pwaRoutes[$route]['action'];
            $params = array_slice($parts, 1);

            // Check if controller exists
            if (class_exists($controller)) {
                $controllerInstance = new $controller();

                // Check if action exists
                if (method_exists($controllerInstance, $action)) {
                    call_user_func_array([$controllerInstance, $action], $params);
                } else {
                    throw new Exception("Action not found: $action");
                }
            } else {
                throw new Exception("Controller not found: $controller");
            }
        } else {
            throw new Exception("PWA route not found: $route");
        }
    } else {
        throw new Exception("Route not found: $uri");
    }
} catch (Exception $e) {
    // Error handling
    http_response_code(404);
    echo "<h1>Error</h1>";
    echo "<p>" . htmlspecialchars($e->getMessage()) . "</p>";

    // Log error
    error_log("Routing error: " . $e->getMessage());
}
