<?php
/**
 * STH NRMS — Settings Helper
 * File: include/settings_helper.php
 *
 * Lightweight key/value settings reader, backed by the `settings` table.
 * Caches all rows in a static array per-request so repeated calls don't
 * hit the DB more than once.
 *
 * USAGE:
 *   require_once '../include/settings_helper.php';
 *   $pass_mark = getSetting('pass_mark_percentage', 50, $conn);   // falls back to 50 if missing
 *   setSetting('hospital_name', 'New Name', $conn, $user_id);
 *
 * PHP 7 COMPATIBLE.
 */

function getAllSettings(mysqli $conn): array
{
    static $cache = null;
    if ($cache !== null) return $cache;

    $cache = [];
    $r = $conn->query("SELECT setting_key, value, data_type FROM settings");
    if ($r) {
        while ($row = $r->fetch_assoc()) {
            $cache[$row['setting_key']] = castSettingValue($row['value'], $row['data_type']);
        }
    }
    return $cache;
}

function castSettingValue($value, string $type)
{
    if ($type === 'integer') return (int)$value;
    if ($type === 'boolean') return ((string)$value === '1' || strtolower((string)$value) === 'true');
    if ($type === 'json')    return json_decode((string)$value, true);
    return $value; // string
}

/**
 * Get a single setting by key. $conn is required so the cache can be
 * populated on first call. Falls back to $default if the key doesn't
 * exist (e.g. the settings table hasn't been migrated yet, or this is
 * a brand new setting not yet seeded).
 */
function getSetting(string $key, $default, mysqli $conn)
{
    $all = getAllSettings($conn);
    return array_key_exists($key, $all) ? $all[$key] : $default;
}

function setSetting(string $key, $value, mysqli $conn, int $updated_by = 0): bool
{
    $stmt = $conn->prepare("UPDATE settings SET value = ?, updated_by = ?, updated_at = NOW() WHERE setting_key = ?");
    $val_str = is_bool($value) ? ($value ? '1' : '0') : (string)$value;
    $stmt->bind_param('sis', $val_str, $updated_by, $key);
    $ok = $stmt->execute();
    $stmt->close();
    return $ok;
}

function settingsTableExists(mysqli $conn): bool
{
    $r = $conn->query("SHOW TABLES LIKE 'settings'");
    return $r && $r->num_rows > 0;
}