<?php
// Load environment variables from .env file
require_once('../config/bootstrap.php');

require_once('../config/environments.php');
require_once('../config/api_keys.php');

// Initialize Sentry if DSN is configured
Sentry_Config::init();

// Change working directory to project root so relative PATH constants work correctly
chdir(__DIR__ . '/..');

require_once(PATH_TO_CONFIG_DIR . 'database.php');
require_once(PATH_TO_LIB_DIR . 'AppLib.php');
require_once(PATH_TO_LIB_DIR . 'RollingCurlX.php');

require_once(PATH_TO_CLASSES_DIR . 'LCHF.php');

global $route;
global $params;
global $data;

AppLib::log_to_db(['http_request', $_SERVER]);

// Check if this is a path-based request (Symfony routes) vs legacy ?c=&a= routes
$query_string = $_SERVER['QUERY_STRING'] ?? '';
$path_info = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$is_legacy_route = strpos($query_string, 'c=') !== false;

// Try Symfony routing for path-based requests (e.g., /api/users, /test/auth)
// See classes/Symfony/Bootstrap.php for documentation on how this works
if (!$is_legacy_route && $path_info !== '/' && $path_info !== '/index.php') {
    require_once(PATH_TO_CONFIG_DIR . 'init.php');
    if (MEMCACHE) {
        require_once(PATH_TO_CONFIG_DIR . 'memcached.php');
    }

    // Kernel.php contains a function (not a class), so must be explicitly loaded
    require_once(PATH_TO_CLASSES_DIR . 'Symfony/Kernel.php');

    // Try Symfony routing - returns null if no route matched
    $response = Symfony_Bootstrap::handle_request();
    if ($response !== null) {
        exit;
    }
    // No route matched, fall through to legacy routing below
}

// Legacy ?c=&a= routing
$request_str = $_SERVER['REQUEST_URI'];
$query = explode('&', $query_string);

$action = '';
$controller = '';
$params = [];

foreach ($query as $query_str) {
    $str_arr = explode('=', $query_str);
    $prev_str = '';

    if (sizeof($str_arr) == 2) {
        if ($str_arr[0] === 'a' && $action === '') {
            $action = ($str_arr[1] !== '') ? $str_arr[1] : 'index';
        }
        elseif ($str_arr[0] === 'c' && $controller === '') {
            $controller = ($str_arr[1] !== '') ? $str_arr[1] : 'default';
        }
        elseif ($str_arr[0] === 'x' && $controller === '') {
            if ($str_arr[1] == 'excel_report') {
                require_once(PATH_TO_CONTROLLERS_DIR . 'Excel_Report_Controller.php');
            }
        }
        elseif ($str_arr[1] !== '') {
            $params[$str_arr[0]] = $str_arr[1];
        }
    }
}

$controller = ($controller === '') ? 'default' : $controller;
$action = ($action === '') ? 'index' : $action;

$route = [
    'controller' => strtolower($controller),
    'action' => strtolower($action)
];

require_once('router.php');
