<?php $this->start('body');
    $sale  = $this->data['sale'] ?? null;
    $banks = $this->data['banks'] ?? [];
    $efds  = $this->data['efds']  ?? [];
    $types = $this->data['types'] ?? [];
    $f     = $this->data['form']  ?? [];
    $balance = $sale ? round((float)$sale['total'] - (float)$sale['amount_paid'], 2) : 0;
?>

<div class="d-flex align-items-center justify-content-between mb-3">
    <h5 class="mb-0" style="font-weight:600;"><i class="fas fa-receipt me-2 text-muted"></i>Record Receipt</h5>
    <a href="<?= PROOT; ?>Receipts" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> All receipts</a>
</div>

<?= $this->raw('fb_msg'); ?>

<?php if ($sale): ?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-body p-3">
        <div class="row g-3">
            <div class="col-md-4"><div class="text-muted small">Invoice</div><div style="font-weight:600;"><?= htmlspecialchars($sale['sale_no'] ?: $sale['invoice_ref']); ?></div></div>
            <div class="col-md-4"><div class="text-muted small">Customer</div><div style="font-weight:600;"><?= htmlspecialchars($sale['customer_name']); ?></div></div>
            <div class="col-md-2"><div class="text-muted small">Total</div><div style="font-weight:600;"><?= htmlspecialchars($sale['currency']); ?> <?= number_format((float)$sale['total']); ?></div></div>
            <div class="col-md-2"><div class="text-muted small">Balance due</div><div style="font-weight:600;font-size:1.05rem;color:<?= $balance>0?'#f59e0b':'#22c55e'; ?>;"><?= htmlspecialchars($sale['currency']); ?> <?= number_format($balance); ?></div></div>
        </div>
    </div>
</div>
<?php endif; ?>

<form method="post" action="<?= PROOT; ?>Receipts/save" autocomplete="off">
    <input type="hidden" name="sale_id" value="<?= (int)($sale['c0d'] ?? 0); ?>">
    <div class="card border-0 shadow-sm">
        <div class="card-body p-3">
            <div class="row g-3">
                <div class="col-md-4">
                    <label class="form-label">Receipt type *</label>
                    <select name="receipt_type" id="fldRtype" class="form-select" required onchange="rsRcpTypeChanged()">
                        <?php foreach ($types as $k => $t): ?>
                            <option value="<?= $k; ?>" data-requires-efd="<?= $t['requires_efd']?1:0; ?>" <?= (($f['receipt_type'] ?? 'EFD_VAT')===$k?'selected':''); ?>>
                                <?= htmlspecialchars($t['label']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <div class="form-text">EFD types capture fiscal metadata for VAT return reconciliation.</div>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Receipt date *</label>
                    <input type="date" name="receipt_date" class="form-control" required value="<?= htmlspecialchars($f['receipt_date'] ?? date('Y-m-d')); ?>">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Amount *</label>
                    <div class="input-group">
                        <span class="input-group-text"><?= htmlspecialchars($sale['currency'] ?? 'TZS'); ?></span>
                        <input type="number" step="0.01" min="0.01" name="amount" class="form-control" required
                               value="<?= htmlspecialchars($f['amount'] ?? ($sale ? number_format($balance, 2, '.', '') : '')); ?>"
                               max="<?= $sale ? $balance : ''; ?>">
                    </div>
                    <?php if ($sale): ?><div class="form-text">Outstanding balance: <?= number_format($balance); ?></div><?php endif; ?>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Bank account *</label>
                    <select name="bank_account_id" class="form-select" required>
                        <option value="">— select —</option>
                        <?php foreach ($banks as $b): ?>
                            <option value="<?= (int)$b['c0d']; ?>" <?= ((int)($f['bank_account_id'] ?? 0)===(int)$b['c0d']?'selected':''); ?>>
                                <?= htmlspecialchars($b['bank_name']); ?> · <?= htmlspecialchars($b['account_name']); ?> (<?= htmlspecialchars($b['currency']); ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Payment method</label>
                    <select name="payment_method" class="form-select">
                        <?php foreach (['BANK_TRANSFER','CHEQUE','CASH','MOBILE_MONEY','POS'] as $m): ?>
                            <option value="<?= $m; ?>" <?= (($f['payment_method'] ?? 'BANK_TRANSFER')===$m?'selected':''); ?>><?= ucwords(strtolower(str_replace('_',' ',$m))); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Bank reference</label>
                    <input type="text" name="bank_reference" class="form-control" value="<?= htmlspecialchars($f['bank_reference'] ?? ''); ?>" placeholder="TT ref / cheque no">
                </div>
            </div>

            <hr class="my-3">
            <div id="efdBlock">
                <div class="d-flex align-items-center mb-2">
                    <strong><i class="fas fa-print me-2 text-muted"></i>EFD fiscal details</strong>
                    <span class="text-muted small ms-2">Required for TRA VAT return reconciliation</span>
                </div>
                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label">EFD device *</label>
                        <select name="efd_device_id" class="form-select">
                            <option value="0">— select —</option>
                            <?php foreach ($efds as $d): ?>
                                <option value="<?= (int)$d['c0d']; ?>" <?= ((int)($f['efd_device_id'] ?? 0)===(int)$d['c0d']?'selected':''); ?>>
                                    <?= htmlspecialchars($d['device_serial']); ?> · <?= htmlspecialchars($d['device_model']); ?> (<?= htmlspecialchars($d['location']); ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">EFD receipt # *</label>
                        <input type="text" name="efd_receipt_number" class="form-control" value="<?= htmlspecialchars($f['efd_receipt_number'] ?? ''); ?>" placeholder="e.g. 0000123456">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">EFD signature</label>
                        <input type="text" name="efd_signature" class="form-control" value="<?= htmlspecialchars($f['efd_signature'] ?? ''); ?>" placeholder="Signature/hash on print">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Z-report reference</label>
                        <input type="text" name="efd_z_number" class="form-control" value="<?= htmlspecialchars($f['efd_z_number'] ?? ''); ?>" placeholder="Daily Z-report no">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">EFD issued at</label>
                        <input type="datetime-local" name="efd_issued_at" class="form-control" value="<?= htmlspecialchars($f['efd_issued_at'] ?? ''); ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">EFD output VAT (auto)</label>
                        <input type="text" class="form-control" disabled value="Computed on save from invoice VAT rate">
                    </div>
                </div>
            </div>

            <div class="mt-3">
                <label class="form-label">Narrative (optional)</label>
                <textarea name="narrative" class="form-control" rows="2"><?= htmlspecialchars($f['narrative'] ?? ''); ?></textarea>
            </div>
        </div>
        <div class="card-footer bg-white text-end">
            <a href="<?= PROOT; ?>Receipts" class="btn btn-sm btn-outline-secondary">Cancel</a>
            <button type="submit" class="btn btn-sm btn-primary" style="background:<?= BRAND_COLOR; ?>;border-color:<?= BRAND_COLOR; ?>;">
                <i class="fas fa-save me-1"></i> Record &amp; Post
            </button>
        </div>
    </div>
</form>

<script>
function rsRcpTypeChanged() {
    const sel = document.getElementById('fldRtype');
    const opt = sel.options[sel.selectedIndex];
    const req = opt.dataset.requiresEfd === '1';
    document.getElementById('efdBlock').style.display = req ? '' : 'none';
}
document.addEventListener('DOMContentLoaded', rsRcpTypeChanged);
</script>

<?php $this->end(); ?>
