<div class="stock-header" style="background: linear-gradient(120deg, #4B6B3A 0%, #2E4322 100%);">
    <div class="sth-icon"><i class="fa-solid fa-building-columns"></i></div>
    <div class="sth-text">
        <h2>Finance Overview</h2>
        <div class="sth-sub">
            Cash &amp; Bank: <?= formatMoney($totalBalance) ?> · Net P&amp;L (This Month): <?= formatMoney($netPnl) ?>
        </div>
    </div>
</div>

<?php if (!empty($alerts)): ?>
<div class="alert-chips">
    <?php foreach ($alerts as $a): ?>
    <span class="alert-chip ac-<?= $a['color'] ?>"><i class="fa-solid <?= $a['icon'] ?>"></i> <?= e($a['text']) ?></span>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<div class="stat-mini-grid">
    <div class="stat-mini sm-blue"><div class="sm-value"><?= formatMoney($totalBalance) ?></div><div class="sm-label">Total Cash &amp; Bank</div></div>
    <div class="stat-mini sm-green">
        <div class="sm-value"><?= formatMoney($monthIncome) ?></div>
        <div class="sm-label">Income (Month)<?php if ($incomeChange !== null): ?> · <i class="fa-solid <?= $incomeChange >= 0 ? 'fa-arrow-up' : 'fa-arrow-down' ?>"></i> <?= abs($incomeChange) ?>%<?php endif; ?></div>
    </div>
    <div class="stat-mini sm-gold">
        <div class="sm-value"><?= formatMoney($monthExpense) ?></div>
        <div class="sm-label">Expenses (Month)<?php if ($expenseChange !== null): ?> · <i class="fa-solid <?= $expenseChange >= 0 ? 'fa-arrow-up' : 'fa-arrow-down' ?>"></i> <?= abs($expenseChange) ?>%<?php endif; ?></div>
    </div>
    <div class="stat-mini <?= $netPnl >= 0 ? 'sm-green' : 'sm-red' ?>"><div class="sm-value"><?= formatMoney($netPnl) ?></div><div class="sm-label">Net P&amp;L (Month)</div></div>
</div>

<div class="panel">
    <div class="panel-head">
        <h3><i class="fa-solid fa-chart-line" style="color:var(--color-teal);margin-right:6px;"></i>Cash Flow — Last 7 Days</h3>
    </div>
    <canvas id="rmsCashFlowChart" height="80"></canvas>
</div>

<div class="panel">
    <div class="panel-head">
        <h3><i class="fa-solid fa-building-columns" style="color:var(--color-teal);margin-right:6px;"></i>Accounts</h3>
        <div style="display:flex;gap:8px;">
            <?php if (Auth::can('finance', 'add')): ?>
            <button type="button" class="btn btn-secondary" onclick="rmsOpenModal('rmsManualEntryModal')" style="font-size:12px;padding:7px 14px;"><i class="fa-solid fa-plus-minus"></i> Manual Entry</button>
            <button type="button" class="btn btn-secondary" onclick="rmsOpenModal('rmsAddAccountModal')" style="font-size:12px;padding:7px 14px;"><i class="fa-solid fa-plus"></i> Add Account</button>
            <?php endif; ?>
        </div>
    </div>
    <div class="snapshot-grid">
        <?php foreach ($accounts as $a): ?>
        <div class="snapshot-card <?= $a['account_type'] === 'CASH' ? 'sc-gold' : 'sc-blue' ?>">
            <div class="s-label"><?= e($a['account_name']) ?></div>
            <div class="s-value"><?= formatMoney((float) $a['current_balance']) ?></div>
            <div class="s-sub"><?= e($a['account_type']) ?><?= !$a['is_active'] ? ' · Inactive' : '' ?></div>
        </div>
        <?php endforeach; ?>
        <?php if (empty($accounts)): ?>
        <div style="color:var(--color-text-muted);font-size:13px;">No active accounts.</div>
        <?php endif; ?>
    </div>
