<?php
// ============================================================
//  config.php  —  Pre-configured for menu.latartekw.com
//
//  Before the site will work, you MUST set DB_PASS below.
// ============================================================

define('DB_HOST', 'localhost');
define('DB_NAME', 'latartekw_qrmenu');
define('DB_USER', 'latartekw_qrmenu');
define('DB_PASS', 'System99$');   // ← edit this one line
define('DB_CHARSET', 'utf8mb4');

define('SITE_URL', 'https://latartekw.com/order');

define('UPLOAD_DIR', __DIR__ . '/uploads/');
define('UPLOAD_URL', SITE_URL . '/uploads/');
define('MAX_UPLOAD_MB', 5);
define('SESSION_NAME', 'grove_admin');

// ── DB connection (singleton) ────────────────────────────────
// Note: we explicitly issue `SET NAMES utf8mb4` immediately after
// connecting, in addition to the `charset=utf8mb4` in the DSN.
// Some MySQL configurations ignore the DSN charset and fall back
// to latin1 for the connection, which makes UTF-8 text (accented
// characters, Arabic, emoji) render as mojibake — e.g. "Tropézienne"
// becoming "TropÃ©zienne". The SET NAMES statement is the reliable
// way to force the connection into UTF-8 mode regardless of server
// default character set.
function db(): PDO {
    static $pdo = null;
    if ($pdo) return $pdo;
    $dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET;
    $pdo = new PDO($dsn, DB_USER, DB_PASS, [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci',
    ]);
    // Belt-and-suspenders: if the INIT_COMMAND attribute is ignored
    // by the driver (rare, but happens), this ensures the connection
    // is UTF-8 before any real query runs.
    $pdo->exec("SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci");
    return $pdo;
}

// ── Helpers ──────────────────────────────────────────────────
function setting(string $key, string $fallback = ''): string {
    static $cache = null;
    if ($cache === null) {
        $rows = db()->query('SELECT key_name, value FROM settings')->fetchAll();
        $cache = array_column($rows, 'value', 'key_name');
    }
    return $cache[$key] ?? $fallback;
}

function json_out(mixed $data, int $code = 200): never {
    http_response_code($code);
    // Explicitly advertise UTF-8 so browsers render special chars correctly
    // even if the webserver's default charset is something else.
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

function sanitize(string $str): string {
    return htmlspecialchars(trim($str), ENT_QUOTES, 'UTF-8');
}
