<?php
// Currency helper functions

function getAllCurrencies($activeOnly = true) {
    $db = getDB();
    $sql = "SELECT * FROM currencies" . ($activeOnly ? " WHERE is_active=1" : "") . " ORDER BY is_default DESC, code";
    try {
        return $db->query($sql)->fetchAll();
    } catch(Exception $e) { return []; }
}

function getDefaultCurrency() {
    $db = getDB();
    try {
        $r = $db->query("SELECT * FROM currencies WHERE is_default=1 LIMIT 1")->fetch();
        return $r ?: ['code'=>'BDT','name'=>'Bangladeshi Taka','symbol'=>'৳','rate'=>1];
    } catch(Exception $e) {
        return ['code'=>'BDT','name'=>'Bangladeshi Taka','symbol'=>'৳','rate'=>1];
    }
}

function getUserCurrency($userId = null) {
    if (!$userId) {
        $user = getCurrentUser();
        $userId = $user['id'] ?? 0;
    }
    $db = getDB();
    try {
        $pref = $db->prepare("SELECT preferred_currency FROM users WHERE id=?")->execute([$userId]);
        $code = $db->prepare("SELECT preferred_currency FROM users WHERE id=?")->execute([$userId]) 
                ? $db->prepare("SELECT preferred_currency FROM users WHERE id=?")->execute([$userId]) 
                : 'BDT';
        $stmt = $db->prepare("SELECT u.preferred_currency, c.* FROM users u LEFT JOIN currencies c ON u.preferred_currency=c.code WHERE u.id=?");
        $stmt->execute([$userId]);
        $r = $stmt->fetch();
        if ($r && $r['code']) return $r;
    } catch(Exception $e) {}
    return getDefaultCurrency();
}

function convertBDT($bdtAmount, $toCurrency) {
    if (!$toCurrency || $toCurrency['code'] === 'BDT') return floatval($bdtAmount);
    return round(floatval($bdtAmount) * floatval($toCurrency['rate']), 2);
}

function formatAmount($bdtAmount, $currency) {
    $converted = convertBDT($bdtAmount, $currency);
    $symbol = $currency['symbol'] ?? '৳';
    if (in_array($currency['code'] ?? 'BDT', ['BDT','INR','PKR','NPR','LKR'])) {
        return $symbol . number_format($converted, 2);
    }
    return $symbol . number_format($converted, 2);
}
