<?php $this->start('body');
    $projects = $this->data['projects'] ?? [];
    $cats     = $this->data['categories'] ?? [];
    $f        = $this->data['form'] ?? [];
?>

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

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

<form method="post" action="<?= PROOT; ?>PettyCash/save" autocomplete="off">
    <div class="card border-0 shadow-sm">
        <div class="card-body p-3">
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label">Project <span class="text-muted small">(optional — leave blank for central HQ)</span></label>
                    <select name="project_id" class="form-select">
                        <option value="0">— Central / HQ —</option>
                        <?php foreach ($projects as $p): ?>
                            <option value="<?= (int)$p['c0d']; ?>" <?= ((int)($f['project_id'] ?? 0)===(int)$p['c0d']?'selected':''); ?>>
                                <?= htmlspecialchars($p['project_no']); ?> · <?= htmlspecialchars($p['project_name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Amount *</label>
                    <input type="number" step="0.01" min="0.01" name="amount" class="form-control" required value="<?= htmlspecialchars($f['amount'] ?? ''); ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Currency</label>
                    <select name="currency" class="form-select">
                        <?php foreach (['TZS','USD','EUR','KES'] as $c): ?>
                            <option value="<?= $c; ?>" <?= (($f['currency'] ?? 'TZS')===$c?'selected':''); ?>><?= $c; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Budget Category</label>
                    <select name="budget_category_id" class="form-select">
                        <option value="0">—</option>
                        <?php foreach ($cats as $c): ?>
                            <option value="<?= (int)$c['c0d']; ?>" <?= ((int)($f['budget_category_id'] ?? 0)===(int)$c['c0d']?'selected':''); ?>>
                                <?= htmlspecialchars($c['category_name']); ?> <?php if ($c['category_code']): ?>· <span class="text-muted">(<?= htmlspecialchars($c['category_code']); ?>)</span><?php endif; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Payee <span class="text-muted small">(defaults to you — the custodian)</span></label>
                    <input type="text" class="form-control" value="<?= htmlspecialchars($_SESSION['full_name'] ?? ''); ?>" disabled>
                </div>

                <div class="col-12">
                    <label class="form-label">Purpose *</label>
                    <textarea name="purpose" class="form-control" rows="3" required placeholder="What is this cash needed for? Be specific — this appears on the PM + FM approval screens."><?= htmlspecialchars($f['purpose'] ?? ''); ?></textarea>
                </div>
            </div>

            <hr class="my-3">
            <div class="d-flex align-items-center mb-2">
                <strong><i class="fas fa-print me-2 text-muted"></i>Supplier receipt (optional — for VAT return)</strong>
                <span class="text-muted small ms-2">If the supplier issued an EFD tax invoice, capture it here so Input VAT is claimable.</span>
            </div>
            <div class="row g-3">
                <div class="col-md-4">
                    <label class="form-label">Supplier receipt type</label>
                    <select name="supplier_receipt_type" id="fldSrt" class="form-select" onchange="rsSrtChanged()">
                        <?php foreach (['NORMAL'=>'Normal (no EFD)','SUPPLIER_EFD_VAT'=>'Supplier EFD · VAT','SUPPLIER_EFD_NON_VAT'=>'Supplier EFD · Non-VAT'] as $k => $lbl): ?>
                            <option value="<?= $k; ?>" data-has-vat="<?= $k==='SUPPLIER_EFD_VAT'?1:0; ?>" <?= (($f['supplier_receipt_type'] ?? 'NORMAL')===$k?'selected':''); ?>><?= htmlspecialchars($lbl); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4" id="grpEfdNo" style="display:none;">
                    <label class="form-label">EFD receipt # *</label>
                    <input type="text" name="supplier_efd_number" class="form-control" value="<?= htmlspecialchars($f['supplier_efd_number'] ?? ''); ?>" placeholder="Number on the EFD print">
                </div>
                <div class="col-md-4" id="grpEfdTin" style="display:none;">
                    <label class="form-label">Supplier TIN</label>
                    <input type="text" name="supplier_tin" class="form-control" value="<?= htmlspecialchars($f['supplier_tin'] ?? ''); ?>" placeholder="e.g. 123-456-789">
                </div>
                <div class="col-md-4" id="grpEfdDate" style="display:none;">
                    <label class="form-label">EFD date</label>
                    <input type="date" name="supplier_efd_date" class="form-control" value="<?= htmlspecialchars($f['supplier_efd_date'] ?? ''); ?>">
                </div>
                <div class="col-md-4" id="grpVatIncl" style="display:none;">
                    <label class="form-label">VAT treatment</label>
                    <div class="form-check mt-1">
                        <input class="form-check-input" type="checkbox" name="vat_inclusive_flag" id="fldVatIncl" value="1" <?= !empty($f['vat_inclusive_flag'])?'checked':''; ?> onchange="rsAutoVat()">
                        <label class="form-check-label" for="fldVatIncl">Amount already includes VAT (18%)</label>
                    </div>
                    <div class="form-text">If unticked, VAT is added on top of Net.</div>
                </div>
                <div class="col-md-4" id="grpVatAmt" style="display:none;">
                    <label class="form-label">VAT amount (input VAT, claimable)</label>
                    <input type="number" step="0.01" min="0" name="vat_amount" id="fldVatAmt" class="form-control" value="<?= htmlspecialchars($f['vat_amount'] ?? '0'); ?>">
                    <div class="form-text">Auto-computed at 18% when you enable inclusive; edit if the receipt shows something else.</div>
                </div>
            </div>

            <div class="alert alert-info py-2 mt-3 mb-0 small">
                <i class="fas fa-info-circle me-1"></i>
                On save, this request becomes an <code>LPO</code> with type <strong>PETTY_CASH</strong> and is submitted into the
                <strong>PETTY_CASH_APPROVAL</strong> chain (PM Check → FM Approve). Once approved, it appears in the Accountant's
                Payables queue for PV preparation. If VAT is captured, the payment journal will split
                <code>Dr Expense (net) / Dr 8210 Input VAT / Cr Bank</code> automatically.
            </div>
        </div>
        <div class="card-footer bg-white text-end">
            <a href="<?= PROOT; ?>Lpos" 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-paper-plane me-1"></i> Raise & Submit
            </button>
        </div>
    </div>
</form>

<script>
function rsSrtChanged() {
    const sel = document.getElementById('fldSrt');
    const opt = sel.options[sel.selectedIndex];
    const hasEfd = sel.value !== 'NORMAL';
    const hasVat = opt.dataset.hasVat === '1';
    ['grpEfdNo','grpEfdTin','grpEfdDate'].forEach(id => document.getElementById(id).style.display = hasEfd ? '' : 'none');
    ['grpVatIncl','grpVatAmt'].forEach(id => document.getElementById(id).style.display = hasVat ? '' : 'none');
    if (!hasVat) { document.getElementById('fldVatAmt').value = 0; document.getElementById('fldVatIncl').checked = false; }
}
function rsAutoVat() {
    const incl = document.getElementById('fldVatIncl').checked;
    const amt  = parseFloat(document.querySelector('input[name="amount"]').value) || 0;
    if (!incl) { document.getElementById('fldVatAmt').value = 0; return; }
    // VAT-inclusive: VAT portion = amount × 18/118
    const vat = Math.round(amt * 18 / 118 * 100) / 100;
    document.getElementById('fldVatAmt').value = vat;
}
document.addEventListener('DOMContentLoaded', () => {
    rsSrtChanged();
    document.querySelector('input[name="amount"]').addEventListener('change', rsAutoVat);
});
</script>

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