<?php
// POST handling must happen BEFORE _guard.php so header() redirects can fire
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
require_once __DIR__ . '/../includes/zoho.php';
require_once __DIR__ . '/../includes/settings.php';
auth_require_admin();

$step       = $_GET['step']       ?? 'start';
$contact_id = $_GET['contact_id'] ?? '';
$invoice_id = $_GET['invoice_id'] ?? '';
$payment_id = $_GET['payment_id'] ?? '';
$fee_id     = $_GET['fee_id']     ?? '';
$flash_msg  = $_GET['msg']        ?? '';

$result = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $do = $_POST['do'] ?? '';

    // ── Step 1: Create customer ───────────────────────────────
    if ($do === 'create_contact') {
        $payload = [
            'contact_name'    => trim($_POST['contact_name'] ?? ''),
            'company_name'    => trim($_POST['company_name'] ?? '') ?: null,
            'contact_type'    => 'customer',
            'contact_persons' => [[
                'first_name'         => trim($_POST['first_name'] ?? ''),
                'last_name'          => trim($_POST['last_name']  ?? ''),
                'email'              => trim($_POST['email']      ?? ''),
                'phone'              => trim($_POST['phone']      ?? ''),
                'is_primary_contact' => true,
            ]],
            'billing_address' => [
                'address' => trim($_POST['address'] ?? ''),
                'city'    => trim($_POST['city']    ?? ''),
                'country' => 'South Africa',
            ],
        ];
        $r = zoho_request('POST', '/contacts', $payload);
        if ($r['ok']) {
            $contact_id = (string)($r['data']['contact']['contact_id'] ?? '');
            header('Location: zoho-test.php?step=invoice&contact_id=' . urlencode($contact_id));
            exit;
        } else {
            $result = ['ok' => false, 'msg' => 'Create contact failed', 'detail' => $r];
        }
    }

    // ── Step 2: Create draft invoice ─────────────────────────
    if ($do === 'create_invoice' && !empty($_POST['contact_id'])) {
        $cid = (string)$_POST['contact_id'];
        $description = trim($_POST['description'] ?? 'Buy Local Membership — test invoice');
        $rate        = (float)($_POST['rate'] ?? 250);
        $qty         = (int)($_POST['quantity'] ?? 1);

        $payload = [
            'customer_id' => $cid,
            'date'        => date('Y-m-d'),
            'line_items'  => [[
                'name'         => $description,
                'description'  => $description,
                'rate'         => $rate,
                'quantity'     => $qty,
            ]],
            'notes'       => 'Test invoice from Buy Local Lowveld website',
        ];
        $r = zoho_request('POST', '/invoices', $payload);
        if ($r['ok']) {
            $invoice_id = (string)($r['data']['invoice']['invoice_id'] ?? '');
            $invoice_number = $r['data']['invoice']['invoice_number'] ?? '';
            header('Location: zoho-test.php?step=done&contact_id=' . urlencode($cid)
                  . '&invoice_id=' . urlencode($invoice_id)
                  . '&invoice_number=' . urlencode($invoice_number));
            exit;
        } else {
            $result = ['ok' => false, 'msg' => 'Create invoice failed', 'detail' => $r];
        }
    }

    // ── Step 3: Mark invoice as sent (drafts can't receive payment) ──
    if ($do === 'mark_sent' && !empty($_POST['invoice_id'])) {
        $iid = (string)$_POST['invoice_id'];
        $r = zoho_request('POST', '/invoices/' . urlencode($iid) . '/status/sent', []);
        if ($r['ok']) {
            header('Location: zoho-test.php?step=done&contact_id=' . urlencode($_POST['contact_id'] ?? '')
                  . '&invoice_id=' . urlencode($iid)
                  . '&msg=invoice_sent');
            exit;
        } else {
            $result = ['ok' => false, 'msg' => 'Mark sent failed', 'detail' => $r];
        }
    }

    // ── Step 4: Record payment against invoice ───────────────────
    if ($do === 'record_payment' && !empty($_POST['invoice_id'])) {
        $iid          = (string)$_POST['invoice_id'];
        $cid          = (string)$_POST['contact_id'];
        $amount       = (float)($_POST['amount']       ?? 0);
        $date         = (string)($_POST['date']        ?? date('Y-m-d'));
        $payment_mode = (string)($_POST['payment_mode']?? 'banktransfer');
        $account_id   = (string)($_POST['account_id']  ?? '');
        $reference    = trim($_POST['reference']       ?? '');
        $gateway      = (string)($_POST['gateway']     ?? ''); // 'payfast' | 'netcash' | ''

        $payload = [
            'customer_id'      => $cid,
            'payment_mode'     => $payment_mode,
            'amount'           => $amount,
            'date'             => $date,
            'reference_number' => $reference ?: null,
            'description'      => 'Payment recorded via Buy Local test page',
            'invoices'         => [[
                'invoice_id'      => $iid,
                'amount_applied'  => $amount,
            ]],
        ];
        if ($account_id !== '') {
            $payload['account_id'] = $account_id;
        }

        $r = zoho_request('POST', '/customerpayments', $payload);
        if ($r['ok']) {
            $payment_id = (string)($r['data']['payment']['payment_id'] ?? '');
            $fee_expense_id = '';

            // Auto-record gateway fee as expense from the same bank account
            if ($gateway !== '' && $account_id !== '') {
                $fees = gateway_calc_fee($gateway, $amount);
                if ($fees['fee_incl'] > 0) {
                    // Use the configured expense account if set, otherwise auto-detect "Bank Charges"
                    $bank_charges_id = (string)setting_get('gateway_fee_account_id', '');

                    if (!$bank_charges_id) {
                        // Fallback: try to find "Bank Charges" / "Merchant Fees" by name
                        $exp_acc = zoho_request('GET', '/chartofaccounts?filter_by=AccountType.Expense&per_page=200');
                        if ($exp_acc['ok']) {
                            foreach (($exp_acc['data']['chartofaccounts'] ?? []) as $coa) {
                                $name = strtolower($coa['account_name'] ?? '');
                                if (str_contains($name, 'bank charge') || str_contains($name, 'merchant fee') || str_contains($name, 'gateway fee')) {
                                    $bank_charges_id = (string)$coa['account_id'];
                                    break;
                                }
                            }
                        }
                    }

                    if ($bank_charges_id) {
                        $exp_payload = [
                            'account_id'             => $bank_charges_id,   // expense category
                            'paid_through_account_id' => $account_id,        // money came OUT of this bank account
                            'date'                   => $date,
                            'amount'                 => $fees['fee_incl'],
                            'is_inclusive_tax'       => true,
                            'description'            => ucfirst($gateway) . ' transaction fee on payment '
                                                        . ($reference ?: $iid) . ' (R' . number_format($amount,2) . ')',
                            'reference_number'       => 'FEE-' . ($reference ?: substr($payment_id, -8)),
                        ];
                        $exp_r = zoho_request('POST', '/expenses', $exp_payload);
                        if ($exp_r['ok']) {
                            $fee_expense_id = (string)($exp_r['data']['expense']['expense_id'] ?? '');
                        }
                    }
                }
            }

            $redirect = 'zoho-test.php?step=done'
                  . '&contact_id=' . urlencode($cid)
                  . '&invoice_id=' . urlencode($iid)
                  . '&payment_id=' . urlencode($payment_id)
                  . '&msg=payment_recorded';
            if ($fee_expense_id) $redirect .= '&fee_id=' . urlencode($fee_expense_id);
            header('Location: ' . $redirect);
            exit;
        } else {
            $result = ['ok' => false, 'msg' => 'Record payment failed', 'detail' => $r];
        }
    }
}

