<div class="stock-header" style="background: linear-gradient(120deg, #1D7A8C 0%, #124D58 100%);">
    <div class="sth-icon"><i class="fa-solid fa-sack-dollar"></i></div>
    <div class="sth-text">
        <h2>Payments</h2>
        <div class="sth-sub">
            Today: <?= formatMoney((float) $stats['today_total']) ?> · This Month: <?= formatMoney((float) $stats['month_total']) ?> · <?= (int) $unpaidCount ?> unpaid orders
        </div>
    </div>
    <div class="sth-actions">
        <?php if (Auth::can('payments', 'add') || Auth::can('payments', 'edit')): ?>
        <button type="button" class="btn sth-btn" onclick="rmsOpenModal('rmsMethodsModal')"><i class="fa-solid fa-gear"></i> Manage Methods</button>
        <?php endif; ?>
        <a href="<?= Router::url('orders?status=ALL') ?>" class="btn sth-btn"><i class="fa-solid fa-receipt"></i> View Orders</a>
    </div>
</div>

<?php if ($unpaidCount > 0): ?>
<div class="alert-chips">
    <span class="alert-chip ac-red"><i class="fa-solid fa-triangle-exclamation"></i> <?= (int) $unpaidCount ?> order(s) awaiting payment</span>
    <?php if ($oldestUnpaidHours !== null && $oldestUnpaidHours > 24): ?>
    <span class="alert-chip ac-gold"><i class="fa-solid fa-hourglass-half"></i> Oldest unpaid order is <?= round($oldestUnpaidHours / 24, 1) ?> day(s) old</span>
    <?php endif; ?>
</div>
<?php endif; ?>

<div class="stat-mini-grid">
    <div class="stat-mini sm-blue"><div class="sm-value"><?= formatMoney((float) $stats['today_total']) ?></div><div class="sm-label">Today's Collections</div></div>
    <div class="stat-mini sm-green"><div class="sm-value"><?= formatMoney((float) $stats['month_total']) ?></div><div class="sm-label">This Month</div></div>
    <div class="stat-mini sm-gold"><div class="sm-value"><?= formatMoney((float) $stats['today_fees']) ?></div><div class="sm-label">Today's Fees</div></div>
    <div class="stat-mini sm-red"><div class="sm-value"><?= (int) $unpaidCount ?></div><div class="sm-label">Unpaid Orders</div></div>
</div>

<div style="display:grid;grid-template-columns:1.4fr 1fr;gap:16px;align-items:start;">
    <div class="panel">
        <div class="panel-head">
            <h3><i class="fa-solid fa-chart-line" style="color:var(--color-teal);margin-right:6px;"></i>Collection Trend — Last 7 Days</h3>
        </div>
        <canvas id="rmsPaymentTrendChart" height="90"></canvas>
    </div>

    <div class="panel">
        <div class="panel-head">
            <h3><i class="fa-solid fa-chart-pie" style="color:var(--color-teal);margin-right:6px;"></i>Today by Method</h3>
        </div>
        <?php foreach ($breakdown as $b): ?>
        <div style="display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid var(--color-border);font-size:12.5px;">
            <span><?= e(str_replace('_', ' ', $b['method_name'])) ?> <span class="badge badge-gray"><?= (int) $b['cnt'] ?></span></span>
            <strong><?= formatMoney((float) $b['total']) ?></strong>
        </div>
        <?php endforeach; ?>
        <?php if (empty($breakdown)): ?>
        <div style="color:var(--color-text-muted);font-size:12.5px;text-align:center;padding:16px 0;">No active payment methods configured.</div>
        <?php endif; ?>
    </div>
</div>

