<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'Rate Monitoring Dashboard';

if (!function_exists('h')) {
    function h($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('money_fmt')) {
    function money_fmt($amount, int $decimals = 5): string
    {
        return number_format((float)$amount, $decimals);
    }
}

if (!function_exists('rate_age_label')) {
    function rate_age_label(?string $date): array
    {
        if (!$date) {
            return ['Never updated', 'danger', 999999];
        }

        $ts = strtotime($date);
        if (!$ts) {
            return ['Invalid date', 'danger', 999999];
        }

        $hours = (time() - $ts) / 3600;

        if ($hours < 1) {
            return ['Updated just now', 'success', $hours];
        }

        if ($hours < 24) {
            return ['Updated ' . floor($hours) . 'h ago', 'success', $hours];
        }

        if ($hours < 48) {
            return ['Updated yesterday', 'warning', $hours];
        }

        return ['Stale: ' . floor($hours / 24) . ' days old', 'danger', $hours];
    }
}

if (!function_exists('is_iso_currency_code')) {
    function is_iso_currency_code(string $code): bool
    {
        return (bool)preg_match('/^[A-Z]{3}$/', strtoupper(trim($code)));
    }
}

if (!function_exists('rm_column_exists')) {
    function rm_column_exists(PDO $pdo, string $table, string $column): bool
    {
        static $cache = [];
        $key = $table . '.' . $column;
        if (array_key_exists($key, $cache)) return $cache[$key];

        try {
            $stmt = $pdo->prepare("\n                SELECT COUNT(*)\n                FROM INFORMATION_SCHEMA.COLUMNS\n                WHERE TABLE_SCHEMA = DATABASE()\n                  AND TABLE_NAME = :table_name\n                  AND COLUMN_NAME = :column_name\n            ");
            $stmt->execute([
                ':table_name'  => $table,
                ':column_name' => $column,
            ]);
            $cache[$key] = ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) {
            $cache[$key] = false;
        }
        return $cache[$key];
    }
}

if (!function_exists('rm_add_column_if_missing')) {
    function rm_add_column_if_missing(PDO $pdo, string $table, string $column, string $ddl): void
    {
        if (!rm_column_exists($pdo, $table, $column)) {
            try { $pdo->exec($ddl); } catch (Throwable $e) {}
        }
    }
}

if (!function_exists('exchange_rate_api_key')) {
    function exchange_rate_api_key(): string
    {
        $keys = [
            defined('EXCHANGE_RATE_API_KEY') ? EXCHANGE_RATE_API_KEY : '',
            defined('EXCHANGERATE_API_KEY') ? EXCHANGERATE_API_KEY : '',
            getenv('EXCHANGE_RATE_API_KEY') ?: '',
            getenv('EXCHANGERATE_API_KEY') ?: '',
        ];

        foreach ($keys as $key) {
            $key = trim((string)$key);
            if ($key !== '') return $key;
        }
        return '';
    }
}

if (!function_exists('exchange_rate_api_request')) {
    function exchange_rate_api_request(string $endpoint, ?string &$error = null): ?array
    {
        $error = null;
        $key = exchange_rate_api_key();
        if ($key === '') {
            $error = 'EXCHANGE_RATE_API_KEY is not configured.';
            return null;
        }

        $url = 'https://v6.exchangerate-api.com/v6/' . rawurlencode($key) . '/' . ltrim($endpoint, '/');
        $json = '';

        try {
            if (function_exists('curl_init')) {
                $ch = curl_init($url);
                curl_setopt_array($ch, [
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_CONNECTTIMEOUT => 8,
                    CURLOPT_TIMEOUT        => 15,
                    CURLOPT_SSL_VERIFYPEER => true,
                ]);
                $json = (string)curl_exec($ch);
                $curlErr = curl_error($ch);
                $status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);

                if ($json === '' || $status >= 400) {
                    $error = $curlErr !== '' ? $curlErr : 'ExchangeRate-API HTTP error ' . $status;
                    return null;
                }
            } else {
                $context = stream_context_create([
                    'http' => ['timeout' => 15],
                    'ssl'  => ['verify_peer' => true, 'verify_peer_name' => true],
                ]);
                $json = (string)@file_get_contents($url, false, $context);
                if ($json === '') {
                    $error = 'Could not connect to ExchangeRate-API.';
                    return null;
                }
            }

            $data = json_decode($json, true);
            if (!is_array($data)) {
                $error = 'ExchangeRate-API returned invalid JSON.';
                return null;
            }

            if (($data['result'] ?? '') !== 'success') {
                $error = 'ExchangeRate-API error: ' . (string)($data['error-type'] ?? 'unknown');
                return null;
            }

            return $data;
        } catch (Throwable $e) {
            $error = $e->getMessage();
            return null;
        }
    }
}