</div>

<div style="display:flex;gap:6px;margin-bottom:16px;">
    <button type="button" class="btn btn-primary rms-tab-btn active" data-tab="ledger" onclick="rmsSwitchTab('ledger', this)"><i class="fa-solid fa-list"></i> Transactions Ledger</button>
    <button type="button" class="btn btn-secondary rms-tab-btn" data-tab="expenses" onclick="rmsSwitchTab('expenses', this)"><i class="fa-solid fa-receipt"></i> Expenses</button>
</div>

<div id="rms-tab-ledger" class="rms-tab-panel">
    <form method="GET" action="<?= Router::url('finance') ?>" style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:14px;">
        <select name="account" class="form-control" style="width:auto;">
            <option value="ALL">All Accounts</option>
            <?php foreach ($accounts as $a): ?>
            <option value="<?= $a['id'] ?>" <?= (string)$activeAccount === (string)$a['id'] ? 'selected' : '' ?>><?= e($a['account_name']) ?></option>
            <?php endforeach; ?>
        </select>
        <select name="category" class="form-control" style="width:auto;">
            <?php foreach (['ALL' => 'All Categories', 'SALES' => 'Sales', 'EXPENSE' => 'Expense', 'PAYROLL' => 'Payroll', 'REFUND' => 'Refund', 'PURCHASE' => 'Purchase', 'MANUAL' => 'Manual'] as $k => $l): ?>
            <option value="<?= $k ?>" <?= $activeCategory === $k ? 'selected' : '' ?>><?= $l ?></option>
            <?php endforeach; ?>
        </select>
        <input type="date" name="date_from" class="form-control" value="<?= e($dateFrom) ?>">
        <input type="date" name="date_to" class="form-control" value="<?= e($dateTo) ?>">
        <button type="submit" class="btn btn-secondary"><i class="fa-solid fa-filter"></i> Filter</button>
    </form>

    <div class="dark-table-panel">
        <div class="dtp-head"><span><i class="fa-solid fa-table-list"></i> Transactions Ledger</span><span class="dtp-count"><?= count($transactions) ?> records</span></div>
        <div style="overflow-x:auto;">
    <table class="data-table">
    <thead><tr><th>#</th><th>Date</th><th>Account</th><th>Type</th><th>Category</th><th>Description</th><th>Amount</th></tr></thead>
    <tbody>
    <?php foreach ($transactions as $i => $t): ?>
    <tr>
        <td><?= $i + 1 ?></td>
        <td><?= date('d M Y, h:i A', strtotime($t['created_at'])) ?></td>
        <td><?= e($t['account_name']) ?></td>
        <td><?= $t['transaction_type'] === 'CREDIT' ? '<span class="badge badge-green"><i class="fa-solid fa-arrow-down"></i> Credit</span>' : '<span class="badge badge-red"><i class="fa-solid fa-arrow-up"></i> Debit</span>' ?></td>
        <td><span class="badge badge-gray"><?= e($t['category']) ?></span></td>
        <td><?= e($t['description'] ?? '—') ?></td>
        <td style="color:<?= $t['transaction_type'] === 'CREDIT' ? 'var(--color-success)' : 'var(--color-danger)' ?>;font-weight:700;">
            <?= $t['transaction_type'] === 'CREDIT' ? '+' : '-' ?><?= formatMoney((float) $t['amount']) ?>
        </td>
    </tr>
    <?php endforeach; ?>
    <?php if (empty($transactions)): ?>
    <tr><td colspan="7" style="text-align:center;color:var(--color-text-muted);padding:30px;">No transactions found.</td></tr>
    <?php endif; ?>
    </tbody>
    </table>
    </div>
</div>
</div>