<form method="GET" action="<?= Router::url('payments') ?>" class="filter-bar">
    <input type="hidden" name="method" value="<?= e($activeMethod) ?>">
    <div class="fb-search" style="flex:1;min-width:180px;"><i class="fa-solid fa-magnifying-glass"></i><input type="text" name="search" placeholder="Order#, phone, name..." value="<?= e($search) ?>"></div>
    <input type="date" name="date_from" class="form-control" style="width:auto;" value="<?= e($dateFrom) ?>">
    <span style="color:var(--color-text-muted);font-size:12px;">to</span>
    <input type="date" name="date_to" class="form-control" style="width:auto;" value="<?= e($dateTo) ?>">
    <button type="submit" class="btn btn-secondary"><i class="fa-solid fa-filter"></i> Filter</button>
    <a href="<?= Router::url('payments') ?>" class="btn btn-secondary"><i class="fa-solid fa-xmark"></i></a>
</form>

<div style="display:flex;gap:6px;flex-wrap:wrap;margin-bottom:16px;">
    <a href="<?= Router::url('payments?method=ALL') ?>" class="btn <?= $activeMethod === 'ALL' ? 'btn-primary' : 'btn-secondary' ?>" style="padding:6px 14px;font-size:12.5px;">All</a>
    <?php foreach ($methods as $m): ?>
    <a href="<?= Router::url('payments?method=' . $m['id']) ?>" class="btn <?= (string)$activeMethod === (string)$m['id'] ? 'btn-primary' : 'btn-secondary' ?>" style="padding:6px 14px;font-size:12.5px;"><?= e(str_replace('_', ' ', $m['method_name'])) ?></a>
    <?php endforeach; ?>
</div>

<div class="dark-table-panel">
    <div class="dtp-head">
        <span><i class="fa-solid fa-table-list"></i> Payment Ledger</span>
        <span class="dtp-count"><?= count($payments) ?> records</span>
    </div>
    <div style="overflow-x:auto;">
    <table class="data-table">
    <thead><tr><th>#</th><th>Date</th><th>Order #</th><th>Customer</th><th>Method</th><th>Amount</th><th>Fee</th><th>Received By</th></tr></thead>
    <tbody>
    <?php foreach ($payments as $i => $p): ?>
    <tr>
        <td><?= $i + 1 ?></td>
        <td><?= date('d M Y, h:i A', strtotime($p['paid_at'])) ?></td>
        <td><a href="<?= Router::url('orders/show?id=' . $p['order_id']) ?>"><strong><?= e($p['order_number']) ?></strong></a></td>
        <td><?= e($p['customer_name'] ?? 'Walk-in') ?><?= $p['customer_phone'] ? ' · ' . e($p['customer_phone']) : '' ?></td>
        <td><span class="badge badge-blue"><?= e(str_replace('_', ' ', $p['method_name'])) ?></span></td>
        <td><?= formatMoney((float) $p['amount']) ?></td>
        <td><?= (float) $p['fee_amount'] > 0 ? formatMoney((float) $p['fee_amount']) : '—' ?></td>
        <td><?= e($p['received_by_name'] ?? 'Online') ?></td>
    </tr>
    <?php endforeach; ?>
    <?php if (empty($payments)): ?>
    <tr><td colspan="8" style="text-align:center;color:var(--color-text-muted);padding:30px;">No payments found.</td></tr>
    <?php endif; ?>
    </tbody>
    </table>
    </div>
</div>