if (!function_exists('fetch_exchange_rate_codes')) {
    function fetch_exchange_rate_codes(bool $forceRefresh = false, ?string &$error = null): array
    {
        $error = null;
        $cacheKey = 'exchange_rate_api_supported_codes_cache';
        $timeKey  = 'exchange_rate_api_supported_codes_cache_time';

        if (!$forceRefresh && isset($_SESSION[$cacheKey], $_SESSION[$timeKey]) && (time() - (int)$_SESSION[$timeKey]) < 86400) {
            return is_array($_SESSION[$cacheKey]) ? $_SESSION[$cacheKey] : [];
        }

        $data = exchange_rate_api_request('codes', $error);
        if (!$data || empty($data['supported_codes']) || !is_array($data['supported_codes'])) {
            return [];
        }

        $codes = [];
        foreach ($data['supported_codes'] as $item) {
            if (!is_array($item) || count($item) < 2) continue;
            $code = strtoupper(trim((string)$item[0]));
            $name = trim((string)$item[1]);
            if (is_iso_currency_code($code)) {
                $codes[$code] = $name !== '' ? $name : $code;
            }
        }
        ksort($codes);

        $_SESSION[$cacheKey] = $codes;
        $_SESSION[$timeKey]  = time();

        return $codes;
    }
}

if (!function_exists('fetch_usd_conversion_rates')) {
    function fetch_usd_conversion_rates(?string &$error = null): array
    {
        $error = null;
        $data = exchange_rate_api_request('latest/USD', $error);
        if (!$data || empty($data['conversion_rates']) || !is_array($data['conversion_rates'])) {
            return [];
        }
        return $data['conversion_rates'];
    }
}

$errors = [];
$warnings = [];
$success = '';
$apiError = null;
$forceCodeRefresh = ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['refresh_api_codes']));
$apiCodes = fetch_exchange_rate_codes($forceCodeRefresh, $apiError);
if ($apiError !== null && exchange_rate_api_key() !== '') {
    $warnings[] = $apiError;
}