<div id="rms-tab-expenses" class="rms-tab-panel" style="display:none;">
    <div style="display:flex;justify-content:flex-end;margin-bottom:14px;">
        <?php if (Auth::can('expenses', 'add')): ?>
        <button type="button" class="btn btn-primary" onclick="rmsOpenModal('rmsAddExpenseModal')"><i class="fa-solid fa-plus"></i> Add Expense</button>
        <?php endif; ?>
    </div>
    <div class="dark-table-panel">
        <div class="dtp-head"><span><i class="fa-solid fa-receipt"></i> Expenses</span><span class="dtp-count"><?= count($expenses) ?> records</span></div>
        <div style="overflow-x:auto;">
    <table class="data-table">
    <thead><tr><th>#</th><th>Date</th><th>Category</th><th>Amount</th><th>Account</th><th>Notes</th><th>Added By</th><th></th></tr></thead>
    <tbody>
    <?php foreach ($expenses as $i => $ex): ?>
    <tr>
        <td><?= $i + 1 ?></td>
        <td><?= date('d M Y', strtotime($ex['expense_date'])) ?></td>
        <td><span class="badge badge-gold"><?= e($ex['expense_category']) ?></span></td>
        <td><?= formatMoney((float) $ex['amount']) ?></td>
        <td><?= e($ex['account_name']) ?></td>
        <td><?= e($ex['notes'] ?? '—') ?></td>
        <td><?= e($ex['created_by_name'] ?? 'System') ?></td>
        <td>
            <?php if (Auth::can('expenses', 'delete')): ?>
            <form method="POST" action="<?= Router::url('finance/expenses/delete') ?>" onsubmit="return confirm('Delete this expense? The account balance will be refunded.');">
                <?= $csrf ?>
                <input type="hidden" name="id" value="<?= $ex['id'] ?>">
                <button type="submit" class="icon-btn icon-btn-red"><i class="fa-solid fa-trash"></i></button>
            </form>
            <?php endif; ?>
        </td>
    </tr>
    <?php endforeach; ?>
    <?php if (empty($expenses)): ?>
    <tr><td colspan="8" style="text-align:center;color:var(--color-text-muted);padding:30px;">No expenses logged yet.</td></tr>
    <?php endif; ?>
    </tbody>
    </table>
    </div>
</div>
</div>

<!-- Add Account Modal -->
<?php if (Auth::can('finance', 'add')): ?>
<div class="rms-modal-overlay" id="rmsAddAccountModal">
    <div class="rms-modal" style="max-width:380px;">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-building-columns" style="color:var(--color-teal);margin-right:6px;"></i>Add Account</h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsAddAccountModal')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST" action="<?= Router::url('finance/accounts/store') ?>">
            <?= $csrf ?>
            <div class="form-group"><label>Account Name</label><input type="text" name="account_name" class="form-control" placeholder="e.g. Petty Cash" required></div>
            <div class="form-group">
                <label>Type</label>
                <select name="account_type" class="form-control">
                    <option value="CASH">Cash</option>
                    <option value="BANK">Bank</option>
                    <option value="OTHER">Other</option>
                </select>
            </div>
            <div class="form-group"><label>Opening Balance</label><input type="number" step="0.01" name="opening_balance" class="form-control" value="0"></div>
            <button type="submit" class="btn btn-primary" style="width:100%;"><i class="fa-solid fa-plus"></i> Add Account</button>
        </form>
    </div>
</div>

