<%- include('partials/header', { title, user }) %>
<%
const firstName = user.full_name.split(' ')[0];
const treasuryBalance = Number(locals.treasuryBalance || 0);
const recentPayouts = locals.recentPayouts || [];
const lowStockProducts = locals.lowStockProducts || [];
const shortfall = pettyCash.length > 0 && pettyCashTotal > treasuryBalance;
const toIssue = requisitions.filter((request) => request.status === 'computed').length;
const avatarTone = (name) => ['green', 'blue', 'amber', 'navy'][String(name || '').length % 4];
%>
<section class="logi-hero">
	<div class="logi-hero-top">
		<div>
			<p class="logi-hero-kicker">Logistics · Treasury &amp; stores</p>
			<h1><%= locals.greeting || 'Welcome back' %>, <%= firstName %></h1>
			<p class="logi-hero-sub"><%= locals.todayLabel || '' %></p>
		</div>
		<div class="logi-hero-actions">
			<a class="logi-hero-button primary" href="/wallet">Treasury balance</a>
			<a class="logi-hero-button" href="/admin/stock">Master database</a>
		</div>
	</div>
	<div class="logi-hero-stats">
		<a class="logi-stat" href="/wallet">
			<small>Treasury balance</small>
			<strong>KES <%= money(treasuryBalance) %></strong>
			<em class="<%= shortfall ? 'is-warning' : '' %>"><%= shortfall ? `KES ${money(pettyCashTotal - treasuryBalance)} short of the payout queue` : 'Available for M-Pesa payouts' %></em>
		</a>
		<a class="logi-stat" href="#payout-queue">
			<small>Awaiting payout</small>
			<strong><%= pettyCash.length %> <span><%= pettyCash.length === 1 ? 'request' : 'requests' %></span></strong>
			<em>KES <%= money(pettyCashTotal) %> approved for payment</em>
		</a>
		<a class="logi-stat" href="#requisition-queue">
			<small>Hardware requisitions</small>
			<strong><%= requisitions.length %> <span>open</span></strong>
			<em><%= toIssue %> ready to issue · <%= requisitionUnits %> units requested</em>
		</a>
		<a class="logi-stat" href="/admin/stock">
			<small>Units in store</small>
			<strong><%= Number(locals.stockInStore || 0).toLocaleString() %></strong>
			<em>Across <%= locals.stockProductCount || 0 %> products<%= lowStockProducts.length ? ` · ${lowStockProducts.length} running low` : '' %></em>
		</a>
	</div>
