<?php
declare(strict_types=1);

define('LK_DB_HOST', 'localhost');
define('LK_DB_NAME', 'gamingserver_server');
define('LK_DB_USER', 'gamingserver_user');
define('LK_DB_PASS', 'serveruserpassword');
define('LK_DB_CHARSET', 'utf8mb4');

define('LK_SITE_URL',    'https://ludoking.gamingserver.win');
define('LK_SITE_NAME',   'LudoKing Bot Panel');
define('LK_SCREENSHOTS', __DIR__ . '/screenshots/');

function lk_pdo(): PDO {
    static $pdo = null;
    if ($pdo !== null) return $pdo;
    $dsn = 'mysql:host=' . LK_DB_HOST . ';dbname=' . LK_DB_NAME . ';charset=' . LK_DB_CHARSET;
    $pdo = new PDO($dsn, LK_DB_USER, LK_DB_PASS, [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
        PDO::ATTR_PERSISTENT         => false,
    ]);
    $pdo->exec("SET time_zone='+06:00'");
    return $pdo;
}

function lk_setting(string $key, string $default = ''): string {
    static $cache = [];
    if (isset($cache[$key])) return $cache[$key];
    try {
        $st = lk_pdo()->prepare("SELECT value FROM settings WHERE `key`=? LIMIT 1");
        $st->execute([$key]);
        $row = $st->fetch(PDO::FETCH_ASSOC);
        $cache[$key] = $row ? (string)$row['value'] : $default;
    } catch (Throwable $e) {
        $cache[$key] = $default;
    }
    return $cache[$key];
}

function lk_setting_set(string $key, string $value): void {
    lk_pdo()->prepare(
        "INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=VALUES(`value`)"
    )->execute([$key, $value]);
}

function lk_e(string $s): string {
    return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