<!-- Manual Entry Modal -->
<div class="rms-modal-overlay" id="rmsManualEntryModal">
    <div class="rms-modal" style="max-width:380px;">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-plus-minus" style="color:var(--color-teal);margin-right:6px;"></i>Manual Entry</h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsManualEntryModal')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST" action="<?= Router::url('finance/manual-entry') ?>">
            <?= $csrf ?>
            <div class="form-group">
                <label>Account</label>
                <select name="finance_account_id" class="form-control" required>
                    <?php foreach ($accounts as $a): ?>
                    <option value="<?= $a['id'] ?>"><?= e($a['account_name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label>Direction</label>
                <div style="display:flex;gap:8px;">
                    <label style="flex:1;display:flex;align-items:center;gap:6px;font-size:12.5px;font-weight:600;border:1px solid var(--color-border);border-radius:8px;padding:8px;">
                        <input type="radio" name="type" value="CREDIT" checked> Money In
                    </label>
                    <label style="flex:1;display:flex;align-items:center;gap:6px;font-size:12.5px;font-weight:600;border:1px solid var(--color-border);border-radius:8px;padding:8px;">
                        <input type="radio" name="type" value="DEBIT"> Money Out
                    </label>
                </div>
            </div>
            <div class="form-group"><label>Amount</label><input type="number" step="0.01" name="amount" class="form-control" required></div>
            <div class="form-group"><label>Description</label><input type="text" name="description" class="form-control" placeholder="e.g. Owner cash injection"></div>
            <input type="hidden" name="category" value="MISC">
            <button type="submit" class="btn btn-primary" style="width:100%;"><i class="fa-solid fa-check"></i> Save Entry</button>
        </form>
    </div>
</div>
<?php endif; ?>

<!-- Add Expense Modal -->
<?php if (Auth::can('expenses', 'add')): ?>
<div class="rms-modal-overlay" id="rmsAddExpenseModal">
    <div class="rms-modal" style="max-width:380px;">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-receipt" style="color:var(--color-teal);margin-right:6px;"></i>Add Expense</h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsAddExpenseModal')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST" action="<?= Router::url('finance/expenses/store') ?>">
            <?= $csrf ?>
            <div class="form-group">
                <label>Category</label>
                <input type="text" name="expense_category" class="form-control" placeholder="e.g. Electricity, Gas, Rent, Transport" required>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                <div class="form-group"><label>Amount</label><input type="number" step="0.01" name="amount" class="form-control" required></div>
                <div class="form-group"><label>Date</label><input type="date" name="expense_date" class="form-control" value="<?= date('Y-m-d') ?>" required></div>
            </div>
            <div class="form-group">
                <label>Pay From</label>
                <select name="finance_account_id" class="form-control" required>
                    <?php foreach ($accounts as $a): ?>
                    <option value="<?= $a['id'] ?>"><?= e($a['account_name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group"><label>Notes</label><input type="text" name="notes" class="form-control"></div>
            <button type="submit" class="btn btn-primary" style="width:100%;"><i class="fa-solid fa-plus"></i> Add Expense</button>
        </form>
    </div>
</div>
<?php endif; ?>

<script>
function rmsSwitchTab(tab, btn) {
    document.querySelectorAll('.rms-tab-panel').forEach(p => p.style.display = 'none');
    document.getElementById('rms-tab-' + tab).style.display = 'block';
    document.querySelectorAll('.rms-tab-btn').forEach(b => { b.classList.remove('btn-primary'); b.classList.add('btn-secondary'); });
    btn.classList.remove('btn-secondary'); btn.classList.add('btn-primary');
}
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.min.js"></script>
<script>
new Chart(document.getElementById('rmsCashFlowChart'), {
    type: 'bar',
    data: {
        labels: <?= json_encode($trend['labels']) ?>,
        datasets: [
            { label: 'Income', data: <?= json_encode($trend['income']) ?>, backgroundColor: '#4B6B3A', borderRadius: 6 },
            { label: 'Expense', data: <?= json_encode($trend['expense']) ?>, backgroundColor: '#B23A3A', borderRadius: 6 }
        ]
    },
    options: {
        responsive: true,
        plugins: { legend: { position: 'bottom', labels: { boxWidth: 10, font: { size: 11 } } } },
        scales: { y: { beginAtZero: true, ticks: { callback: v => 'Rs.' + v } }, x: { grid: { display: false } } }
    }
});
</script>
