<?php
/**
 * SSBS-ISCMS — Currency Configuration Helper
 *
 * Usage (anywhere after dbconn.php is included):
 *
 *   $currency = ssbs_default_currency();        // e.g. 'USD'
 *   $symbol   = ssbs_currency_symbol();         // e.g. '$'
 *   $label    = ssbs_currency_label();          // e.g. 'USD — US Dollar'
 *   $list     = ssbs_supported_currencies();    // ['USD'=>'US Dollar','SSP'=>'South Sudanese Pound']
 *   $select   = ssbs_currency_select_html('fee_currency', 'USD', 'form-select');
 *   $fmt      = ssbs_format_amount(12500.50);   // e.g. 'USD 12,500.50'
 *   $fmt      = ssbs_format_amount(12500.50, 'SSP');  // override currency
 */

// ── Supported currencies ─────────────────────────────────────────────────────
// Add more here as needed (e.g. EAC currencies for regional trade).
const SSBS_CURRENCIES = [
    'USD' => [
        'name'     => 'US Dollar',
        'symbol'   => '$',
        'decimals' => 2,
        'position' => 'before',   // symbol before amount
    ],
    'SSP' => [
        'name'     => 'South Sudanese Pound',
        'symbol'   => 'SSP',
        'decimals' => 2,
        'position' => 'before',
    ],
    'EUR' => [
        'name'     => 'Euro',
        'symbol'   => '€',
        'decimals' => 2,
        'position' => 'before',
    ],
    'KES' => [
        'name'     => 'Kenyan Shilling',
        'symbol'   => 'KSh',
        'decimals' => 2,
        'position' => 'before',
    ],
    'UGX' => [
        'name'     => 'Ugandan Shilling',
        'symbol'   => 'USh',
        'decimals' => 0,
        'position' => 'before',
    ],
    'ETB' => [
        'name'     => 'Ethiopian Birr',
        'symbol'   => 'ETB',
        'decimals' => 2,
        'position' => 'before',
    ],
];

// ── Internal cache (avoids a DB query per-request) ────────────────────────────
$_ssbs_currency_cache = [];

/**
 * Load currency settings from DB once per request.
 * Falls back to USD if the table isn't reachable yet.
 */
function _ssbs_load_currency_settings(): void
{
    global $conn, $_ssbs_currency_cache;

    if (!empty($_ssbs_currency_cache)) {
        return;
    }

    $defaults = [
        'default_currency'     => 'USD',
        'supported_currencies' => 'USD,SSP',
    ];

    if (!isset($conn) || !($conn instanceof mysqli) || $conn->connect_error) {
        $_ssbs_currency_cache = $defaults;
        return;
    }

    $keys   = "'default_currency','supported_currencies'";
    $result = $conn->query(
        "SELECT setting_key, setting_value
         FROM   system_settings
         WHERE  setting_key IN ({$keys})"
    );

    if (!$result) {
        $_ssbs_currency_cache = $defaults;
        return;
    }

    $rows = $result->fetch_all(MYSQLI_ASSOC);
    foreach ($rows as $row) {
        $defaults[$row['setting_key']] = $row['setting_value'];
    }
    $_ssbs_currency_cache = $defaults;
}

/**
 * Return the system default currency code (e.g. 'USD').
 */
function ssbs_default_currency(): string
{
    global $_ssbs_currency_cache;
    _ssbs_load_currency_settings();
    $code = strtoupper(trim($_ssbs_currency_cache['default_currency'] ?? 'USD'));
    return array_key_exists($code, SSBS_CURRENCIES) ? $code : 'USD';
}

/**
 * Return an associative array of enabled currencies [ 'USD' => 'US Dollar', ... ].
 * Only currencies listed in the supported_currencies setting are returned.
 */
function ssbs_supported_currencies(): array
{
    global $_ssbs_currency_cache;
    _ssbs_load_currency_settings();

    $enabled_codes = array_map(
        'trim',
        explode(',', strtoupper($_ssbs_currency_cache['supported_currencies'] ?? 'USD,SSP'))
    );

    $out = [];
    foreach ($enabled_codes as $code) {
        if (isset(SSBS_CURRENCIES[$code])) {
            $out[$code] = SSBS_CURRENCIES[$code]['name'];
        }
    }

    // Always include the default even if missing from the list
    $default = ssbs_default_currency();
    if (!isset($out[$default]) && isset(SSBS_CURRENCIES[$default])) {
        $out[$default] = SSBS_CURRENCIES[$default]['name'];
    }

    return $out;
}

/**
 * Return the symbol for the given (or default) currency.
 */