try {
    /* Optional audit columns. Safe on older MySQL versions because we check first. */
    rm_add_column_if_missing($pdo, 'tblcurrency', 'roe_direction', "ALTER TABLE tblcurrency ADD COLUMN roe_direction VARCHAR(30) NOT NULL DEFAULT 'CURRENCY_PER_USD'");
    rm_add_column_if_missing($pdo, 'tblcurrency', 'roe_updated_at', "ALTER TABLE tblcurrency ADD COLUMN roe_updated_at DATETIME NULL");
    rm_add_column_if_missing($pdo, 'tblcurrency', 'roe_source', "ALTER TABLE tblcurrency ADD COLUMN roe_source VARCHAR(80) NULL");


    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_currency_manual'])) {
        $currencyId = (int)($_POST['currency_id'] ?? 0);
        $code = strtoupper(trim((string)($_POST['edit_currency_code'] ?? '')));
        $name = trim((string)($_POST['edit_currency_name'] ?? ''));
        $roeRaw = trim((string)($_POST['edit_roe'] ?? ''));
        $status = (int)($_POST['edit_status'] ?? 1) === 1 ? 1 : 0;
        $orderNoRaw = trim((string)($_POST['edit_order_no'] ?? ''));

        if ($currencyId <= 0) {
            throw new RuntimeException('Invalid currency selected for manual update.');
        }
        if (!is_iso_currency_code($code)) {
            throw new RuntimeException('Currency code must be a valid 3-letter ISO code.');
        }
        if ($name === '') {
            throw new RuntimeException('Currency name is required.');
        }
        if ($roeRaw === '' || !is_numeric($roeRaw) || (float)$roeRaw <= 0) {
            throw new RuntimeException('Manual ROE must be a valid amount greater than zero.');
        }

        $roe = round((float)$roeRaw, 5);
        if ($code === 'USD') {
            $roe = 1.00000;
        }
        $orderNo = $orderNoRaw !== '' && is_numeric($orderNoRaw) ? (int)$orderNoRaw : null;

        $stmt = $pdo->prepare("\n            SELECT CurrencyID\n            FROM tblcurrency\n            WHERE UPPER(CurrencyCode) = :code\n              AND CurrencyID <> :id\n            LIMIT 1\n        ");
        $stmt->execute([':code' => $code, ':id' => $currencyId]);
        if ((int)($stmt->fetchColumn() ?: 0) > 0) {
            throw new RuntimeException('Another currency already uses code ' . $code . '.');
        }

        $stmt = $pdo->prepare("\n            UPDATE tblcurrency\n            SET CurrencyCode = :code,\n                Currency = :currency,\n                ROE = :roe,\n                status = :status,\n                `order_no` = :order_no,\n                roe_direction = 'CURRENCY_PER_USD',\n                roe_source = 'manual edit',\n                roe_updated_at = NOW()\n            WHERE CurrencyID = :id\n        ");
        $stmt->execute([
            ':code' => $code,
            ':currency' => $name,
            ':roe' => $roe,
            ':status' => $status,
            ':order_no' => $orderNo,
            ':id' => $currencyId,
        ]);
        $success = $code . ' updated manually.';
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['fix_usd'])) {
        $stmt = $pdo->prepare("\n            UPDATE tblcurrency\n            SET ROE = 1.00000,\n                roe_direction = 'CURRENCY_PER_USD',\n                roe_source = 'system correction',\n                roe_updated_at = NOW()\n            WHERE UPPER(CurrencyCode) = 'USD'\n        ");
        $stmt->execute();
        $success = 'USD base rate fixed to 1.00000.';
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_currency'])) {
        $code = strtoupper(trim((string)($_POST['currency_code'] ?? '')));
        $manualName = trim((string)($_POST['currency_name'] ?? ''));
        $makeActive = (int)($_POST['currency_status'] ?? 1) === 1 ? 1 : 0;
        $manualRoeRaw = trim((string)($_POST['manual_roe'] ?? ''));

        if (!is_iso_currency_code($code)) {
            throw new RuntimeException('Please select or enter a valid 3-letter ISO currency code.');
        }

        $currencyName = $manualName !== '' ? $manualName : ($apiCodes[$code] ?? $code);
        $roe = 0.00000;
        $source = 'ExchangeRate-API';

        if ($manualRoeRaw !== '') {
            if (!is_numeric($manualRoeRaw) || (float)$manualRoeRaw <= 0) {
                throw new RuntimeException('Manual ROE must be a valid amount greater than zero.');
            }
            $roe = round((float)$manualRoeRaw, 5);
            $source = 'manual entry';
        } elseif ($code === 'USD') {
            $roe = 1.00000;
            $source = 'system USD base';
        } else {
            $rateErr = null;
            $rates = fetch_usd_conversion_rates($rateErr);
            if (!$rates || !isset($rates[$code])) {
                throw new RuntimeException('Could not fetch current USD rate for ' . $code . '. ' . ($rateErr ?: 'Code was not returned by ExchangeRate-API.') . ' You can enter the ROE manually instead.');
            }
            $roe = round((float)$rates[$code], 5);
        }

        if ($code === 'USD') {
            $roe = 1.00000;
        }

        if ($roe <= 0) {
            throw new RuntimeException('Invalid ROE for ' . $code . '.');
        }

        $stmt = $pdo->prepare("\n            SELECT CurrencyID\n            FROM tblcurrency\n            WHERE UPPER(CurrencyCode) = :code\n            ORDER BY CurrencyID ASC\n            LIMIT 1\n        ");
        $stmt->execute([':code' => $code]);
        $existingId = (int)($stmt->fetchColumn() ?: 0);

        if ($existingId > 0) {
            $stmt = $pdo->prepare("\n                UPDATE tblcurrency\n                SET CurrencyCode = :code,\n                    Currency = :currency,\n                    ROE = :roe,\n                    status = :status,\n                    roe_direction = 'CURRENCY_PER_USD',\n                    roe_source = :source,\n                    roe_updated_at = NOW()\n                WHERE CurrencyID = :id\n            ");
            $stmt->execute([
                ':code'     => $code,
                ':currency' => $currencyName,
                ':roe'      => $roe,
                ':status'   => $makeActive,
                ':source'   => $source,
                ':id'       => $existingId,
            ]);
            $success = $code . ' already existed, so it was updated with the latest ExchangeRate-API rate.';
        } else {
            $nextOrder = 1;
            try {
                $nextOrder = (int)$pdo->query("SELECT COALESCE(MAX(`order_no`),0) + 1 FROM tblcurrency")->fetchColumn();
            } catch (Throwable $e) {}

            $stmt = $pdo->prepare("\n                INSERT INTO tblcurrency\n                    (CurrencyCode, Currency, ROE, status, `order_no`, roe_direction, roe_source, roe_updated_at)\n                VALUES\n                    (:code, :currency, :roe, :status, :order_no, 'CURRENCY_PER_USD', :source, NOW())\n            ");
            $stmt->execute([
                ':code'     => $code,
                ':currency' => $currencyName,
                ':roe'      => $roe,
                ':status'   => $makeActive,
                ':order_no' => $nextOrder,
                ':source'   => $source,
            ]);
            $success = $code . ' added successfully with current ExchangeRate-API ROE.';
        }
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['refresh_api_codes']) && $success === '') {
        $success = 'ExchangeRate-API currency code list refreshed.';
    }

    $stmt = $pdo->query("\n        SELECT\n            CurrencyID,\n            CurrencyCode,\n            Currency,\n            ROE,\n            status,\n            roe_direction,\n            roe_source,\n            roe_updated_at,\n            `order_no`\n        FROM tblcurrency\n        ORDER BY\n            CASE WHEN `order_no` IS NULL THEN 999999 ELSE `order_no` END ASC,\n            CurrencyCode ASC,\n            Currency ASC\n    ");
    $currencies = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (Throwable $e) {
    $currencies = [];
    $errors[] = $e->getMessage();

    try {
        $stmt = $pdo->query("\n            SELECT CurrencyID, CurrencyCode, Currency, ROE, status, roe_direction, roe_source, roe_updated_at, `order_no`\n            FROM tblcurrency\n            ORDER BY CASE WHEN `order_no` IS NULL THEN 999999 ELSE `order_no` END ASC, CurrencyCode ASC, Currency ASC\n        ");
        $currencies = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $ignored) {}
}

