<?php
// Available routes with their file paths
$routes = [
    '/'                 => 'views/events.php',
    '/events'           => 'views/events.php',
    '/create-events'    => 'views/create-events.php',
    '/request'          => 'views/request.php',
    '/create-request'   => 'views/create-request.php',
    '/member-request'   => 'views/create-request-member.php',
    '/request-approval' => 'views/request-approval.php',
    '/items'            => 'views/items.php',
    '/create-items'     => 'views/create-items.php',
    '/about'            => 'views/about.php',
    '/404'              => 'views/404.php',
    '/ctrl-global'      => 'controller/ctrl-global.php',
    '/ctrl-events'      => 'controller/ctrl-events.php',
    '/ctrl-request'     => 'controller/ctrl-request.php',
    '/ctrl-items'       => 'controller/ctrl-items.php',
    '/add-user'         => 'add-user.php',
];

// Routing function
function handleRequest($uri) {
    global $routes;

    $baseFolder = '/senior'; // Base folder for your application

    // Remove base folder and query string from URI
    $uri = str_replace($baseFolder, '', parse_url($uri, PHP_URL_PATH));

    // Loop through each route and check for a match
    foreach ($routes as $route => $template) {
        // Convert dynamic segments in route (e.g., {id}) to a regular expression
        $pattern = preg_replace('#\{([a-zA-Z0-9_]+)\}#', '([a-zA-Z0-9_]+)', $route);
        $pattern = "#^$pattern$#";

        // Match the route against the URI
        if (preg_match($pattern, $uri, $matches)) {
            // Extract parameter names from the route definition
            preg_match_all('#\{([a-zA-Z0-9_]+)\}#', $route, $paramNames);

            // Remove the full match, leave only parameters
            array_shift($matches);

            // Combine parameter names with values
            $params = [];
            foreach ($paramNames[1] as $index => $name) {
                $params[$name] = $matches[$index] ?? null;
            }

            // Include the corresponding template file
            if (file_exists($template)) {
                include $template;
                return;
            } else {
                // Handle file not found
                include 'views/404.php';
                return;
            }
        }
    }

    // No match found, handle 404
    include 'views/404.php';
}

// Call the routing function with the current URI
handleRequest($_SERVER['REQUEST_URI']);
?>
