<?php
//
// It all starts here..
//
use app\app;
use app\controllers\account;
use app\controllers\address;
use app\controllers\admin;
use app\controllers\cart;
use app\controllers\category;
use app\controllers\checkout;
use app\controllers\home;
use app\controllers\lnurlp;
use app\controllers\lost;
use app\controllers\magic_link;
use app\controllers\support;
use app\controllers\transaction;
use app\models\user_settings;

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

// Load environment variables from the .env file at project root
Dotenv\Dotenv::createImmutable(__DIR__ . '/../')->load();

// Start the session
app::init_db();
session_start();
session_regenerate_id(true); // prevent session fixation attacks

// prevent session hijack
if (! isset($_SESSION['fingerprint'])) {
    $_SESSION['fingerprint'] = hash('sha256', $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']);
} else {
    if ($_SESSION['fingerprint'] !== hash('sha256', $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'])) {
        session_unset();
        session_destroy();
    }
}

// these will be available to use in all twig templates
$user_settings = isset($_SESSION['user_id']) ? user_settings::getByUserId($_SESSION['user_id']) : null;
$theme         = 'light';
if (isset($_SESSION['user_id']) && $user_settings !== null && isset($user_settings['dark_theme'])) {
    $theme = $user_settings['dark_theme'] ? 'dark' : 'light';
} elseif (isset($_COOKIE["theme"])) {
    $theme = $_COOKIE["theme"];
}
$defaults = [
    'copyright_year' => date('Y'),
    'session'        => $_SESSION,
    'http_host'      => $_SERVER['HTTP_HOST'],
    'env'            => $_ENV,
    'is_user'        => isset($_SESSION['user_id']),
    'user_settings'  => $user_settings,
    'is_admin'       => isset($_SESSION['user_id']) && $_SESSION['user_id'] == 1,
    // uses cookie-js to get the client's preferred theme
    // used to conditionally deliver image assets
    // or styles based on theme
    'theme'          => $theme,
    // set your tailwind colors here for app themeing
    // the idea is to avoid using colors in your templates
    'colors'         => require dirname(__DIR__) . '/src/colors.php',
];

// Setup a twig
$loader          = new \Twig\Loader\FilesystemLoader(paths: dirname(__DIR__) . '/src/views');
$GLOBALS['twig'] = new \Twig\Environment($loader, [
    //'cache' => dirname(__DIR__) . '/cache',
    'cache' => false,
]);

$route = explode(separator: '?', string: $_SERVER['REQUEST_URI'])[0];
if (str_starts_with(haystack: $route, needle: '/.well-known/lnurlp/')) {
    $route = '/lnurlp';
}

// Use this controller for routes that include a model ID
if (preg_match('/^\/(address(?:\/edit|\/delete)?|transaction|user|order|quote|product|subscription|cart|admin\/categories\/edit|admin\/products\/edit)\/([\w-]+)$/', $route, $matches)) {
    [$full, $type, $id] = $matches;
    $controller         = [
        'address/edit'          => fn($id)          => address::edit($defaults, $id),
        'address/delete'        => fn($id)        => address::delete($defaults, $id),
        'transaction'           => fn($id)           => transaction::view($defaults, $id),
        'user'                  => fn($id)                  => users::view($id),
        'order'                 => fn($id)                 => orders::view($id),
        'quote'                 => fn($id)                 => quotes::view($id),
        'product'               => fn($id)               => products::view($id),
        'subscription'          => fn($id)          => subscriptions::view($id),
        'cart'                  => fn($id)                  => cart::index($id),
        'admin/categories/edit' => fn($id) => $defaults['is_admin'] ? admin::categories_edit($defaults, $id) : lost::index($defaults),
        'admin/products/edit'   => fn($id)   => $defaults['is_admin'] ? admin::products_edit($defaults, $id) : lost::index($defaults),
    ];

    if (isset($controller[$type])) {
        $controller = $controller[$type]($id);
    }
} else { // Use this controller for static routes
    $controller = match ($route) {
        '/' => home::index($defaults),
        '/account/login' => account::login($defaults),
        '/account/signup' => account::signup($defaults),
        '/account/verify' => account::verify($defaults),
        '/account' => $defaults['is_user'] ? account::index($defaults) : header('Location: /account/login'),
        '/account/profile' => $defaults['is_user'] ? account::profile() : header('Location: /account/login'),
        '/account/email' => $defaults['is_user'] ? account::email() : header('Location: /account/login'),
        '/account/logout' => $defaults['is_user'] ? account::logout() : header('Location: /account/login'),
        '/account/returns' => $defaults['is_user'] ? account::returns($defaults) : header('Location: /account/login'),
        '/account/billing' => $defaults['is_user'] ? account::billing($defaults) : header('Location: /account/login'),
        '/account/orders' => $defaults['is_user'] ? account::orders($defaults) : header('Location: /account/login'),
        '/account/shipping' => $defaults['is_user'] ? account::shipping($defaults) : header('Location: /account/login'),
        '/account/notifications' => $defaults['is_user'] ? account::notifications($defaults) : header('Location: /account/login'),
        '/account/address/edit' => $defaults['is_user'] ? account::address_edit($defaults) : header('Location: /account/login'),
        '/account/address/set-default-shipping' => $defaults['is_user'] ? account::set_default_shipping($defaults) : header('Location: /account/login'),
        '/account/address/set-default-billing' => $defaults['is_user'] ? account::set_default_billing($defaults) : header('Location: /account/login'),
        '/admin' => $defaults['is_admin'] ? admin::index($defaults) : lost::index($defaults),
        '/admin/users' => $defaults['is_admin'] ? admin::users($defaults) : lost::index($defaults),
        '/admin/products' => $defaults['is_admin'] ? admin::products($defaults) : lost::index($defaults),
        '/admin/products/add' => $defaults['is_admin'] ? admin::products_add($defaults) : lost::index($defaults),
        '/admin/orders' => $defaults['is_admin'] ? admin::orders($defaults) : lost::index($defaults),
        '/admin/emails' => $defaults['is_admin'] ? admin::emails($defaults) : lost::index($defaults),
        '/admin/categories' => $defaults['is_admin'] ? admin::categories($defaults) : lost::index($defaults),
        '/admin/categories/add' => $defaults['is_admin'] ? admin::categories_add($defaults) : lost::index($defaults),
        '/admin/transactions' => $defaults['is_admin'] ? admin::transactions($defaults) : lost::index($defaults),
        '/admin/transactions/add' => $defaults['is_admin'] ? admin::transactions_add($defaults) : lost::index($defaults),
        '/admin/transactions/reset' => $defaults['is_admin'] ? admin::transactions_reset($defaults) : lost::index($defaults),
        '/admin/returns' => $defaults['is_admin'] ? admin::returns($defaults) : lost::index($defaults),
        '/admin/subscriptions' => $defaults['is_admin'] ? admin::subscriptions($defaults) : lost::index($defaults),
        '/admin/subscriptions/add' => $defaults['is_admin'] ? admin::subscriptions_add($defaults) : lost::index($defaults),
        '/magic-link' => magic_link::index(),
        '/checkout/confirmed' => checkout::confirmed($defaults),
        '/checkout/review-pay' => checkout::review_pay($defaults),
        '/checkout/shipping-billing' => checkout::shipping_billing($defaults),
        '/support/ask' => support::index($defaults),
        '/support/bitcoin' => support::bitcoin($defaults),
        '/cart' => cart::index($defaults),
        '/lnurlp' => lnurlp::index(),
        // product categories
        '/power-meters' => category::power_meters($defaults),
        default => lost::index($defaults)
    };
}
;

// Clear alerts after rendering
foreach (['error', 'warning', 'info', 'success'] as $alert) {
    unset($_SESSION[$alert]);
}
