<?php
require_once __DIR__.'/db.php';

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

function money($v): string {
    $value = (float)$v;
    // Sentiasa format kepada 2 titik perpuluhan
    return 'RM'.number_format($value, 2);
}

function setting(string $k, $def='') {
    $st = db()->prepare("SELECT value FROM settings WHERE key=?");
    $st->execute([$k]);
    $r = $st->fetch();
    return $r ? $r['value'] : $def;
}

/**
 * KEMAS KINI FUNGSI set_setting()
 * Versi baru ini lebih serasi dengan pelbagai versi SQLite.
 * Ia akan periksa dahulu jika tetapan wujud, kemudian UPDATE atau INSERT.
 */
function set_setting(string $k, string $v) {
    // Periksa jika kunci (key) sudah wujud
    $check = db()->prepare("SELECT COUNT(*) as c FROM settings WHERE key = ?");
    $check->execute([$k]);
    $exists = (int)$check->fetch()['c'] > 0;

    if ($exists) {
        // Jika wujud, KEMAS KINI (UPDATE)
        $st = db()->prepare("UPDATE settings SET value = ? WHERE key = ?");
        $st->execute([$v, $k]);
    } else {
        // Jika tidak wujud, MASUKKAN BARU (INSERT)
        $st = db()->prepare("INSERT INTO settings (key, value) VALUES (?, ?)");
        $st->execute([$k, $v]);
    }
}

function rate_limit(string $key, int $sec=5): bool {
    $now = time();
    if (!isset($_SESSION['rate'][$key])) {
        $_SESSION['rate'][$key] = $now;
        return true;
    }
    if ($now - $_SESSION['rate'][$key] >= $sec) {
        $_SESSION['rate'][$key] = $now;
        return true;
    }
    return false;
}

function random_doa(): string {
    $r = db()->query("SELECT text FROM doa WHERE active=1 ORDER BY RANDOM() LIMIT 1")->fetch();
    return $r ? $r['text'] : 'Ya Allah, berkati rezeki kami.';
}

function client_ip(): string {
    return $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
}