<%- include('partials/header', { title, user }) %>
<%
const stats = walletStats || { monthlyPayouts: 0, totalDisbursed: totals.disbursed };
const filters = walletFilters || { q: '', type: '', dept: '', date: '' };
const page = walletPagination || { page: 1, totalPages: 1, total: ledger?.length || 0 };
const filtered = Boolean(filters.q || filters.type || filters.dept || filters.date);
const monthName = new Date().toLocaleDateString('en-GB', { month: 'long' });
const ledgerTone = (entry) => entry.type.startsWith('Credit') ? 'credit' : entry.type.startsWith('Debit') ? 'debit' : entry.type === 'Failed' ? 'failed' : entry.type === 'Pending' ? 'pending' : 'settled';
const ledgerIcon = (entry) => entry.category === 'Treasury top-up' ? '&#8595;' : entry.category === 'Disbursement' ? '&#8593;' : '&#8634;';
%>
<%# The banner shares the logistics dashboard's hero styles. %>
<section class="logi-hero wallet-hero">
	<div class="logi-hero-top">
		<div>
			<p class="logi-hero-kicker">Finance control · Petty cash</p>
			<h1>Treasury &amp; wallet</h1>
			<p class="logi-hero-sub">As at <%= fmtDay(new Date()) %></p>
		</div>
		<div class="logi-hero-actions">
			<% if (canManage && !balanceSyncOff) { %><form method="post" action="/wallet/balance/refresh"><button class="logi-hero-button primary" type="submit">Refresh balance</button></form><% } %>
			<% if (canManage && canOperate) { %><a class="logi-hero-button" href="/dashboard#payout-queue">Payout queue</a><% } %>
			<% if (canManage && canOperate) { %><a class="logi-hero-button" href="/wallet/export">Export CSV</a><% } %>
		</div>
	</div>
	<div class="logi-hero-stats wallet-hero-stats">
		<div class="logi-stat wallet-balance-stat">
			<small>Available to disburse</small>
			<strong>KES <%= money(walletDoc.total_balance) %></strong>
			<% if (balanceSyncOff) { %>
			<em>Set manually · readings from Safaricom are switched off</em>
			<% } else if (b2cBalance?.checked_at) { %>
			<em>Safaricom B2C balance KES <%= money(b2cBalance.utility) %><% if (b2cBalance.awaiting_confirmation) { %>, less KES <%= money(b2cBalance.awaiting_confirmation) %> awaiting confirmation<% } %> · read <%= fmtDate(b2cBalance.checked_at) %></em>
			<% } else { %>
			<em>Not yet read from Safaricom</em>
			<% } %>
			<% if (canManage && !balanceSyncOff && b2cBalance?.last_error) { %><em class="wallet-balance-error">Last reading failed: <%= b2cBalance.last_error %></em><% } %>
		</div>
		<div class="logi-stat">
			<small>Disbursed to staff</small>
			<strong>KES <%= money(stats.totalDisbursed) %></strong>
			<em>All-time petty cash payouts</em>
		</div>
		<div class="logi-stat">
			<small>Paid out in <%= monthName %></small>
			<strong>KES <%= money(stats.monthlyPayouts) %></strong>
			<em>Petty cash sent to staff this month</em>
		</div>
	</div>
</section>


<section class="logi-panel wallet-section wallet-ledger-panel" id="ledger">
	<div class="logi-panel-head">
		
		<div><h2>Transaction ledger</h2><p>Every payout, top-up and expense clearance, latest first.</p></div>
		<span class="logi-count blue"><%= page.total %> <%= page.total === 1 ? 'transaction' : 'transactions' %></span>
	</div>
	<form class="wallet-filter-bar" method="get" action="/wallet#ledger">
		<label class="wallet-search"><span>Search</span><input type="search" name="q" value="<%= filters.q %>" placeholder="Transaction ID, name or purpose…"></label>
		<label><span>Type</span><select name="type"><option value="">All types</option><option value="disbursement" <%= filters.type === 'disbursement' ? 'selected' : '' %>>Disbursement</option><option value="topup" <%= filters.type === 'topup' ? 'selected' : '' %>>Treasury top-up</option><option value="expense" <%= filters.type === 'expense' ? 'selected' : '' %>>Expense clear</option></select></label>
		<label><span>Department</span><select name="dept"><option value="">All departments</option><% (walletDepartments || []).forEach((department) => { %><option value="<%= department %>" <%= filters.dept === department ? 'selected' : '' %>><%= department %></option><% }) %></select></label>
		<label><span>Date</span><select name="date"><option value="">All time</option><option value="month" <%= filters.date === 'month' ? 'selected' : '' %>>This month</option><option value="7" <%= filters.date === '7' ? 'selected' : '' %>>Last 7 days</option><option value="30" <%= filters.date === '30' ? 'selected' : '' %>>Last 30 days</option></select></label>
		<div class="wallet-filter-actions"><button class="button small primary" type="submit">Apply</button><% if (filtered) { %><a class="button small outline" href="/wallet#ledger">Clear</a><% } %></div>
	</form>
	<% if (!ledger?.length) { %>
	<div class="logi-empty"><strong><%= filtered ? 'No matches' : 'No transactions yet' %></strong><p>No wallet transactions match these filters.</p></div>
	<% } else { %>
	<div class="table-wrap"><table class="wallet-ledger">
		<thead><tr><th>Transaction</th><th>Details &amp; recipient</th><th>Type</th><th class="num">Amount (KES)</th><th>Receipt</th></tr></thead>
		<tbody>
		<% ledger.forEach((entry) => { const tone = ledgerTone(entry); %>
			<tr>
				<td><div class="wallet-txn"><span class="wallet-txn-icon <%= tone %>" aria-hidden="true"><%- ledgerIcon(entry) %></span><div><strong>#<%= entry.id %></strong><small><%= entry.category %> · <%= fmtDay(entry.date) %></small></div></div></td>
				<td><strong><%= entry.details %></strong><small><%= entry.subtitle || 'No additional notes' %></small></td>
				<td><span class="ledger-type <%= tone %>"><%= entry.type %></span></td>
				<td class="num amount <%= tone === 'failed' ? 'debit' : tone %>"><%= tone === 'credit' ? '+' : tone === 'debit' ? '−' : '' %><%= money(entry.amount) %></td>
				<td><span class="receipt-state <%= ['Pending', 'Processing'].includes(entry.receipt) ? 'waiting' : entry.receipt === 'Failed' ? 'failed' : '' %>"><%= entry.receipt %></span></td>
			</tr>
		<% }) %>
		</tbody>
	</table></div>
	<% } %>
	<div class="wallet-pagination">
		<span>Showing <%= page.total ? ((page.page - 1) * 10) + 1 : 0 %>–<%= Math.min(page.page * 10, page.total) %> of <%= page.total %></span>
		<div>
			<% if (page.page > 1) { %><a href="/wallet?<%= new URLSearchParams({ ...filters, page: page.page - 1 }).toString() %>#ledger">&larr; Previous</a><% } %>
			<strong><%= page.page %> / <%= page.totalPages %></strong>
			<% if (page.page < page.totalPages) { %><a href="/wallet?<%= new URLSearchParams({ ...filters, page: page.page + 1 }).toString() %>#ledger">Next &rarr;</a><% } %>
		</div>
	</div>
</section>
<%- include('partials/footer') %>