$totalCurrencies = count($currencies);
$activeCurrencies = 0;
$invalidCodes = 0;
$invalidRoe = 0;
$staleRates = 0;
$neverUpdated = 0;
$usdIssues = 0;
$existingCodes = [];

foreach ($currencies as $row) {
    $active = (int)($row['status'] ?? 0) === 1;
    if ($active) {
        $activeCurrencies++;
    }

    $code = strtoupper(trim((string)($row['CurrencyCode'] ?? '')));
    if ($code !== '') $existingCodes[$code] = true;
    $roe = (float)($row['ROE'] ?? 0);

    if (!is_iso_currency_code($code)) {
        $invalidCodes++;
    }

    if ($roe <= 0) {
        $invalidRoe++;
    }

    [$ageText, $ageClass, $hours] = rate_age_label($row['roe_updated_at'] ?? null);
    if (empty($row['roe_updated_at'])) {
        $neverUpdated++;
    } elseif ($hours > 24) {
        $staleRates++;
    }

    if ($code === 'USD' && abs($roe - 1.00000) > 0.00001) {
        $usdIssues++;
    }
}

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band rate-hero">
    <div class="d-flex flex-wrap justify-content-between align-items-center gap-2">
        <div>
            <div class="page-eyebrow text-white-50"><i class="bi bi-currency-exchange"></i> Exchange-rate control</div>
            <div class="hero-title rate-title">Rate Monitoring Dashboard</div>
            <div class="hero-subtitle rate-subtitle">Monitor ROE, add API-backed currencies, and keep USD-base direction locked.</div>
        </div>
        <div class="d-inline-flex gap-2 flex-wrap justify-content-end">
            <a href="/rooms/modules/payments/currency_rates_sync.php" target="_blank" class="btn btn-sm btn-light">
                <i class="bi bi-arrow-repeat me-1"></i>Run Sync
            </a>
            <a href="/rooms/modules/payments/payments.php" class="btn btn-sm btn-outline-light">
                <i class="bi bi-cash-stack me-1"></i>Payments
            </a>
        </div>
    </div>
