<?php
$current_page = 'nowpayments';
$api_key_configured = $api_key_configured ?? false;
$bearer_configured = $bearer_configured ?? false;
$balance_result = $balance_result ?? null;
$fiat_list_result = $fiat_list_result ?? null;
$fiat_filters = $fiat_filters ?? [];
$payment_lookup = $payment_lookup ?? null;
$payment_id_input = $payment_id_input ?? '';
$crypto_payout_lookup = $crypto_payout_lookup ?? null;
$crypto_payout_id_input = $crypto_payout_id_input ?? '';
$fiat_providers_result = $fiat_providers_result ?? null;
$bearer_static = $bearer_static ?? false;
$bearer_via_auth = $bearer_via_auth ?? false;
$ipn_secret_configured = $ipn_secret_configured ?? false;
$nowpayments_ipn_url = $nowpayments_ipn_url ?? '';

$fiatRows = [];
if (!empty($fiat_list_result['success']) && is_array($fiat_list_result['data'] ?? null)) {
    $d = $fiat_list_result['data'];
    $r = is_array($d['result'] ?? null) ? $d['result'] : $d;
    $fiatRows = is_array($r['rows'] ?? null) ? $r['rows'] : [];
}

$providerList = [];
if (!empty($fiat_providers_result['success']) && is_array($fiat_providers_result['data']['result'] ?? null)) {
    $providerList = $fiat_providers_result['data']['result'];
}

