<?php
date_default_timezone_set('Asia/Colombo');

session_start();

// Basic autoloader for the 'App' namespace pointing to 'src/' directory
spl_autoload_register(function ($class) {
    $prefix = 'App\\';
    $base_dir = __DIR__ . '/../';
    
    // Check if the class uses the App namespace
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        return;
    }
    
    // Get the relative class name
    $relative_class = substr($class, $len);
    
    // Replace the namespace prefix with the base directory, replace namespace
    // separators with directory separators in the relative class name, append
    // with .php
    // Example: App\Controllers\HomeController -> src/Controllers/HomeController.php
    $file = $base_dir . 'src/' . str_replace('\\', '/', $relative_class) . '.php';
    
    // If the file exists, require it
    if (file_exists($file)) {
        require $file;
    } else {
        // Fallback for Config folder: App\Config\Database -> config/database.php or config/Database.php
        $parts = explode('\\', $relative_class);
        if ($parts[0] === 'Config' && isset($parts[1])) {
            $config_file_camel = $base_dir . 'config/' . $parts[1] . '.php';
            $config_file_lower = $base_dir . 'config/' . strtolower($parts[1]) . '.php';
            
            if (file_exists($config_file_camel)) {
                require $config_file_camel;
            } elseif (file_exists($config_file_lower)) {
                require $config_file_lower;
            }
        }
    }
});

// Simple Router (Works with both Apache .htaccess and PHP built-in server)
$requestUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$requestUri = trim($requestUri, '/');

// If empty, default to login
$url = $requestUri ?: 'login';
$url = filter_var($url, FILTER_SANITIZE_URL);
$urlParts = explode('/', $url);

$controllerName = ucfirst($urlParts[0] ?? 'Login') . 'Controller';
$methodName = $urlParts[1] ?? 'index';

// Handle plural to singular mapping for controllers
$routeMap = [
    'BranchesController' => 'BranchController',
    'UsersController' => 'UserController',
    'MedicinesController' => 'MedicineController',
    'SalesController' => 'SaleController',
    'InventoryController' => 'InventoryController'
];

if (isset($routeMap[$controllerName])) {
    $controllerName = $routeMap[$controllerName];
}

$controllerClass = "App\\Controllers\\{$controllerName}";

if (class_exists($controllerClass)) {
    $controller = new $controllerClass();
    if (method_exists($controller, $methodName)) {
        // Call the method, passing any remaining URL parts as arguments
        $params = array_slice($urlParts, 2);
        call_user_func_array([$controller, $methodName], $params);
    } else {
        http_response_code(404);
        echo "404 - Method not found";
    }
} else {
    http_response_code(404);
    echo "404 - Page not found";
}

// Background "lazy" monitoring: Check daemon heartbeat after request completes
register_shutdown_function(['App\Utils\DaemonMonitor', 'checkAndAlert']);