// ── Always load: contact info if we have one, invoice info if we have one, bank accounts
$contact_data = null;
if ($contact_id) {
    $r = zoho_request('GET', '/contacts/' . urlencode($contact_id));
    if ($r['ok']) $contact_data = $r['data']['contact'] ?? null;
}

$invoice_data = null;
if ($invoice_id) {
    $r = zoho_request('GET', '/invoices/' . urlencode($invoice_id));
    if ($r['ok']) $invoice_data = $r['data']['invoice'] ?? null;
}

$payment_data = null;
if ($payment_id) {
    $r = zoho_request('GET', '/customerpayments/' . urlencode($payment_id));
    if ($r['ok']) $payment_data = $r['data']['payment'] ?? null;
}

$fee_data = null;
if ($fee_id) {
    $r = zoho_request('GET', '/expenses/' . urlencode($fee_id));
    if ($r['ok']) $fee_data = $r['data']['expense'] ?? null;
}

// Bank accounts + recent transactions
$bank_accounts = [];
$bank_txns     = [];
$bank_error    = null;
$ba = zoho_request('GET', '/bankaccounts');
if ($ba['ok']) {
    $bank_accounts = $ba['data']['bankaccounts'] ?? [];
    if (!empty($bank_accounts)) {
        $first_account = $bank_accounts[0]['account_id'];
        $bt = zoho_request('GET', '/banktransactions?account_id=' . urlencode($first_account) . '&per_page=20');
        if ($bt['ok']) {
            $bank_txns = $bt['data']['banktransactions'] ?? [];
        }
    }
} else {
    $bank_error = 'HTTP ' . $ba['status'] . ' — ' . substr($ba['raw'] ?? '', 0, 200);
}

