<?php
declare(strict_types=1);
require __DIR__ . '/app/bootstrap.php';
require_auth();
require_current_schema();
require_permission('payments.record');
require __DIR__ . '/app/layout.php';
require __DIR__ . '/app/actions.php';
handle_actions();

$query = trim((string)($_GET['q'] ?? ''));
$invoiceId = (int)($_GET['invoice_id'] ?? 0);
$params = [];
$where = ['d.type="invoice"', 'd.status NOT IN ("cancelled","draft")'];
if ($query !== '') {
    $needle = '%' . $query . '%';
    $where[] = '(d.number LIKE ? OR c.name LIKE ? OR c.company_name LIKE ? OR c.phone LIKE ?)';
    array_push($params, $needle, $needle, $needle, $needle);
}
$sql = 'SELECT d.id,d.number,d.issue_date,d.due_date,d.total,d.currency_code,d.status,c.name customer,c.company_name,c.phone,(SELECT COALESCE(SUM(p.amount),0) FROM payments p WHERE p.invoice_id=d.id)-(SELECT COALESCE(SUM(r.amount),0) FROM payment_reversals r JOIN payments rp ON rp.id=r.payment_id WHERE rp.invoice_id=d.id) paid,(SELECT COALESCE(SUM(ca.amount),0) FROM credit_note_applications ca WHERE ca.invoice_id=d.id) credited,DATEDIFF(CURDATE(),d.due_date) due_days FROM documents d JOIN customers c ON c.id=d.customer_id WHERE ' . implode(' AND ', $where) . ' HAVING d.total-paid-credited>.009 ORDER BY d.due_date ASC,d.id DESC LIMIT 250';
$stmt = db()->prepare($sql);
$stmt->execute($params);
$openInvoices = $stmt->fetchAll();

$selected = null;
if ($invoiceId > 0) {
    $stmt = db()->prepare('SELECT d.*,c.name customer,c.company_name,c.phone,c.email,(SELECT COALESCE(SUM(p.amount),0) FROM payments p WHERE p.invoice_id=d.id)-(SELECT COALESCE(SUM(r.amount),0) FROM payment_reversals r JOIN payments rp ON rp.id=r.payment_id WHERE rp.invoice_id=d.id) paid,(SELECT COALESCE(SUM(ca.amount),0) FROM credit_note_applications ca WHERE ca.invoice_id=d.id) credited,DATEDIFF(CURDATE(),d.due_date) due_days FROM documents d JOIN customers c ON c.id=d.customer_id WHERE d.id=? AND d.type="invoice" AND d.status NOT IN ("cancelled","draft")');
    $stmt->execute([$invoiceId]);
    $selected = $stmt->fetch() ?: null;
    if ($selected && max(0, (float)$selected['total'] - (float)$selected['paid'] - (float)$selected['credited']) <= 0.009) {
        flash('success', 'That invoice is already paid in full.');
        redirect('index.php?page=document-view&id=' . $invoiceId);
    }
}
$accounts = db()->query('SELECT * FROM payment_accounts WHERE active=1 ORDER BY currency_code,type,name')->fetchAll();
$openTotal = 0.0;
$overdueInvoices = 0;
foreach ($openInvoices as $invoice) {
    if ($invoice['currency_code'] === (settings()['currency_code'] ?? 'USD')) $openTotal += max(0, (float)$invoice['total'] - (float)$invoice['paid'] - (float)$invoice['credited']);
    if ((int)$invoice['due_days'] > 0) $overdueInvoices++;
}

render_header('Receive payment', 'payments');
?>
<section class="payment-command-hero">
    <div><span class="command-kicker">Customer payments</span><h2>Receive and allocate a payment</h2><p>Find the invoice, confirm how the customer paid, and save the receipt in one guided flow.</p></div>
    <a class="button secondary" href="index.php?page=payments">View payment register</a>
</section>

<section class="payment-overview" aria-label="Outstanding invoice overview">
    <article><span>Open invoices</span><strong><?=count($openInvoices)?></strong><small>Ready to receive payment</small></article>
    <article><span>Overdue invoices</span><strong><?=$overdueInvoices?></strong><small>Require customer follow-up</small></article>
    <article><span><?=e(settings()['currency_code'] ?? 'USD')?> outstanding</span><strong><?=money($openTotal)?></strong><small>Base-currency open balance</small></article>
</section>