<div class="rms-modal-overlay" id="rmsMethodsModal">
    <div class="rms-modal" style="max-width:520px;">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-gear" style="color:var(--color-teal);margin-right:6px;"></i>Payment Methods</h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsMethodsModal')"><i class="fa-solid fa-xmark"></i></button>
        </div>

        <div style="max-height:40vh;overflow-y:auto;margin-bottom:16px;">
        <?php foreach ($methods as $m): ?>
        <div style="display:flex;align-items:center;justify-content:space-between;padding:10px 0;border-bottom:1px solid var(--color-border);font-size:12.5px;">
            <div>
                <strong><?= e(str_replace('_', ' ', $m['method_name'])) ?></strong>
                <div style="color:var(--color-text-muted);font-size:11.5px;">
                    <?= $m['account_name'] ? e($m['account_name']) : 'No account linked' ?>
                    <?= $m['fee_percentage'] > 0 ? ' · ' . $m['fee_percentage'] . '% fee' : '' ?>
                </div>
            </div>
            <div style="display:flex;gap:4px;">
                <?php if (Auth::can('payments', 'edit')): ?>
                <button type="button" class="icon-btn icon-btn-gray" onclick="rmsOpenModal('rmsEditMethod<?= $m['id'] ?>')"><i class="fa-solid fa-pen"></i></button>
                <form method="POST" action="<?= Router::url('payments/methods/toggle') ?>">
                    <?= $csrf ?>
                    <input type="hidden" name="id" value="<?= $m['id'] ?>">
                    <button type="submit" class="icon-btn <?= $m['is_active'] ? 'icon-btn-red' : 'icon-btn-blue' ?>"><i class="fa-solid <?= $m['is_active'] ? 'fa-ban' : 'fa-check' ?>"></i></button>
                </form>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
        </div>

        <?php if (Auth::can('payments', 'add')): ?>
        <form method="POST" action="<?= Router::url('payments/methods/store') ?>">
            <?= $csrf ?>
            <label style="font-size:12.5px;font-weight:700;display:block;margin-bottom:8px;">Add New Method</label>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:8px;">
                <input type="text" name="method_name" class="form-control" placeholder="e.g. Koko, Frimi" required>
                <select name="finance_account_id" class="form-control">
                    <option value="">— No account —</option>
                    <?php foreach ($financeAccounts as $fa): ?>
                    <option value="<?= $fa['id'] ?>"><?= e($fa['account_name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div style="display:grid;grid-template-columns:1fr auto;gap:8px;">
                <input type="number" step="0.01" name="fee_percentage" class="form-control" placeholder="Fee % (0 if none)">
                <button type="submit" class="btn btn-primary"><i class="fa-solid fa-plus"></i></button>
            </div>
        </form>
        <?php endif; ?>
    </div>
</div>

<?php foreach ($methods as $m): if (!Auth::can('payments', 'edit')) continue; ?>
<div class="rms-modal-overlay" id="rmsEditMethod<?= $m['id'] ?>">
    <div class="rms-modal" style="max-width:380px;">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-pen" style="color:var(--color-teal);margin-right:6px;"></i>Edit <?= e(str_replace('_', ' ', $m['method_name'])) ?></h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsEditMethod<?= $m['id'] ?>')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST" action="<?= Router::url('payments/methods/update') ?>">
            <?= $csrf ?>
            <input type="hidden" name="id" value="<?= $m['id'] ?>">
            <div class="form-group">
                <label>Linked Finance Account</label>
                <select name="finance_account_id" class="form-control">
                    <option value="">— No account —</option>
                    <?php foreach ($financeAccounts as $fa): ?>
                    <option value="<?= $fa['id'] ?>" <?= $m['finance_account_id'] == $fa['id'] ? 'selected' : '' ?>><?= e($fa['account_name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label>Fee Percentage (%)</label>
                <input type="number" step="0.01" name="fee_percentage" class="form-control" value="<?= e((string)$m['fee_percentage']) ?>">
            </div>
            <button type="submit" class="btn btn-primary" style="width:100%;"><i class="fa-solid fa-floppy-disk"></i> Save</button>
        </form>
    </div>
</div>
<?php endforeach; ?>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.min.js"></script>
<script>
new Chart(document.getElementById('rmsPaymentTrendChart'), {
    type: 'bar',
    data: {
        labels: <?= json_encode($trend['labels']) ?>,
        datasets: [{
            label: 'Collections',
            data: <?= json_encode($trend['data']) ?>,
            backgroundColor: '#1D7A8C',
            borderRadius: 6,
        }]
    },
    options: {
        responsive: true,
        plugins: { legend: { display: false } },
        scales: { y: { beginAtZero: true, ticks: { callback: v => 'Rs.' + v } }, x: { grid: { display: false } } }
    }
});
</script>