// Now load the page chrome
$page_title = 'Zoho Test Page';
require __DIR__ . '/_guard.php';
?>

<style>
.zt-step{display:flex;gap:.5rem;margin-bottom:1.5rem;}
.zt-step span{padding:.4em .9em;border-radius:999px;background:var(--surface-alt);font-size:.78rem;color:var(--ink-muted);font-weight:600;}
.zt-step span.active{background:var(--brand-primary);color:#fff;}
.zt-step span.done{background:#22c55e;color:#fff;}
.zt-card{background:#fff;border:1px solid var(--line);border-radius:var(--radius);padding:1.5rem;margin-bottom:1.25rem;}
.zt-result{font-family:ui-monospace,Menlo,monospace;font-size:.8rem;background:#0e0e0e;color:#9be39b;padding:1rem;border-radius:6px;max-height:280px;overflow:auto;white-space:pre-wrap;word-break:break-all;}
.zt-result.err{color:#ff8a8a;}
.zt-grid{display:grid;grid-template-columns:1fr 1fr;gap:1rem;}
@media(max-width:600px){.zt-grid{grid-template-columns:1fr;}}
.atbl{width:100%;border-collapse:collapse;font-size:.85rem;}
.atbl th{padding:.5rem .75rem;background:var(--surface-alt);font-size:.7rem;text-transform:uppercase;letter-spacing:.05em;color:var(--ink-muted);border-bottom:2px solid var(--line);text-align:left;white-space:nowrap;}
.atbl td{padding:.5rem .75rem;border-bottom:1px solid var(--line);}
.field-row{display:flex;justify-content:space-between;padding:.4rem 0;border-bottom:1px dashed var(--line);font-size:.88rem;}
.field-row:last-child{border-bottom:none;}
.field-row .lbl{color:var(--ink-muted);}
</style>

<section class="section">
<div class="container">

<h1 style="margin:0 0 .5rem;">Zoho Test Page</h1>
<p class="muted" style="margin:0 0 1.5rem;">Live API test: create a customer, create a draft invoice, view bank feeds.</p>

<!-- Stepper -->
<div class="zt-step">
    <span class="<?= $step==='start'?'active':'done' ?>">1. Create customer</span>
    <span class="<?= $step==='invoice'?'active':($step==='done'?'done':'') ?>">2. Create invoice</span>
    <span class="<?= ($step==='done' && empty($payment_data))?'active':(!empty($payment_data)?'done':'') ?>">3. Mark sent + pay</span>
    <span class="<?= !empty($payment_data)?'active':'' ?>">4. Done</span>
</div>

<?php if ($result && !$result['ok']): ?>
    <div class="alert alert-error" style="margin-bottom:1rem;">
        <strong><?= htmlspecialchars($result['msg']) ?></strong> (HTTP <?= $result['detail']['status'] ?>)
        <pre class="zt-result err" style="margin-top:.5rem;"><?= htmlspecialchars(substr($result['detail']['raw'] ?? '', 0, 1500)) ?></pre>
    </div>
<?php endif; ?>

<!-- ─────── STEP 1: Create customer ─────── -->
<?php if ($step === 'start'): ?>
<div class="zt-card">
    <h2 style="margin-top:0;">Step 1 — Create customer in Zoho Books</h2>
    <p class="muted" style="font-size:.88rem;">Fill in customer details and click Create.</p>

    <form method="post">
        <?= csrf_field() ?>
        <input type="hidden" name="do" value="create_contact">

        <label>Contact name *</label>
        <input type="text" name="contact_name" required value="Test Buyer <?= date('H:i') ?>">

        <label>Company name</label>
        <input type="text" name="company_name" value="Test Company Pty Ltd">

        <div class="zt-grid">
            <div>
                <label>First name</label>
                <input type="text" name="first_name" value="Test">
            </div>
            <div>
                <label>Last name</label>
                <input type="text" name="last_name" value="Customer">
            </div>
        </div>

        <div class="zt-grid">
            <div>
                <label>Email</label>
                <input type="email" name="email" value="test+<?= time() ?>@example.com">
            </div>
            <div>
                <label>Phone</label>
                <input type="tel" name="phone" value="0123456789">
            </div>
        </div>

        <label>Address</label>
        <input type="text" name="address" value="123 Test Street">

        <label>City</label>
        <input type="text" name="city" value="Nelspruit">

        <button type="submit" class="btn">Create customer →</button>
    </form>
</div>
<?php endif; ?>

<!-- ─────── STEP 2: Create draft invoice ─────── -->
<?php if ($step === 'invoice' && $contact_data): ?>
<div class="zt-card">
    <h2 style="margin-top:0;">Step 2 — Create draft invoice</h2>

    <p>Customer created:</p>
    <div class="field-row"><span class="lbl">Contact ID</span><strong><code><?= htmlspecialchars($contact_id) ?></code></strong></div>
    <div class="field-row"><span class="lbl">Name</span><strong><?= htmlspecialchars($contact_data['contact_name'] ?? '') ?></strong></div>
    <div class="field-row"><span class="lbl">Email</span><?= htmlspecialchars($contact_data['email'] ?? '—') ?></div>
    <div class="field-row"><span class="lbl">Status</span><?= htmlspecialchars($contact_data['status'] ?? '—') ?></div>

    <form method="post" style="margin-top:1.5rem;">
        <?= csrf_field() ?>
        <input type="hidden" name="do" value="create_invoice">
        <input type="hidden" name="contact_id" value="<?= htmlspecialchars($contact_id) ?>">

        <label>Item description</label>
        <input type="text" name="description" value="Buy Local Membership — Bronze (Test)">

        <div class="zt-grid">
            <div>
                <label>Rate (R)</label>
                <input type="number" step="0.01" name="rate" value="250.00">
            </div>
            <div>
                <label>Quantity</label>
                <input type="number" name="quantity" value="1" min="1">
            </div>
        </div>

        <button type="submit" class="btn">Create draft invoice →</button>
        <a href="zoho-test.php" class="btn btn-outline">Start over</a>
    </form>
</div>
<?php endif; ?>

<!-- ─────── STEP 3: Done ─────── -->
<?php if ($step === 'done' && $contact_data && $invoice_data):
    $invoice_status = strtolower($invoice_data['status'] ?? '');
    $invoice_balance = (float)($invoice_data['balance'] ?? $invoice_data['total'] ?? 0);
    $is_draft        = ($invoice_status === 'draft');
    $is_payable      = in_array($invoice_status, ['sent','overdue','partially_paid'], true);
    $is_paid         = ($invoice_status === 'paid');
?>
<div class="zt-card">
    <h2 style="margin-top:0;">
        <?= $is_paid ? '✅ Invoice paid in full' : '✅ Customer + invoice ready' ?>
    </h2>

    <?php if ($flash_msg === 'invoice_sent'): ?>
        <div class="alert alert-success" data-autohide>Invoice marked as sent. You can now record a payment.</div>
    <?php elseif ($flash_msg === 'payment_recorded'): ?>
        <div class="alert alert-success" data-autohide>Payment recorded successfully on Zoho.</div>
    <?php endif; ?>

    <h3 style="margin-top:0;font-size:1rem;">Customer</h3>
    <div class="field-row"><span class="lbl">Contact ID</span><strong><code><?= htmlspecialchars($contact_id) ?></code></strong></div>
    <div class="field-row"><span class="lbl">Name</span><strong><?= htmlspecialchars($contact_data['contact_name'] ?? '') ?></strong></div>

    <h3 style="margin:1.5rem 0 .5rem;font-size:1rem;">Invoice</h3>
    <div class="field-row"><span class="lbl">Invoice number</span><strong><?= htmlspecialchars($invoice_data['invoice_number'] ?? '') ?></strong></div>
    <div class="field-row"><span class="lbl">Invoice ID</span><code><?= htmlspecialchars($invoice_id) ?></code></div>
    <div class="field-row"><span class="lbl">Status</span><strong style="text-transform:uppercase;color:<?= $is_paid?'#16a34a':($is_draft?'#b45309':'#1a1a2e') ?>;"><?= htmlspecialchars($invoice_status) ?></strong></div>
    <div class="field-row"><span class="lbl">Total</span><strong>R <?= htmlspecialchars(number_format((float)($invoice_data['total'] ?? 0), 2)) ?></strong></div>
    <?php if (!$is_paid && $invoice_balance > 0): ?>
        <div class="field-row"><span class="lbl">Balance due</span><strong style="color:#b45309;">R <?= htmlspecialchars(number_format($invoice_balance, 2)) ?></strong></div>
    <?php endif; ?>
    <div class="field-row"><span class="lbl">Date</span><?= htmlspecialchars($invoice_data['date'] ?? '') ?></div>

    <p style="margin-top:1rem;">
        <a href="https://books.zoho.com/app/<?= htmlspecialchars(ZOHO_ORG_ID) ?>#/invoices/<?= htmlspecialchars($invoice_id) ?>"
           target="_blank" class="btn btn-outline">Open invoice in Zoho ↗</a>
    </p>

    <!-- ── Payment block ── -->
    <?php if ($is_draft): ?>
        <h3 style="margin:2rem 0 .5rem;font-size:1rem;">Record payment</h3>
        <div class="alert alert-info" style="margin:0 0 1rem;">
            <strong>Invoice is still a draft.</strong> Drafts can't receive payments in Zoho.
            Mark it as sent first, then you can record payment.
        </div>
        <form method="post" style="display:inline;">
            <?= csrf_field() ?>
            <input type="hidden" name="do" value="mark_sent">
            <input type="hidden" name="invoice_id" value="<?= htmlspecialchars($invoice_id) ?>">
            <input type="hidden" name="contact_id" value="<?= htmlspecialchars($contact_id) ?>">
            <button type="submit" class="btn">Mark as sent →</button>
        </form>
    <?php elseif ($is_payable): ?>
        <h3 style="margin:2rem 0 .5rem;font-size:1rem;">Record payment to bank account</h3>
        <?php if (empty($bank_accounts)): ?>
            <div class="alert alert-error">
                You don't have a bank account in Zoho yet. Connect one first to record payments.
            </div>
        <?php else: ?>
        <form method="post" id="payment-form">
            <?= csrf_field() ?>
            <input type="hidden" name="do" value="record_payment">
            <input type="hidden" name="invoice_id" value="<?= htmlspecialchars($invoice_id) ?>">
            <input type="hidden" name="contact_id" value="<?= htmlspecialchars($contact_id) ?>">

            <div class="zt-grid">
                <div>
                    <label>Amount (R) *</label>
                    <input type="number" step="0.01" name="amount" id="pay-amount" required
                           value="<?= htmlspecialchars(number_format($invoice_balance, 2, '.', '')) ?>"
                           min="0.01" max="<?= htmlspecialchars((string)$invoice_balance) ?>">
                </div>
                <div>
                    <label>Payment date *</label>
                    <input type="date" name="date" required value="<?= date('Y-m-d') ?>">
                </div>
            </div>

            <div class="zt-grid">
                <div>
                    <label>Payment method *</label>
                    <select name="payment_mode" required>
                        <option value="banktransfer">Bank Transfer</option>
                        <option value="cash">Cash</option>
                        <option value="check">Cheque</option>
                        <option value="creditcard">Credit Card</option>
                        <option value="bankremittance">Bank Remittance</option>
                        <option value="onlinepayment">Online Payment (PayFast / Netcash)</option>
                    </select>
                </div>
                <div>
                    <label>Deposit to bank account *</label>
                    <select name="account_id" required>
                        <option value="">— pick account —</option>
                        <?php foreach ($bank_accounts as $a): ?>
                            <option value="<?= htmlspecialchars($a['account_id']) ?>">
                                <?= htmlspecialchars($a['account_name']) ?>
                                <?php if (!empty($a['bank_name'])): ?>
                                    — <?= htmlspecialchars($a['bank_name']) ?>
                                <?php endif; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div class="zt-grid">
                <div>
                    <label>Gateway (auto-records fee)</label>
                    <select name="gateway" id="pay-gateway">
                        <option value="">— none / no fee —</option>
                        <option value="payfast"
                                data-pct="<?= htmlspecialchars((string)setting_get('payfast.fee_percent', 0)) ?>"
                                data-fixed="<?= htmlspecialchars((string)setting_get('payfast.fee_fixed', 0)) ?>"
                                data-vat="<?= htmlspecialchars((string)setting_get('payfast.fee_vat_percent', 0)) ?>">
                            PayFast (<?= setting_get('payfast.fee_percent') ?>% + R<?= setting_get('payfast.fee_fixed') ?>)
                        </option>
                        <option value="netcash"
                                data-pct="<?= htmlspecialchars((string)setting_get('netcash.fee_percent', 0)) ?>"
                                data-fixed="<?= htmlspecialchars((string)setting_get('netcash.fee_fixed', 0)) ?>"
                                data-vat="<?= htmlspecialchars((string)setting_get('netcash.fee_vat_percent', 0)) ?>">
                            Netcash (<?= setting_get('netcash.fee_percent') ?>% + R<?= setting_get('netcash.fee_fixed') ?>)
                        </option>
                    </select>
                    <p class="desc" style="font-size:.78rem;color:var(--ink-muted);margin:.3rem 0 0;">
                        <a href="settings.php">⚙ Edit fee rates</a>
                    </p>
                </div>
                <div>
                    <label>Reference / payment ID (optional)</label>
                    <input type="text" name="reference" placeholder="e.g. PayFast TX 12345 or EFT reference">
                </div>
            </div>

            <!-- Live fee preview -->
            <div id="fee-preview" style="display:none;background:#fff7ed;border:1px solid #fed7aa;border-radius:6px;padding:.85rem 1rem;margin:1rem 0;">
                <strong style="font-size:.88rem;">Will auto-record this expense:</strong>
                <div style="display:flex;gap:1.5rem;margin-top:.4rem;flex-wrap:wrap;font-size:.85rem;">
                    <span>Fee (excl): <strong>R <span id="fp-excl">0.00</span></strong></span>
                    <span>VAT: <strong>R <span id="fp-vat">0.00</span></strong></span>
                    <span>Total fee: <strong style="color:#b45309;">R <span id="fp-incl">0.00</span></strong></span>
                    <span>Net to bank: <strong style="color:#16a34a;">R <span id="fp-net">0.00</span></strong></span>
                </div>
            </div>

            <button type="submit" class="btn" style="margin-top:.75rem;">Record payment →</button>
        </form>

        <script>
        (function(){
            const amt = document.getElementById('pay-amount');
            const gw  = document.getElementById('pay-gateway');
            const box = document.getElementById('fee-preview');
            const excl = document.getElementById('fp-excl');
            const vat  = document.getElementById('fp-vat');
            const incl = document.getElementById('fp-incl');
            const net  = document.getElementById('fp-net');
            function recalc(){
                const opt = gw.options[gw.selectedIndex];
                const a = parseFloat(amt.value)||0;
                if (!opt.value || !a) { box.style.display='none'; return; }
                const pct   = parseFloat(opt.dataset.pct)||0;
                const fixed = parseFloat(opt.dataset.fixed)||0;
                const vatP  = parseFloat(opt.dataset.vat)||0;
                const feeE  = (a*pct/100) + fixed;
                const vatA  = feeE*vatP/100;
                const feeI  = feeE+vatA;
                excl.textContent = feeE.toFixed(2);
                vat.textContent  = vatA.toFixed(2);
                incl.textContent = feeI.toFixed(2);
                net.textContent  = (a - feeI).toFixed(2);
                box.style.display='block';
            }
            amt.addEventListener('input', recalc);
            gw.addEventListener('change', recalc);
            recalc();
        })();
        </script>
        <?php endif; ?>
    <?php endif; ?>

    <!-- Show recorded payment if any -->
    <?php if ($payment_data): ?>
        <h3 style="margin:2rem 0 .5rem;font-size:1rem;">Payment receipt</h3>
        <div class="field-row"><span class="lbl">Payment number</span><strong><?= htmlspecialchars($payment_data['payment_number'] ?? '') ?></strong></div>
        <div class="field-row"><span class="lbl">Payment ID</span><code><?= htmlspecialchars($payment_id) ?></code></div>
        <div class="field-row"><span class="lbl">Amount</span><strong>R <?= htmlspecialchars(number_format((float)($payment_data['amount'] ?? 0), 2)) ?></strong></div>
        <div class="field-row"><span class="lbl">Date</span><?= htmlspecialchars($payment_data['date'] ?? '') ?></div>
        <div class="field-row"><span class="lbl">Method</span><?= htmlspecialchars($payment_data['payment_mode'] ?? '') ?></div>
        <div class="field-row"><span class="lbl">Deposit account</span><?= htmlspecialchars($payment_data['account_name'] ?? '—') ?></div>
        <p style="margin-top:1rem;">
            <a href="https://books.zoho.com/app/<?= htmlspecialchars(ZOHO_ORG_ID) ?>#/payments-received/<?= htmlspecialchars($payment_id) ?>"
               target="_blank" class="btn btn-outline">Open payment in Zoho ↗</a>
        </p>
    <?php endif; ?>

    <!-- Show gateway fee expense if recorded -->
    <?php if ($fee_data): ?>
        <h3 style="margin:2rem 0 .5rem;font-size:1rem;">Gateway fee (auto-recorded)</h3>
        <div class="field-row"><span class="lbl">Expense ID</span><code><?= htmlspecialchars($fee_id) ?></code></div>
        <div class="field-row"><span class="lbl">Description</span><?= htmlspecialchars($fee_data['description'] ?? '') ?></div>
        <div class="field-row"><span class="lbl">Amount (incl VAT)</span><strong style="color:#b45309;">R <?= htmlspecialchars(number_format((float)($fee_data['total'] ?? 0), 2)) ?></strong></div>
        <div class="field-row"><span class="lbl">Paid from</span><?= htmlspecialchars($fee_data['paid_through_account_name'] ?? '—') ?></div>
        <div class="field-row"><span class="lbl">Category</span><?= htmlspecialchars($fee_data['account_name'] ?? '—') ?></div>
        <p style="margin-top:1rem;font-size:.88rem;color:var(--ink-muted);">
            ✓ The fee has been deducted from the same bank account as the payment, so the running bank balance reflects the net deposit.
        </p>
        <p>
            <a href="https://books.zoho.com/app/<?= htmlspecialchars(ZOHO_ORG_ID) ?>#/expenses/<?= htmlspecialchars($fee_id) ?>"
               target="_blank" class="btn btn-outline">Open fee in Zoho ↗</a>
        </p>
    <?php endif; ?>

    <p style="margin-top:1.5rem;">
        <a href="zoho-test.php" class="btn btn-outline">Start another test</a>
    </p>
</div>
<?php endif; ?>

<!-- ─────── BANK FEEDS (always shown) ─────── -->
<div class="zt-card">
    <h2 style="margin-top:0;">Bank Feeds</h2>

    <?php if ($bank_error): ?>
        <div class="alert alert-error">
            <strong>Bank feeds unavailable.</strong> <?= htmlspecialchars($bank_error) ?>
            <p style="font-size:.85rem;margin:.5rem 0 0;">
                You may need to <a href="https://books.zoho.com/app/<?= htmlspecialchars(ZOHO_ORG_ID) ?>#/banking" target="_blank">connect a bank account</a> in Zoho Books first.
            </p>
        </div>
    <?php elseif (empty($bank_accounts)): ?>
        <p class="muted">No bank accounts connected in Zoho Books yet.
            <a href="https://books.zoho.com/app/<?= htmlspecialchars(ZOHO_ORG_ID) ?>#/banking" target="_blank">Connect one →</a>
        </p>
    <?php else: ?>
        <h3 style="font-size:.95rem;margin:0 0 .5rem;">Accounts (<?= count($bank_accounts) ?>)</h3>
        <table class="atbl">
            <thead>
                <tr><th>Name</th><th>Type</th><th style="text-align:right;">Balance</th><th>Currency</th></tr>
            </thead>
            <tbody>
            <?php foreach ($bank_accounts as $a): ?>
                <tr>
                    <td><strong><?= htmlspecialchars($a['account_name'] ?? '') ?></strong>
                        <br><small class="muted"><?= htmlspecialchars($a['bank_name'] ?? '') ?></small>
                    </td>
                    <td><?= htmlspecialchars($a['account_type'] ?? '') ?></td>
                    <td style="text-align:right;font-weight:600;">
                        <?= htmlspecialchars(number_format((float)($a['balance'] ?? 0), 2)) ?>
                    </td>
                    <td><?= htmlspecialchars($a['currency_code'] ?? '') ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>

        <?php if (!empty($bank_txns)): ?>
            <h3 style="font-size:.95rem;margin:1.5rem 0 .5rem;">Recent transactions on first account (<?= count($bank_txns) ?>)</h3>
            <table class="atbl">
                <thead>
                    <tr><th>Date</th><th>Description</th><th>Type</th><th style="text-align:right;">Amount</th><th>Status</th></tr>
                </thead>
                <tbody>
                <?php foreach ($bank_txns as $t): ?>
                    <tr>
                        <td style="white-space:nowrap;"><?= htmlspecialchars($t['date'] ?? '') ?></td>
                        <td><?= htmlspecialchars($t['description'] ?? $t['reference_number'] ?? '—') ?></td>
                        <td><?= htmlspecialchars($t['transaction_type'] ?? '') ?></td>
                        <td style="text-align:right;font-weight:600;">
                            <?= htmlspecialchars(number_format((float)($t['amount'] ?? 0), 2)) ?>
                        </td>
                        <td><?= htmlspecialchars($t['status'] ?? '') ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <p class="muted" style="font-size:.85rem;margin-top:1rem;">No transactions on the first account yet.</p>
        <?php endif; ?>
    <?php endif; ?>
</div>

</div>
</section>

<?php require __DIR__ . '/_footer.php'; ?>