</section>
<% if (shortfall) { %>
<div class="logi-alert" role="status"><div><strong>The treasury cannot cover every approved payout.</strong><p>KES <%= money(treasuryBalance) %> is available against KES <%= money(pettyCashTotal) %> awaiting payout. Load the B2C account in the M-Pesa organisation portal, then refresh the balance on the Wallet page.</p></div><a class="button small" href="/wallet">Open wallet</a></div>
<% } %>
<%- include('partials/cover-requests') %>
<div class="logi-layout">
	<div class="logi-main">
		<section class="logi-panel" id="payout-queue">
			<div class="logi-panel-head">
				
				<div><h2>Petty cash payouts</h2><p>Approved requests waiting to be sent to staff via M-Pesa.</p></div>
				<span class="logi-count"><%= pettyCash.length %> waiting</span>
			</div>
			<% if (!pettyCash.length) { %>
			<div class="logi-empty"><strong>All caught up</strong><p>No approved petty cash requests are waiting for disbursement.</p></div>
			<% } %>
			<ul class="logi-list">
			<% pettyCash.forEach((request) => { const owner = ownerMap[request.user_id]; const reminders = request.payout_reminders || []; const state = request.canCheckPayoutStatus ? 'check' : ['initiating', 'processing', 'checking_status', 'status_checking'].includes(request.payoutStatus) ? 'processing' : request.payoutStatus === 'unknown' ? 'unknown' : request.payoutStatus === 'failed' ? 'failed' : 'ready'; %>
				<li class="logi-payout is-<%= state %>">
					<span class="logi-avatar <%= avatarTone(owner?.full_name) %>" aria-hidden="true"><%= initials(owner?.full_name || '?') %></span>
					<div class="logi-item-main">
						<div class="logi-item-title"><strong><%= owner?.full_name || 'Unknown' %></strong><% if (reminders.length) { %><span class="reminder-chip" title="Last reminder <%= fmtDate(reminders[reminders.length - 1].at) %>">Reminded <%= reminders.length %>&times;</span><% } %></div>
						<p><%= request.details?.description_of_need || 'Petty cash request' %></p>
						<small><a href="/requests/<%= request.id %>">#PC-<%= String(request.id).padStart(3, '0') %></a> · <%= owner?.department || 'No department' %> · Submitted <%= fmtDay(request.submitted_at) %></small>
					</div>
					<div class="logi-amount"><small>KES</small><strong><%= money(request.details?.amount_approved || request.details?.amount_requested) %></strong></div>
					<div class="logi-item-action">
						<% if (state === 'check') { %>
						<form method="post" action="/wallet/disburse/<%= request.payoutTransactionId %>/reconcile"><button class="button small outline" type="submit">Check M-Pesa status</button></form>
						<% } else if (state === 'processing') { %>
						<span class="logi-state processing">Awaiting Safaricom confirmation</span>
						<% } else if (state === 'unknown') { %>
						<span class="logi-state processing"><%= request.hasProviderReference ? 'Status unclear; check again shortly' : 'No provider reference; contact Safaricom before retrying' %></span>
						<% } else { %>
						<% if (state === 'failed') { %><small class="logi-state failed">Last attempt failed. Verify the number before retrying.</small><% } %>
						<form method="post" action="/wallet/disburse" class="mpesa-payout-form"><input type="hidden" name="request_id" value="<%= request.id %>"><label><span>M-Pesa number</span><input class="mpesa-recipient-input" type="tel" name="mpesa_phone" value="<%= request.mpesaPhone %>" inputmode="tel" autocomplete="tel" placeholder="0712345678" required></label><button class="button small success" type="submit"><%= state === 'failed' ? 'Retry payout' : 'Send via M-Pesa' %></button></form>
						<% } %>
					</div>
				</li>
			<% }) %>
			</ul>
		</section>

		<section class="logi-panel" id="requisition-queue">
			<div class="logi-panel-head">
				
				<div><h2>Hardware &amp; telematics requisitions</h2><p>Check stock, allocate units and issue the hardware.</p></div>
				<a class="logi-panel-link" href="/requests?type=requisition">All requisitions &rarr;</a>
			</div>
			<% if (!requisitions.length) { %>
			<div class="logi-empty"><strong>No open requisitions</strong><p>No stock requisitions are awaiting approval.</p></div>
			<% } %>
			<ul class="logi-list">
			<% requisitions.forEach((request) => { const owner = ownerMap[request.user_id]; const stockChecks = request.stockChecks || []; const matched = stockChecks.length && stockChecks.every((line) => line.matches.length); const allAvailable = matched && stockChecks.every((line) => line.available >= line.quantity); %>
				<li class="logi-requisition">
					<span class="logi-avatar <%= avatarTone(owner?.full_name) %>" aria-hidden="true"><%= initials(owner?.full_name || '?') %></span>
					<div class="logi-item-main">
						<div class="logi-item-title"><strong><%= request.details?.item_requested || 'Hardware requisition' %></strong><span class="logi-stage <%= request.status === 'computed' ? 'ready' : '' %>"><%= request.status === 'computed' ? (() => { const lines = request.details?.items || []; const issued = lines.reduce((sum, line) => sum + (line.issued_serial_numbers || []).length, 0); const total = lines.reduce((sum, line) => sum + Number(line.quantity || 0), 0); return issued ? `Partly issued · ${issued} of ${total}` : 'Ready to issue'; })() : 'Awaiting approval' %></span></div>
						<p><%= stockChecks.map((line) => `${line.stockType} × ${line.quantity}`).join(' · ') || `${Number(request.details?.quantity || 0)} units` %></p>
						<small><a href="/requests/<%= request.id %>">#RQ-<%= String(request.id).padStart(3, '0') %></a> · <%= owner?.full_name || 'Unknown' %> · <%= owner?.department || 'No department' %></small>
					</div>
					<div class="logi-stock">
						<% if (matched) { %>
						<span class="logi-stock-pill <%= allAvailable ? 'ok' : 'low' %>"><%= allAvailable ? 'In stock' : 'Short stock' %></span>
						<small><%= stockChecks.map((line) => `${line.available} available / ${line.quantity} needed`).join(', ') %></small>
						<% } else { %>
						<span class="logi-stock-pill low">No catalogue match</span>
						<% } %>
					</div>
					<div class="logi-item-action"><button class="button small <%= request.status === 'computed' ? 'primary' : 'outline' %>" type="button" data-queue-review="<%= request.id %>"><%= request.status === 'computed' ? 'Review & issue' : 'Review' %></button></div>
				</li>
			<% }) %>
			</ul>
		</section>
	</div>

	<aside class="logi-side">
		<section class="logi-panel compact">
			<div class="logi-panel-head"><div><h2>Stock watch</h2><p>Products with 10 or fewer units in store.</p></div></div>
			<% if (!lowStockProducts.length) { %>
			<p class="logi-side-empty">Every product is well stocked.</p>
			<% } %>
			<ul class="logi-stock-watch">
			<% lowStockProducts.forEach((product) => { %>
				<li><a href="/admin/stock?product=<%= encodeURIComponent(product._id) %>#records"><span><%= product.name %></span><b class="<%= product.available === 0 ? 'out' : 'low' %>"><%= product.available === 0 ? 'Out' : product.available %></b></a><span class="logi-meter" aria-hidden="true"><span class="<%= product.available === 0 ? 'out' : 'low' %>" style="width: <%= Math.max(4, Math.min(100, product.available * 10)) %>%"></span></span></li>
			<% }) %>
			</ul>
			<a class="logi-panel-link" href="/admin/stock">Open master database &rarr;</a>
		</section>

		<section class="logi-panel compact">
			<div class="logi-panel-head"><div><h2>Recent payouts</h2><p>Latest confirmed M-Pesa disbursements.</p></div></div>
			<% if (!recentPayouts.length) { %>
			<p class="logi-side-empty">No payouts have been sent yet.</p>
			<% } %>
			<ul class="logi-recent">
			<% recentPayouts.forEach((payout) => { const owner = ownerMap[payout.user_id]; %>
				<li><span class="logi-recent-dot" aria-hidden="true"></span><div><strong><%= owner?.full_name || 'Staff member' %></strong><small><%= payout.mpesa_ref || 'M-Pesa' %> · <%= fmtDay(payout.completed_at || payout.created_at) %></small></div><b>KES <%= money(payout.amount) %></b></li>
			<% }) %>
			</ul>
			<a class="logi-panel-link" href="/wallet">View the ledger &rarr;</a>
		</section>

		<nav class="logi-panel compact logi-shortcuts" aria-label="Shortcuts">
			<h2>Shortcuts</h2>
			<a href="/wallet?type=disbursement#ledger">Payout history</a>
			<a href="/requests?type=requisition">Requisition history</a>
			<a href="/wallet/export">Export ledger (CSV)</a>
		</nav>
	</aside>
</div>
<%- include('partials/requisition-review-modal') %>
<%- include('partials/footer') %>