<?php

declare(strict_types=1);

// ============================================================
// KHỞI ĐỘNG SESSION
// ============================================================

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
// ============================================================
// CSRF TOKEN
// ============================================================

if (empty($_SESSION['csrf_token'])) {

    $_SESSION['csrf_token'] =
        bin2hex(random_bytes(32));
}
// ============================================================
// LOAD CONFIG
// ============================================================

$config = require __DIR__ . '/../config/app.php';

// Cho phép sử dụng config ở toàn bộ project
$GLOBALS['config'] = $config;

// ============================================================
// CONSTANTS
// ============================================================

define('BASE_PATH', dirname(__DIR__));

define(
    'BASE_URL',
    rtrim($config['base_url'] ?? '', '/')
);

define(
    'APP_NAME',
    $config['app_name'] ?? 'PET SHOP'
);

// ============================================================
// TIMEZONE
// ============================================================

date_default_timezone_set(
    $config['timezone'] ?? 'Asia/Ho_Chi_Minh'
);

// ============================================================
// DEBUG
// ============================================================

if (($config['debug'] ?? false) === true) {

    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');

    error_reporting(E_ALL);

} else {

    ini_set('display_errors', '0');
}

// ============================================================
// DATABASE
// ============================================================

require_once BASE_PATH . '/config/database.php';
require_once BASE_PATH . '/app/models/RememberToken.php';
require_once BASE_PATH . '/app/helpers/SessionAuth.php';

if (empty($_SESSION['user'])) {
    try {
        $rememberedUser = (new RememberToken())->restoreFromCookie();
        if ($rememberedUser) {
            sign_in_user($rememberedUser);
        }
    } catch (Throwable) {
        // A missing optional table must not make the public site unavailable.
    }
}
// ============================================================
// GLOBAL SHOP INFORMATION
// ============================================================

require_once BASE_PATH
    . '/app/models/SystemSetting.php';

require_once BASE_PATH
    . '/app/models/ShopSetting.php';

require_once BASE_PATH
    . '/app/models/SocialLink.php';


try {

    $systemSettingModel =
        new SystemSetting();

    $GLOBALS['system_settings'] =
        $systemSettingModel->getAll();

    $requestedRoute =
        trim(
            $_GET['url']
            ?? '',
            '/'
        );

    $isBackofficeRoute =
        str_starts_with(
            $requestedRoute,
            'admin'
        )
        || str_starts_with(
            $requestedRoute,
            'owner'
        );

    $isAuthenticationRoute =
        in_array(
            $requestedRoute,
            [
                'login',
                'login/submit',
                'logout'
            ],
            true
        );

    if (
        $systemSettingModel->getBoolean(
            'maintenance_mode',
            false
        )
        && !$isBackofficeRoute
        && !$isAuthenticationRoute
    ) {
        http_response_code(503);

        require BASE_PATH
            . '/app/views/errors/maintenance.php';

        exit;
    }

    $shopSettingModel =
        new ShopSetting();


    $socialLinkModel =
        new SocialLink();


    $GLOBALS['shop_settings'] =
        $shopSettingModel->get();


    $GLOBALS['social_links'] =
        $socialLinkModel
            ->getActive();


} catch (Throwable $e) {

    // Website vẫn hoạt động nếu phần settings có lỗi

    $GLOBALS['shop_settings'] = [
        'shop_name' => APP_NAME,
        'logo' => null,
        'phone' => null,
        'email' => null,
        'address' => null,
        'description' => null,
        'map_embed_url' => null,
        'shipping_fee' => 0,
        'free_shipping_from' => null
    ];


    $GLOBALS['social_links'] = [];

    $GLOBALS['system_settings'] = [];
}

// Enforce configurable Customer/Owner permissions before controllers run.
// Controllers still enforce the role itself; this layer also protects direct URLs.
require_once BASE_PATH . '/app/helpers/Authorization.php';
Authorization::enforceRoute(trim($_GET['url'] ?? '', '/'));
// ============================================================
// ROUTER
// ============================================================

require_once BASE_PATH . '/routes/web.php';