function ssbs_currency_symbol(string $code = ''): string
{
    $code = strtoupper(trim($code)) ?: ssbs_default_currency();
    return SSBS_CURRENCIES[$code]['symbol'] ?? $code;
}

/**
 * Return a human-readable label, e.g. "USD — US Dollar".
 */
function ssbs_currency_label(string $code = ''): string
{
    $code = strtoupper(trim($code)) ?: ssbs_default_currency();
    $name = SSBS_CURRENCIES[$code]['name'] ?? $code;
    return "{$code} — {$name}";
}

/**
 * Format a monetary amount with its currency symbol.
 *
 * ssbs_format_amount(12500)        → 'USD 12,500.00'   (using default currency)
 * ssbs_format_amount(12500, 'SSP') → 'SSP 12,500.00'
 * ssbs_format_amount(12500, 'USD', true) → '$12,500.00'  (use symbol instead of code)
 */
function ssbs_format_amount(float $amount, string $code = '', bool $use_symbol = false): string
{
    $code     = strtoupper(trim($code)) ?: ssbs_default_currency();
    $meta     = SSBS_CURRENCIES[$code] ?? ['symbol' => $code, 'decimals' => 2, 'position' => 'before'];
    $decimals = (int)$meta['decimals'];
    $prefix   = $use_symbol ? $meta['symbol'] : $code;
    $formatted = number_format($amount, $decimals);

    return $meta['position'] === 'before'
        ? "{$prefix} {$formatted}"
        : "{$formatted} {$prefix}";
}

/**
 * Render an HTML <select> element listing all supported currencies.
 *
 * @param string $name       The field name attribute.
 * @param string $selected   The currently selected code (defaults to system default).
 * @param string $class      CSS class(es) for the <select>.
 * @param bool   $show_symbol Whether to include the symbol in option text.
 */
function ssbs_currency_select_html(
    string $name     = 'currency',
    string $selected = '',
    string $class    = 'form-select',
    bool   $show_symbol = true
): string {
    $selected  = strtoupper(trim($selected)) ?: ssbs_default_currency();
    $supported = ssbs_supported_currencies();
    $id        = htmlspecialchars($name);
    $class_esc = htmlspecialchars($class);

    $html = "<select name=\"{$id}\" id=\"{$id}\" class=\"{$class_esc}\">\n";
    foreach ($supported as $code => $name_str) {
        $sym    = SSBS_CURRENCIES[$code]['symbol'] ?? $code;
        $label  = $show_symbol ? "{$code} ({$sym}) — {$name_str}" : "{$code} — {$name_str}";
        $sel    = ($code === $selected) ? ' selected' : '';
        $html  .= "  <option value=\"{$code}\"{$sel}>"
                . htmlspecialchars($label)
                . "</option>\n";
    }
    $html .= '</select>';
    return $html;
}

/**
 * Update the default currency in system_settings.
 * Returns true on success.
 * Call this from the settings save handler.
 */
function ssbs_set_default_currency(string $code): bool
{
    global $conn, $_ssbs_currency_cache;

    $code = strtoupper(trim($code));
    if (!array_key_exists($code, SSBS_CURRENCIES)) {
        return false;
    }

    if (!isset($conn) || !($conn instanceof mysqli)) {
        return false;
    }

    $stmt = $conn->prepare(
        "UPDATE system_settings SET setting_value = ? WHERE setting_key = 'default_currency'"
    );
    if (!$stmt) return false;
    $stmt->bind_param('s', $code);
    $ok = $stmt->execute();
    $stmt->close();

    // Bust the in-request cache
    if ($ok) {
        $_ssbs_currency_cache['default_currency'] = $code;
    }
    return $ok;
}

/**
 * Update the comma-separated list of supported currencies.
 * E.g. ssbs_set_supported_currencies(['USD','SSP'])
 */
function ssbs_set_supported_currencies(array $codes): bool
{
    global $conn, $_ssbs_currency_cache;

    $valid = array_filter(
        array_map('strtoupper', $codes),
        fn($c) => array_key_exists($c, SSBS_CURRENCIES)
    );

    if (empty($valid)) return false;

    $value = implode(',', array_unique($valid));

    if (!isset($conn) || !($conn instanceof mysqli)) {
        return false;
    }

    $stmt = $conn->prepare(
        "UPDATE system_settings SET setting_value = ? WHERE setting_key = 'supported_currencies'"
    );
    if (!$stmt) return false;
    $stmt->bind_param('s', $value);
    $ok = $stmt->execute();
    $stmt->close();

    if ($ok) {
        $_ssbs_currency_cache['supported_currencies'] = $value;
    }
    return $ok;
}
