<?php global /** @var response $response */
$DEBUG, $CONFIG_DB, $ENCRYPTION_KEY, $CORS, $WD, $db, $response, $request, $router, $redis;
ini_set('output_buffering', 'off');
ini_set('zlib.output_compression', false);

/**
 * This is the main entry point to the Truck Wash API.
 */
const WD = __DIR__;
require_once 'config.php';
/** Debug */
if ($DEBUG) {
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
}

/** CORS */
header("Access-Control-Allow-Origin: $CORS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");

/** Autoload */
require_once 'vendor/autoload.php';
/** Load all Interfaces */
foreach ( glob(WD . '/interfaces/*.php') as $interface ) {
    require_once $interface;
}
/** Load all Traits */
foreach ( glob(WD . '/traits/*.php') as $trait ) {
    require_once $trait;
}

/**
 * Load all statistics
 */
foreach ( glob(WD . '/statistics/*.php') as $statistic ) {
    require_once $statistic;
}

/** Load all Classes */
require_once 'classes/encrypt.php';
require_once 'classes/authentication.php';
require_once 'classes/permission_node.php';
require_once 'classes/object_property.php';
require_once 'classes/router.php';
require_once 'classes/db.php';
require_once 'classes/response.php';
require_once 'classes/request.php';
require_once 'classes/ratelimit.php';
require_once 'classes/wash_certificate_store.php';
require_once 'classes/invoice_store.php';
require_once 'classes/pdf_store.php';
require_once 'classes/redis.php';
require_once 'classes/slack.php';
require_once 'classes/wordpress_bookings_remote.php';
require_once 'classes/language_packs.php';
require_once 'classes/economic.php';
require_once 'classes/statistics.php';
require_once 'classes/recaptcha.php';
require_once 'classes/email.php';
require_once 'classes/backup_store.php';
require_once 'classes/motorapi.php';
require_once 'classes/stripe.php';
require_once 'classes/form.php';
require_once 'classes/pdf_generator.php';
require_once 'classes/fxratesapi.php';
require_once 'classes/gatewayapi.php';
require_once 'classes/xlvask.php';
require_once 'classes/entra.php';
require_once 'classes/limble.php';
require_once 'classes/ocr_space.php';
require_once 'classes/openai.php';
require_once 'classes/licenseplaterecognizer.php';
require_once 'classes/image_processor.php';
require_once 'classes/upload_store.php';
require_once 'classes/attachments.php';
require_once 'classes/attachment_store.php';
require_once 'classes/virkdata.php';
require_once 'classes/shelly.php';
require_once 'classes/selfserve.php';

/**
 * Modules
 * Load all the modules
 */
require_once 'modules/economic/economic_m.php';
require_once 'modules/economic/customers/economicCustomers.php';
require_once 'modules/economic/customers/economic_customer_mo.php';
require_once 'modules/economic/invoices/draft/economicInvoicesDrafts.php';
require_once 'modules/economic/invoices/draft/economic_invoice_draft_mo.php';

// Goals module
foreach (glob(WD . '/modules/goals/interfaces/*.php') as $interface) {
    require_once $interface;
}
foreach (glob(WD . '/modules/goals/traits/*.php') as $trait) {
    require_once $trait;
}
require_once 'modules/goals/helpers/goals_criteria_type.php';
require_once 'modules/goals/helpers/goals_criteria_progress_alert_frequency.php';
require_once 'modules/goals/helpers/goals_criteria_progress_alert_destination.php';
require_once 'modules/goals/helpers/goals_criteria_progress_alert_progress_type.php';
require_once 'modules/goals/helpers/goals_criteria_progress_alert_style.php';
require_once 'modules/goals/helpers/goals_criteria_progress_alert_weekday.php';
require_once 'modules/goals/formats/email_progress_alert_format.php';
require_once 'modules/goals/formats/slack_progress_alert_format.php';
require_once 'modules/goals/formats/sms_progress_alert_format.php';
require_once 'modules/goals/services/goals_progress_alert_renderer.php';
require_once 'modules/goals/classes/goals_criteria_users.php';
require_once 'modules/goals/classes/goals_criteria_departments.php';
require_once 'modules/goals/classes/goals_criteria_products.php';
require_once 'modules/goals/classes/goals_criteria.php';
require_once 'modules/goals/classes/goals.php';

// Subusers module
// Load interfaces, traits, classes, helpers and permissions to ensure autoloading for route usage
foreach (glob(WD . '/modules/subusers/interfaces/*.php') as $interface) {
    require_once $interface;
}
foreach (glob(WD . '/modules/subusers/traits/*.php') as $trait) {
    require_once $trait;
}
foreach (glob(WD . '/modules/subusers/classes/*.php') as $classFile) {
    require_once $classFile;
}
foreach (glob(WD . '/modules/subusers/helpers/*.php') as $helper) {
    require_once $helper;
}
foreach (glob(WD . '/modules/subusers/permissions/*.php') as $permissionFile) {
    require_once $permissionFile;
}

// Dynamic Images module
foreach (glob(WD . '/modules/dynamicimages/interfaces/*.php') as $interface) {
    require_once $interface;
}
foreach (glob(WD . '/modules/dynamicimages/traits/*.php') as $trait) {
    require_once $trait;
}
foreach (glob(WD . '/modules/dynamicimages/classes/*.php') as $classFile) {
    require_once $classFile;
}
foreach (glob(WD . '/modules/dynamicimages/helpers/*.php') as $helper) {
    require_once $helper;
}
foreach (glob(WD . '/modules/dynamicimages/config/*.php') as $configFile) {
    require_once $configFile;
}
// Load image definitions (e.g., dynamicimages\images\machine_1)
foreach (glob(WD . '/modules/dynamicimages/images/*.php') as $imageClass) {
    require_once $imageClass;
}

use classes\db;
use classes\redis;
use classes\request;
use classes\response;
use classes\router;

// Start the session
$router = new router();
$response = new response();
$request = new request();
$db = new db($CONFIG_DB);
try {
    define("redis", (new redis())->connect());
} catch (Exception $e) {
    $response->error($e->getMessage(), 500);
}

// Connect to the database, and ensure the connection is successful
try {
    $db->connect();
} catch (Exception $e) {
    $response->error($e->getMessage(), 500);
}
// Load all the traits
foreach ( glob(WD . '/traits/*.php') as $trait ) {
    require_once $trait;
}

// Load all the routes
foreach ( glob(WD . '/routes/*.php') as $route ) {
    require_once $route;
}

/** Load all Objects */
foreach ( glob(WD . '/objects/*.php') as $object ) {
    try {
        require_once $object;
    } catch (Exception $e) {
        $response->error($e->getMessage(), 500);
    }
}

// If the program was called from the command line, run the cli script
if (php_sapi_name() === 'cli' || isset($_GET['internalCronCall'])) {
    require_once 'cli.php';
    exit;
}

// If the route ends with .php, then require the file_server.php
if (str_contains($_SERVER['REQUEST_URI'], '.pdf')) {
    require_once 'file_server.php';
    exit;
}
// If the route ends with a MIME type, then require the file_server.php
if ((preg_match('/\.(jpg|jpeg|png)$/', $_SERVER['REQUEST_URI']) || str_contains($_SERVER['REQUEST_URI'], '/files/'))) {
    require_once 'file_server.php';
    exit;
}

// Autoload all the routes
$router->auto_load_routes(WD . '/routes');

/** If no matching route is found, return a 404 */
if (!$response->is_matching_route_found()) {
    // Debug
    $response->add_debug(['message' => 'No matching route found']);
    $response->not_found();
}