<?php
declare(strict_types=1);

ob_start();

if (session_status() === PHP_SESSION_NONE) {
    session_set_cookie_params(['lifetime' => 86400, 'secure' => true, 'httponly' => true, 'samesite' => 'Strict']);
    session_start();
}

if (empty($_SESSION['csrf_token'])) {
    try {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    } catch (Throwable $e) {
        $_SESSION['csrf_token'] = sha1(uniqid((string)mt_rand(), true));
    }
}

$skip_auth_check = true; 

require_once __DIR__ . '/../db/db_connection.php';
require_once __DIR__ . '/security.php';

$brandingFile = __DIR__ . '/../brand/branding.php';
if (file_exists($brandingFile)) {
    require_once $brandingFile;
}

require_once __DIR__ . '/business-information.php';
require_once __DIR__ . '/timezone.php';
require_once __DIR__ . '/formatters.php';

$public_lang_code = 'en';

if (isset($pdo) && $pdo instanceof PDO) {
    $stmtLang = $pdo->prepare("SELECT public_language FROM business_info LIMIT 1");
    $stmtLang->execute();
    $row = $stmtLang->fetch(PDO::FETCH_ASSOC);
    if ($row && !empty($row['public_language'])) {
        $public_lang_code = $row['public_language'];
    }
}

$base_lang_dir = __DIR__ . '/lang/main/';       
$public_lang_dir = __DIR__ . "/lang/{$public_lang_code}/"; 

$TRANSLATIONS = [];

if (is_dir($base_lang_dir)) {
    $files = glob($base_lang_dir . '*.php');
    if ($files) {
        foreach ($files as $file) {
            $filename = basename($file);
            $base_trans = require $file;
            if (!is_array($base_trans)) continue;

            $public_file = $public_lang_dir . $filename;
            if (file_exists($public_file)) {
                $public_trans = require $public_file;
                if (is_array($public_trans)) {
                    $base_trans = array_merge($base_trans, $public_trans);
                }
            }
            $TRANSLATIONS = array_merge($TRANSLATIONS, $base_trans);
        }
    }
}

if (!function_exists('__')) {
    function __($key) {
        global $TRANSLATIONS;
        return $TRANSLATIONS[$key] ?? $key;
    }
}

if (!function_exists('__status')) {
    function __status($prefix, $db_value) {
        $normalized = strtolower(str_replace(' ', '_', trim((string)$db_value)));
        return __($prefix . '_' . $normalized);
    }
}
?>