$balanceRows = [];
if (!empty($balance_result['success']) && is_array($balance_result['data'] ?? null)) {
    foreach ($balance_result['data'] as $ccy => $row) {
        if (!is_array($row) || isset($row['raw']) || isset($row['value'])) {
            continue;
        }
        $balanceRows[] = [
            'currency' => (string) $ccy,
            'amount' => $row['amount'] ?? null,
            'pending' => $row['pendingAmount'] ?? $row['pending_amount'] ?? null,
        ];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NOWPayments - Admin App</title>
    <link rel="icon" href="/favicon.svg" type="image/svg+xml">
    <link rel="icon" href="/favicon.ico" sizes="any">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <?= view('admin/partials/admin_styles') ?>
    <style>
        .page-header { margin-bottom: 1.5rem; }
        .page-title { font-size: 1.5rem; color: #1e293b; font-weight: 700; }
        .breadcrumb { display: flex; align-items: center; gap: 0.5rem; color: #64748b; margin-top: 0.35rem; font-size: 0.9rem; }
        .breadcrumb a { color: #6366f1; text-decoration: none; font-weight: 500; }
        .np-section {
            background: #fff;
            padding: 1.5rem;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.06);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }
        .np-section h3 { font-size: 1.1rem; color: #1e293b; margin-bottom: 1rem; display: flex; align-items: center; gap: 0.5rem; }
        .np-section h3 i { color: #6366f1; }
        .np-stat-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 1rem; margin-bottom: 1rem; }
        .np-stat { background: #f8fafc; padding: 1rem; border-radius: 10px; border: 1px solid #e2e8f0; }
        .np-stat .lbl { font-size: 0.75rem; text-transform: uppercase; color: #64748b; font-weight: 600; }
        .np-stat .val { font-size: 1.1rem; font-weight: 700; color: #1e293b; margin-top: 0.25rem; }
        .np-stat.ok .val { color: #059669; }
        .np-stat.bad .val { color: #dc2626; }
        .not-configured {
            background: #fef3c7;
            border: 1px solid #f59e0b;
            color: #92400e;
            padding: 1.25rem;
            border-radius: 12px;
            margin-bottom: 1.5rem;
        }
        .error-msg { background: #fee2e2; color: #991b1b; padding: 0.75rem 1rem; border-radius: 8px; margin-top: 0.75rem; font-size: 0.9rem; }
        .form-row { display: flex; gap: 1rem; flex-wrap: wrap; align-items: flex-end; margin-bottom: 1rem; }
        .form-group { flex: 1; min-width: 140px; }
        .form-group label { display: block; margin-bottom: 0.35rem; font-weight: 600; color: #374151; font-size: 0.85rem; }
        .form-group input, .form-group select { width: 100%; padding: 0.55rem 0.75rem; border: 2px solid #e2e8f0; border-radius: 8px; font-size: 0.9rem; }
        .form-group input:focus, .form-group select:focus { outline: none; border-color: #6366f1; }
        .btn {
            padding: 0.55rem 1.15rem;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 0.9rem;
            font-weight: 600;
            background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            color: white;
            text-decoration: none;
            display: inline-block;
        }
        .btn:hover { opacity: 0.95; }
        .btn-secondary { background: #64748b; color: white; }
        .data-table { width: 100%; border-collapse: collapse; font-size: 0.85rem; }
        .data-table th, .data-table td { padding: 0.65rem 0.75rem; text-align: left; border-bottom: 1px solid #e2e8f0; }
        .data-table th { background: #f8fafc; font-weight: 600; color: #475569; }
        .data-table .mono { font-family: ui-monospace, monospace; font-size: 0.8rem; }
        .data-table .status { font-weight: 600; color: #6366f1; }
        .json-preview {
            background: #0f172a;
            color: #e2e8f0;
            padding: 1rem;
            border-radius: 8px;
            font-size: 0.78rem;
            overflow: auto;
            max-height: 320px;
            margin-top: 0.75rem;
        }
        .filter-actions { display: flex; gap: 0.75rem; flex-wrap: wrap; align-items: center; margin-top: 0.5rem; }
        .api-info { font-size: 0.85rem; color: #64748b; margin-top: 0.5rem; }
        .api-info code { font-family: ui-monospace, monospace; font-size: 0.82em; word-break: break-all; }
        .chip-row { display: flex; flex-wrap: wrap; gap: 0.4rem; margin-top: 0.5rem; }
        .chip { background: #eef2ff; color: #4338ca; padding: 0.25rem 0.6rem; border-radius: 6px; font-size: 0.75rem; font-weight: 600; }
    </style>
</head>
<body>
<?= view('admin/partials/header_sidebar') ?>

<div class="page-header">
    <h1 class="page-title"><i class="fas fa-bitcoin-sign"></i> NOWPayments</h1>
    <div class="breadcrumb">
        <a href="<?= site_url('admin/dashboard') ?>">Dashboard</a>
        <span>/</span>
        <span>NOWPayments</span>
    </div>
    <p class="api-info">Live data from NOWPayments API. Payments and crypto payout lookups use the API key. Fiat and payout-create need a JWT: set <code>nowpayments.bearer_token</code>, or <code>nowpayments.auth_email</code> + <code>nowpayments.auth_password</code> (dashboard login) so the server obtains a token via <code>POST /v1/auth</code> (cached 4 minutes; JWT expires in 5).</p>
    <?php if ($nowpayments_ipn_url !== ''): ?>
        <p class="api-info"><strong>IPN:</strong> set callback URL in NOWPayments to <code><?= esc($nowpayments_ipn_url) ?></code> and the same <code>nowpayments.ipn_secret</code> as in the dashboard. Requests must include header <code>x-nowpayments-sig</code> (verified when the secret is set in <code>.env</code>).</p>
    <?php endif; ?>
</div>

<?php if (!$api_key_configured && !$bearer_configured): ?>
    <div class="not-configured">
        <strong>Not configured.</strong>
        <p>Set <code>nowpayments.api_key</code> and <code>nowpayments.bearer_token</code> in <code>.env</code>, then reload.</p>
    </div>
<?php elseif (!$api_key_configured): ?>
    <div class="not-configured">
        <strong>API key missing.</strong>
        <p>Set <code>nowpayments.api_key</code> for balances and payment / crypto payout lookups.</p>
    </div>
<?php elseif (!$bearer_configured): ?>
    <div class="not-configured">
        <strong>Bearer JWT missing.</strong>
        <p>Set <code>nowpayments.bearer_token</code> or dashboard <code>nowpayments.auth_email</code> + <code>nowpayments.auth_password</code> to load fiat payouts and providers. Crypto balance still works below.</p>
    </div>
<?php endif; ?>

<div class="np-stat-grid">
    <div class="np-stat <?= $api_key_configured ? 'ok' : 'bad' ?>">
        <div class="lbl">API key</div>
        <div class="val"><?= $api_key_configured ? 'Configured' : 'Missing' ?></div>
    </div>
    <div class="np-stat <?= $bearer_configured ? 'ok' : 'bad' ?>">
        <div class="lbl">Bearer (any)</div>
        <div class="val"><?= $bearer_configured ? 'Yes' : 'No' ?></div>
    </div>
    <div class="np-stat <?= $bearer_static ? 'ok' : 'bad' ?>">
        <div class="lbl">Static JWT in .env</div>
        <div class="val"><?= $bearer_static ? 'Yes' : 'No' ?></div>
    </div>
    <div class="np-stat <?= $bearer_via_auth ? 'ok' : 'bad' ?>">
        <div class="lbl">Dashboard auth in .env</div>
        <div class="val"><?= $bearer_via_auth ? 'Yes' : 'No' ?></div>
    </div>
    <div class="np-stat <?= $ipn_secret_configured ? 'ok' : 'bad' ?>">
        <div class="lbl">IPN secret (.env)</div>
        <div class="val"><?= $ipn_secret_configured ? 'Set' : 'Missing' ?></div>
    </div>
</div>

<?php if ($api_key_configured): ?>
    <div class="np-section">
        <h3><i class="fas fa-wallet"></i> Crypto balance</h3>
        <?php if (empty($balance_result['success'])): ?>
            <p class="api-info">Could not load balance.</p>
            <?php if (!empty($balance_result['message'])): ?>
                <div class="error-msg"><?= esc($balance_result['message']) ?></div>
            <?php endif; ?>
        <?php elseif ($balanceRows === []): ?>
            <p class="api-info">No currency rows in response (check API response shape).</p>
            <pre class="json-preview"><?= esc(json_encode($balance_result['data'] ?? [], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) ?></pre>
        <?php else: ?>
            <table class="data-table">
                <thead>
                    <tr>
                        <th>Currency</th>
                        <th>Amount</th>
                        <th>Pending</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($balanceRows as $br): ?>
                        <tr>
                            <td class="mono"><?= esc(strtoupper($br['currency'])) ?></td>
                            <td><?= esc((string) ($br['amount'] ?? '')) ?></td>
                            <td><?= esc((string) ($br['pending'] ?? '')) ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>

    <div class="np-section">
        <h3><i class="fas fa-search-dollar"></i> Look up payment</h3>
        <form method="get" action="<?= site_url('admin/nowpayments') ?>" class="form-row">
            <input type="hidden" name="crypto_payout_id" value="<?= esc($crypto_payout_id_input) ?>">
            <?php foreach (['status', 'provider', 'limit', 'page', 'id', 'requestId', 'fiatCurrency', 'cryptoCurrency', 'dateFrom', 'dateTo'] as $fk): ?>
                <?php $fv = $fiat_filters[$fk] ?? ''; if ($fv !== null && $fv !== ''): ?>
                    <input type="hidden" name="<?= esc($fk) ?>" value="<?= esc((string) $fv) ?>">
                <?php endif; ?>
            <?php endforeach; ?>
            <div class="form-group" style="flex: 2; min-width: 220px;">
                <label for="payment_id">Payment ID</label>
                <input type="text" id="payment_id" name="payment_id" value="<?= esc($payment_id_input) ?>" placeholder="e.g. 6249365965">
            </div>
            <button type="submit" class="btn">Fetch status</button>
            <?php if ($payment_id_input !== ''): ?>
                <a href="<?= site_url('admin/nowpayments') ?>" class="btn btn-secondary">Clear</a>
            <?php endif; ?>
        </form>
        <?php if ($payment_id_input !== '' && $payment_lookup !== null): ?>
            <?php if (empty($payment_lookup['success'])): ?>
                <div class="error-msg"><?= esc($payment_lookup['message'] ?? 'Request failed') ?></div>
                <?php if (!empty($payment_lookup['data'])): ?>
                    <pre class="json-preview"><?= esc(json_encode($payment_lookup['data'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) ?></pre>
                <?php endif; ?>
            <?php else: ?>
                <p class="api-info">Status: <strong class="status"><?= esc((string) ($payment_lookup['data']['payment_status'] ?? 'unknown')) ?></strong>
                    <?php if (isset($payment_lookup['data']['order_id']) && $payment_lookup['data']['order_id'] !== null): ?>
                        &middot; Order: <span class="mono"><?= esc((string) $payment_lookup['data']['order_id']) ?></span>
                    <?php endif; ?>
                </p>
                <pre class="json-preview"><?= esc(json_encode($payment_lookup['data'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) ?></pre>
            <?php endif; ?>
        <?php endif; ?>
    </div>

    <div class="np-section">
        <h3><i class="fas fa-arrow-right-arrow-left"></i> Look up crypto payout</h3>
        <form method="get" action="<?= site_url('admin/nowpayments') ?>" class="form-row">
            <input type="hidden" name="payment_id" value="<?= esc($payment_id_input) ?>">
            <?php foreach (['status', 'provider', 'limit', 'page', 'id', 'requestId', 'fiatCurrency', 'cryptoCurrency', 'dateFrom', 'dateTo'] as $fk): ?>
                <?php $fv = $fiat_filters[$fk] ?? ''; if ($fv !== null && $fv !== ''): ?>
                    <input type="hidden" name="<?= esc($fk) ?>" value="<?= esc((string) $fv) ?>">
                <?php endif; ?>
            <?php endforeach; ?>
            <div class="form-group" style="flex: 2; min-width: 220px;">
                <label for="crypto_payout_id">Payout ID</label>
                <input type="text" id="crypto_payout_id" name="crypto_payout_id" value="<?= esc($crypto_payout_id_input) ?>" placeholder="NOWPayments payout id">
            </div>
            <button type="submit" class="btn">Fetch status</button>
            <?php if ($crypto_payout_id_input !== ''): ?>
                <a href="<?= site_url('admin/nowpayments') ?>" class="btn btn-secondary">Clear</a>
            <?php endif; ?>
        </form>
        <?php if ($crypto_payout_id_input !== '' && $crypto_payout_lookup !== null): ?>
            <?php if (empty($crypto_payout_lookup['success'])): ?>
                <div class="error-msg"><?= esc($crypto_payout_lookup['message'] ?? 'Request failed') ?></div>
                <?php if (!empty($crypto_payout_lookup['data'])): ?>
                    <pre class="json-preview"><?= esc(json_encode($crypto_payout_lookup['data'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) ?></pre>
                <?php endif; ?>
            <?php else: ?>
                <pre class="json-preview"><?= esc(json_encode($crypto_payout_lookup['data'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) ?></pre>
            <?php endif; ?>
        <?php endif; ?>
    </div>
<?php endif; ?>

<?php if ($bearer_configured): ?>
    <div class="np-section">
        <h3><i class="fas fa-building"></i> Fiat providers</h3>
        <?php if (empty($fiat_providers_result['success'])): ?>
            <div class="error-msg"><?= esc($fiat_providers_result['message'] ?? 'Could not load providers') ?></div>
        <?php elseif ($providerList === []): ?>
            <p class="api-info">No providers in response.</p>
        <?php else: ?>
            <div class="chip-row">
                <?php foreach ($providerList as $p): ?>
                    <?php if (!is_array($p)) { continue; }
                    $pn = (string) ($p['name'] ?? '');
                    $pc = (string) ($p['code'] ?? '');
                    $plabel = $pn !== '' ? ($pc !== '' ? $pn . ' (' . $pc . ')' : $pn) : ($pc !== '' ? $pc : '?');
                    ?>
                    <span class="chip"><?= esc($plabel) ?></span>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <div class="np-section">
        <h3><i class="fas fa-list"></i> Fiat payouts</h3>
        <form method="get" action="<?= site_url('admin/nowpayments') ?>" class="form-row">
            <input type="hidden" name="payment_id" value="<?= esc($payment_id_input) ?>">
            <input type="hidden" name="crypto_payout_id" value="<?= esc($crypto_payout_id_input) ?>">
            <div class="form-group">
                <label for="f_status">Status</label>
                <input type="text" id="f_status" name="status" value="<?= esc((string) ($fiat_filters['status'] ?? '')) ?>" placeholder="e.g. FINISHED">
            </div>
            <div class="form-group">
                <label for="f_provider">Provider</label>
                <input type="text" id="f_provider" name="provider" value="<?= esc((string) ($fiat_filters['provider'] ?? '')) ?>" placeholder="e.g. transfi">
            </div>
            <div class="form-group">
                <label for="f_limit">Limit</label>
                <input type="number" id="f_limit" name="limit" value="<?= esc((string) ($fiat_filters['limit'] ?? '20')) ?>" min="1" max="100">
            </div>
            <div class="form-group">
                <label for="f_page">Page</label>
                <input type="number" id="f_page" name="page" value="<?= esc((string) ($fiat_filters['page'] ?? '1')) ?>" min="1">
            </div>
            <div class="form-group">
                <label for="f_id">Id</label>
                <input type="text" id="f_id" name="id" value="<?= esc((string) ($fiat_filters['id'] ?? '')) ?>">
            </div>
            <div class="form-group">
                <label for="f_req">Request ID</label>
                <input type="text" id="f_req" name="requestId" value="<?= esc((string) ($fiat_filters['requestId'] ?? '')) ?>">
            </div>
            <div class="form-group">
                <label for="f_fc">Fiat currency</label>
                <input type="text" id="f_fc" name="fiatCurrency" value="<?= esc((string) ($fiat_filters['fiatCurrency'] ?? '')) ?>">
            </div>
            <div class="form-group">
                <label for="f_cc">Crypto currency</label>
                <input type="text" id="f_cc" name="cryptoCurrency" value="<?= esc((string) ($fiat_filters['cryptoCurrency'] ?? '')) ?>">
            </div>
            <div class="form-group">
                <label for="f_df">Date from</label>
                <input type="date" id="f_df" name="dateFrom" value="<?= esc((string) ($fiat_filters['dateFrom'] ?? '')) ?>">
            </div>
            <div class="form-group">
                <label for="f_dt">Date to</label>
                <input type="date" id="f_dt" name="dateTo" value="<?= esc((string) ($fiat_filters['dateTo'] ?? '')) ?>">
            </div>
            <div class="filter-actions">
                <button type="submit" class="btn">Apply filters</button>
                <a href="<?= site_url('admin/nowpayments') ?>" class="btn btn-secondary">Reset</a>
            </div>
        </form>

        <?php if (empty($fiat_list_result['success'])): ?>
            <div class="error-msg"><?= esc($fiat_list_result['message'] ?? 'Could not load fiat payouts') ?></div>
        <?php elseif ($fiatRows === []): ?>
            <p class="api-info">No rows returned for the current filters.</p>
        <?php else: ?>
            <table class="data-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Provider</th>
                        <th>Status</th>
                        <th>Fiat</th>
                        <th>Crypto</th>
                        <th>Updated</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($fiatRows as $row): ?>
                        <?php if (!is_array($row)) { continue; } ?>
                        <tr>
                            <td class="mono"><?= esc((string) ($row['id'] ?? '')) ?></td>
                            <td><?= esc((string) ($row['provider'] ?? '')) ?></td>
                            <td class="status"><?= esc((string) ($row['status'] ?? '')) ?></td>
                            <td><?= esc(trim((string) ($row['fiatAmount'] ?? '') . ' ' . strtoupper((string) ($row['fiatCurrencyCode'] ?? '')))) ?></td>
                            <td class="mono"><?= esc(trim((string) ($row['cryptoCurrencyAmount'] ?? '') . ' ' . strtoupper((string) ($row['cryptoCurrencyCode'] ?? '')))) ?></td>
                            <td class="mono"><?= esc((string) ($row['updatedAt'] ?? $row['updated_at'] ?? '')) ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
<?php endif; ?>

<?= view('admin/partials/footer') ?>
</body>
</html>