</div>

<?php if ($success): ?>
    <div class="alert alert-success py-2"><?php echo h($success); ?></div>
<?php endif; ?>

<?php if ($warnings): ?>
    <div class="alert alert-warning py-2">
        <strong>Notice:</strong>
        <ul class="mb-0">
            <?php foreach ($warnings as $warning): ?>
                <li><?php echo h($warning); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<?php if ($errors): ?>
    <div class="alert alert-danger py-2">
        <strong>Please fix the following:</strong>
        <ul class="mb-0">
            <?php foreach ($errors as $error): ?>
                <li><?php echo h($error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<?php if (exchange_rate_api_key() === ''): ?>
    <div class="alert alert-info py-2">
        Add <code>EXCHANGE_RATE_API_KEY</code> in your config or environment to enable live currency-code lookup and automatic ROE fetching.
    </div>
<?php endif; ?>

<div class="row g-3 mb-3">
    <div class="col-md-6 col-xl-3">
        <div class="metric-card compact-metric">
            <div class="metric-icon bg-primary-subtle text-primary"><i class="bi bi-list-check"></i></div>
            <div>
                <div class="metric-label">Currencies</div>
                <div class="metric-value"><?php echo number_format($activeCurrencies); ?>/<?php echo number_format($totalCurrencies); ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-3">
        <div class="metric-card compact-metric">
            <div class="metric-icon bg-danger-subtle text-danger"><i class="bi bi-exclamation-triangle"></i></div>
            <div>
                <div class="metric-label">Invalid Codes</div>
                <div class="metric-value"><?php echo number_format($invalidCodes); ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-3">
        <div class="metric-card compact-metric">
            <div class="metric-icon bg-warning-subtle text-warning"><i class="bi bi-clock-history"></i></div>
            <div>
                <div class="metric-label">Stale Rates</div>
                <div class="metric-value"><?php echo number_format($staleRates + $neverUpdated); ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-3">
        <div class="metric-card compact-metric">
            <div class="metric-icon bg-success-subtle text-success"><i class="bi bi-shield-check"></i></div>
            <div>
                <div class="metric-label">ROE Direction</div>
                <div class="metric-value">USD Base</div>
            </div>
        </div>
    </div>
</div>

<div class="card panel-card mb-3">
    <div class="card-header py-2 d-flex justify-content-between align-items-center flex-wrap gap-2">
        <div>
            <h6 class="mb-0 fw-bold">Add / Update Currency from ExchangeRate-API</h6>
            <small>Pick an ISO code from the API list. ROE is saved as Currency per 1 USD.</small>
        </div>
        <form method="post" class="m-0">
            <button type="submit" name="refresh_api_codes" value="1" class="btn btn-sm btn-outline-secondary">
                <i class="bi bi-cloud-arrow-down me-1"></i>Refresh Codes
            </button>
        </form>
    </div>
    <div class="card-body py-3">
        <form method="post" class="row g-2 align-items-end" autocomplete="off">
            <div class="col-lg-3 col-md-4">
                <label class="form-label small fw-bold mb-1">Currency Code</label>
                <input list="apiCurrencyCodes" name="currency_code" id="currency_code" class="form-control form-control-sm" placeholder="e.g. AED" maxlength="3" required>
                <datalist id="apiCurrencyCodes">
                    <?php foreach ($apiCodes as $code => $name): ?>
                        <option value="<?php echo h($code); ?>" data-name="<?php echo h($name); ?>"><?php echo h($code . ' - ' . $name); ?></option>
                    <?php endforeach; ?>
                </datalist>
            </div>
            <div class="col-lg-3 col-md-5">
                <label class="form-label small fw-bold mb-1">Currency Name</label>
                <input name="currency_name" id="currency_name" class="form-control form-control-sm" placeholder="Auto-filled from API where possible">
            </div>
            <div class="col-lg-2 col-md-3">
                <label class="form-label small fw-bold mb-1">Manual ROE</label>
                <input type="number" step="0.00001" min="0" name="manual_roe" class="form-control form-control-sm" placeholder="Optional">
            </div>
            <div class="col-lg-2 col-md-3">
                <label class="form-label small fw-bold mb-1">Status</label>
                <select name="currency_status" class="form-select form-select-sm">
                    <option value="1">Active</option>
                    <option value="0">Inactive</option>
                </select>
            </div>
            <div class="col-lg-2 col-md-12 d-flex gap-2">
                <button type="submit" name="add_currency" value="1" class="btn btn-sm btn-primary flex-fill">
                    <i class="bi bi-plus-circle me-1"></i>Add / Update
                </button>
                <form method="post"></form>
            </div>
            <div class="col-12 small text-muted">
                Existing codes are updated instead of duplicated. Enter Manual ROE to bypass API. Available API codes loaded: <strong><?php echo number_format(count($apiCodes)); ?></strong>.
            </div>
        </form>
    </div>
</div>

<div class="card panel-card mb-3">
    <div class="card-header py-2 d-flex justify-content-between align-items-center flex-wrap gap-2">
        <div>
            <h6 class="mb-0 fw-bold">ROE Direction Lock</h6>
            <small>ROE = Currency per 1 USD. Effective USD Payment = Amount Entered / ROE.</small>
        </div>

        <form method="post" class="m-0">
            <button type="submit" name="fix_usd" value="1" class="btn btn-sm btn-outline-primary">
                <i class="bi bi-shield-lock me-1"></i>Fix USD = 1
            </button>
        </form>
    </div>
    <div class="card-body py-3">
        <div class="roe-rule-grid">
            <div class="roe-rule compact-rule">
                <span>ZAR</span>
                <strong>1 USD = 18.50 ZAR</strong>
                <small>Payment ZAR 1,850 / 18.50 = USD 100</small>
            </div>
            <div class="roe-rule compact-rule">
                <span>EUR</span>
                <strong>1 USD = 1.02 EUR</strong>
                <small>Payment EUR 102 / 1.02 = USD 100</small>
            </div>
            <div class="roe-rule compact-rule">
                <span>GBP</span>
                <strong>1 USD = 0.85 GBP</strong>
                <small>Payment GBP 85 / 0.85 = USD 100</small>
            </div>
        </div>
    </div>
</div>

<div class="card panel-card">
    <div class="card-header py-2 d-flex justify-content-between align-items-center flex-wrap gap-2">
        <div>
            <h6 class="mb-0 fw-bold">Currency Rates</h6>
            <small>Codes must be ISO format: USD, EUR, GBP, ZAR, BWP, AED, etc.</small>
        </div>
    </div>

    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-modern align-middle mb-0">
                <thead>
                    <tr>
                        <th>Currency</th>
                        <th>ISO Code</th>
                        <th class="text-end">ROE</th>
                        <th>Direction</th>
                        <th>USD → Currency</th>
                        <th>Currency → USD</th>
                        <th>Last Updated</th>
                        <th>Source</th>
                        <th>Status</th>
                        <th class="text-end">Action</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!$currencies): ?>
                    <tr>
                        <td colspan="10" class="text-center text-muted py-5">No currencies found.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($currencies as $row): ?>
                        <?php
                        $code = strtoupper(trim((string)($row['CurrencyCode'] ?? '')));
                        $name = trim((string)($row['Currency'] ?? ''));
                        $roe = (float)($row['ROE'] ?? 0);
                        $direction = trim((string)($row['roe_direction'] ?? 'CURRENCY_PER_USD'));
                        $source = trim((string)($row['roe_source'] ?? 'Manual'));
                        $active = (int)($row['status'] ?? 0) === 1;

                        $codeValid = is_iso_currency_code($code);
                        $roeValid = $roe > 0;
                        $usdValid = $code !== 'USD' || abs($roe - 1.00000) <= 0.00001;

                        [$ageText, $ageClass, $hours] = rate_age_label($row['roe_updated_at'] ?? null);

                        $rowClass = '';
                        if (!$codeValid || !$roeValid || !$usdValid) {
                            $rowClass = 'table-danger';
                        } elseif ($hours > 24 || empty($row['roe_updated_at'])) {
                            $rowClass = 'table-warning';
                        }

                        $reverse = $roeValid ? (1 / $roe) : 0;
                        ?>
                        <tr class="<?php echo h($rowClass); ?>">
                            <td>
                                <div class="data-stack">
                                    <input form="currency_form_<?php echo (int)$row['CurrencyID']; ?>" name="edit_currency_name" class="form-control form-control-sm currency-edit-name" value="<?php echo h($name !== '' ? $name : $code); ?>" required>
                                    <small>ID <?php echo (int)$row['CurrencyID']; ?></small>
                                </div>
                            </td>
                            <td>
                                <?php if ($codeValid): ?>
                                    <input form="currency_form_<?php echo (int)$row['CurrencyID']; ?>" name="edit_currency_code" class="form-control form-control-sm currency-code-input" value="<?php echo h($code); ?>" maxlength="3" required>
                                <?php else: ?>
                                    <span class="badge text-bg-danger"><?php echo h($code !== '' ? $code : 'MISSING'); ?></span>
                                    <div class="small text-danger mt-1">Use ISO code e.g. EUR</div>
                                <?php endif; ?>
                            </td>
                            <td class="text-end fw-bold">
                                <input form="currency_form_<?php echo (int)$row['CurrencyID']; ?>" type="number" step="0.00001" min="0.00001" name="edit_roe" class="form-control form-control-sm text-end currency-roe-input" value="<?php echo h($roeValid ? money_fmt($roe, 5) : '0.00000'); ?>" required>
                                <?php if (!$usdValid): ?>
                                    <div class="small text-danger">USD must be 1.00000</div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="badge text-bg-light border text-dark">
                                    <?php echo h($direction !== '' ? $direction : 'CURRENCY_PER_USD'); ?>
                                </span>
                            </td>
                            <td>
                                <?php if ($roeValid && $codeValid): ?>
                                    1 USD = <strong><?php echo money_fmt($roe, 5); ?> <?php echo h($code); ?></strong>
                                <?php else: ?>
                                    <span class="text-muted">-</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($roeValid && $codeValid): ?>
                                    1 <?php echo h($code); ?> = <strong><?php echo money_fmt($reverse, 5); ?> USD</strong>
                                <?php else: ?>
                                    <span class="text-muted">-</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="badge text-bg-<?php echo h($ageClass); ?>">
                                    <?php echo h($ageText); ?>
                                </span>
                                <?php if (!empty($row['roe_updated_at'])): ?>
                                    <div class="small text-muted mt-1"><?php echo h($row['roe_updated_at']); ?></div>
                                <?php endif; ?>
                            </td>
                            <td><?php echo h($source !== '' ? $source : 'Manual'); ?></td>
                            <td>
                                <select form="currency_form_<?php echo (int)$row['CurrencyID']; ?>" name="edit_status" class="form-select form-select-sm">
                                    <option value="1" <?php echo $active ? 'selected' : ''; ?>>Active</option>
                                    <option value="0" <?php echo !$active ? 'selected' : ''; ?>>Inactive</option>
                                </select>
                            </td>
                            <td class="text-end">
                                <input form="currency_form_<?php echo (int)$row['CurrencyID']; ?>" type="hidden" name="currency_id" value="<?php echo (int)$row['CurrencyID']; ?>">
                                <input form="currency_form_<?php echo (int)$row['CurrencyID']; ?>" type="hidden" name="edit_order_no" value="<?php echo h((string)($row['order_no'] ?? '')); ?>">
                                <form id="currency_form_<?php echo (int)$row['CurrencyID']; ?>" method="post" class="m-0"></form>
                                <button form="currency_form_<?php echo (int)$row['CurrencyID']; ?>" type="submit" name="save_currency_manual" value="1" class="btn btn-sm btn-primary">
                                    <i class="bi bi-save me-1"></i>Save
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
(function () {
    const map = <?php echo json_encode($apiCodes, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
    const codeInput = document.getElementById('currency_code');
    const nameInput = document.getElementById('currency_name');
    if (!codeInput || !nameInput) return;

    function fillName() {
        const code = (codeInput.value || '').trim().toUpperCase();
        codeInput.value = code;
        if (map[code] && nameInput.value.trim() === '') {
            nameInput.value = map[code];
        }
    }

    codeInput.addEventListener('change', fillName);
    codeInput.addEventListener('blur', fillName);
})();
</script>

<style>
.rate-hero {
    padding: 10px 14px !important;
    border-radius: 16px;
    margin-bottom: .75rem !important;
}
.rate-title {
    font-size: 1.18rem !important;
    line-height: 1.15 !important;
    margin-top: 2px !important;
}
.rate-subtitle {
    font-size: .78rem !important;
    line-height: 1.2 !important;
    margin-top: 2px !important;
}
.compact-metric {
    min-height: 74px;
    padding: 12px !important;
}
.roe-rule-grid {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 10px;
}
.roe-rule {
    border: 1px solid #e5e7eb;
    border-radius: 16px;
    padding: 12px;
    background: linear-gradient(135deg, #ffffff, #f8fafc);
}
.compact-rule { padding: 10px 12px; }
.roe-rule span {
    display: inline-flex;
    font-size: .68rem;
    font-weight: 900;
    color: #2563eb;
    background: #eff6ff;
    border: 1px solid #bfdbfe;
    border-radius: 999px;
    padding: 2px 7px;
    margin-bottom: 6px;
}
.roe-rule strong {
    display: block;
    font-size: .9rem;
    color: #0f172a;
}
.roe-rule small {
    display: block;
    margin-top: 3px;
    color: #64748b;
}
.data-stack strong {
    display: block;
    font-weight: 800;
}
.data-stack small {
    display: block;
    color: #64748b;
}
.table-modern th,
.table-modern td {
    font-size: .84rem;
}
.currency-edit-name{min-width:170px;}
.currency-code-input{width:86px;text-transform:uppercase;font-weight:800;}
.currency-roe-input{min-width:118px;font-weight:800;}
@media (max-width: 991.98px) {
    .roe-rule-grid {
        grid-template-columns: 1fr;
    }
}
</style>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
