<?php
declare(strict_types=1);

// -------- Helpers (escape + cache-busting assets) --------
function h($s): string {
    return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function asset(string $path): string {
    $path = ltrim($path, '/');
    $full = __DIR__ . '/' . $path;
    $v = is_file($full) ? (string)filemtime($full) : (string)time();
    return $path . '?v=' . $v;
}

function tg_user_url(string $username): string {
    $u = ltrim(trim($username), '@');
    return 'https://t.me/' . rawurlencode($u);
}

// Basic hardening headers (safe defaults)
if (!headers_sent()) {
    header('X-Content-Type-Options: nosniff');
    header('Referrer-Policy: strict-origin-when-cross-origin');
}
// -------- Charger .env (simple parser) --------
function env_file_get($file) {
    $out = [];
    if (!is_file($file)) return $out;
    foreach (file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
        if ($line === '' || str_starts_with(trim($line), '#')) continue;
        [$k, $v] = array_pad(explode('=', $line, 2), 2, '');
        $k = trim($k); $v = trim($v);
        $v = preg_replace('/^["\']|["\']$/', '', $v);
        if ($k !== '') $out[$k] = $v;
    }
    return $out;
}
function cfg($key, $default = '') {
    static $env = null;
    if ($env === null) $env = env_file_get(__DIR__.'/.env');
    return $env[$key] ?? getenv($key) ?? $default;
}

// -------- Variables globales --------
$APP_NAME = cfg('APP_NAME', 'FrenchCo App');
$INSTAGRAM_URL = cfg('INSTAGRAM_URL', 'https://instagram.com/youraccount');
$CHANNEL_URL = cfg('CHANNEL_URL', 'https://t.me/YourChannel');

$CONTACT_BOT_USERNAME = ltrim(cfg('CONTACT_BOT_USERNAME', 'YourContactBot'), '@');
$ORDER_BOT_USERNAME   = ltrim(cfg('ORDER_BOT_USERNAME',   'YourOrderBot'),   '@');

$ADMIN_SECRET = cfg('ADMIN_SECRET', 'change-me');

$DB_HOST = cfg('DB_HOST', '127.0.0.1');
$DB_USER = cfg('DB_USER', 'root');
$DB_PASS = cfg('DB_PASS', '');
$DB_NAME = cfg('DB_NAME', 'frenchco');

// -------- Connexion DB --------
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if ($mysqli->connect_errno) {
    http_response_code(500);
    die("DB connect error: ".$mysqli->connect_error);
}
$mysqli->set_charset('utf8mb4');