<section class="receive-payment-layout">
    <article class="panel invoice-payment-picker">
        <div class="payment-step-heading"><i>1</i><span><h2>Choose the invoice</h2><p>Search by customer, company, phone number or invoice number.</p></span></div>
        <form class="payment-search" method="get">
            <label for="payment-search">Search open invoices</label>
            <div><input id="payment-search" name="q" value="<?=e($query)?>" placeholder="e.g. SZW-INV- or customer name"><button class="button secondary">Search</button><?php if ($query !== ''):?><a href="receive-payment.php">Clear</a><?php endif;?></div>
        </form>
        <div class="open-invoice-list">
            <?php foreach ($openInvoices as $invoice):?><?php $balance = max(0, (float)$invoice['total'] - (float)$invoice['paid'] - (float)$invoice['credited']);?>
                <a class="<?=$invoiceId === (int)$invoice['id'] ? 'selected' : ''?>" href="receive-payment.php?invoice_id=<?=$invoice['id']?><?=$query !== '' ? '&q=' . rawurlencode($query) : ''?>">
                    <i><?=app_nav_icon('invoices')?></i>
                    <span><b><?=e($invoice['number'])?> · <?=e($invoice['company_name'] ?: $invoice['customer'])?></b><small><?=e(date('j M Y', strtotime($invoice['issue_date'])))?> · <?php if ((int)$invoice['due_days'] > 0):?><em><?=$invoice['due_days']?> days overdue</em><?php else:?>due <?=e(date('j M Y', strtotime($invoice['due_date'])))?><?php endif;?></small></span>
                    <strong><?=money($balance, $invoice['currency_code'])?></strong>
                    <em>&rarr;</em>
                </a>
            <?php endforeach;?>
            <?php if (!$openInvoices):?><div class="command-empty"><b>No matching open invoices</b><span>Try another search or create a new invoice first.</span><a class="button primary small" href="quick-invoice.php">Create invoice</a></div><?php endif;?>
        </div>
    </article>

    <aside class="panel receive-payment-panel">
        <?php if ($selected):?><?php $balance = max(0, (float)$selected['total'] - (float)$selected['paid'] - (float)$selected['credited']);?>
            <div class="payment-step-heading"><i>2</i><span><h2>Confirm the receipt</h2><p>Record exactly what arrived in your account.</p></span></div>
            <div class="selected-invoice-summary">
                <span><small>Customer</small><b><?=e($selected['company_name'] ?: $selected['customer'])?></b></span>
                <span><small>Invoice</small><b><?=e($selected['number'])?></b></span>
                <span><small>Invoice total</small><b><?=money($selected['total'], $selected['currency_code'])?></b></span>
                <span class="balance"><small>Balance due</small><strong><?=money($balance, $selected['currency_code'])?></strong></span>
            </div>
            <?php if (!$accounts):?><div class="alert error" role="alert">Add an active payment account in Settings before receiving a payment.</div><?php else:?>
            <form method="post" class="payment-form guided-payment-form">
                <?=csrf_field()?>
                <input type="hidden" name="action" value="record_payment">
                <input type="hidden" name="invoice_id" value="<?=$invoiceId?>">
                <input type="hidden" data-invoice-currency value="<?=e($selected['currency_code'])?>">
                <label>Payment date<input type="date" name="payment_date" value="<?=date('Y-m-d')?>" required></label>
                <label>Received through<select name="account_id" data-payment-account required><option value="">Select Cash, EcoCash, bank or POS</option><?php foreach ($accounts as $account):?><option value="<?=$account['id']?>" data-currency="<?=e($account['currency_code'])?>"><?=e($account['name'])?> · <?=e($account['currency_code'])?></option><?php endforeach;?></select></label>
                <label>Amount received<input type="number" step=".01" min=".01" name="received_amount" value="<?=number_format($balance, 2, '.', '')?>" data-received required></label>
                <label>Exchange rate<input type="number" step=".000001" min=".000001" name="exchange_rate" value="1" data-exchange-rate required><small>Payment currency units for 1 <?=e($selected['currency_code'])?></small></label>
                <label>Transaction fee<input type="number" step=".01" min="0" name="fee_amount" value="0"></label>
                <label>Reference / approval code<input name="reference" placeholder="EcoCash approval or bank reference"></label>
                <label class="full">Internal note<input name="notes" placeholder="Optional note about this receipt"></label>
                <div class="payment-application full"><span>Amount applied to <?=e($selected['number'])?></span><strong><?=e($selected['currency_code'])?> <span data-applied><?=number_format($balance, 2)?></span></strong></div>
                <button class="button command-payment full" type="submit"><?=app_nav_icon('payments')?> Save payment and update invoice</button>
            </form>
            <?php endif;?>
        <?php else:?>
            <div class="payment-awaiting-selection"><i><?=app_nav_icon('payments')?></i><span>Step 2</span><h2>Select an invoice to continue</h2><p>The payment form will appear here with the outstanding balance already filled in.</p></div>
        <?php endif;?>
    </aside>
</section>

<section class="payment-assurance">
    <div><b>Accurate allocation</b><span>The payment is applied only to the selected invoice.</span></div>
    <div><b>Zimbabwe-ready channels</b><span>Cash, EcoCash, bank transfer, POS and configured accounts.</span></div>
    <div><b>Automatic status</b><span>Invoice and linked refill payment statuses update immediately.</span></div>
</section>
<?php render_footer();
