<?php $this->start('body');
    $projects = $this->data['projects'] ?? [];
    $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-file-invoice me-2 text-muted"></i>Draft Invoice</h5>
    <a href="<?= PROOT; ?>Sales" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> All invoices</a>
</div>

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

<?php
    $cpo      = $this->data['cpo']       ?? null;
    $cpoItems = $this->data['cpo_items'] ?? [];
?>
<?php if ($cpo): ?>
<div class="alert alert-info py-2 mb-3 d-flex align-items-center justify-content-between">
    <div>
        <i class="fas fa-file-contract me-1"></i> Drafting from Client PO
        <a href="<?= PROOT; ?>GoodsClientPos/view/<?= (int)$cpo['c0d']; ?>"><strong><?= htmlspecialchars($cpo['client_po_no']); ?></strong></a>
        · Contract total: <?= htmlspecialchars($cpo['currency']); ?> <?= number_format((float)$cpo['total']); ?>
    </div>
    <a href="<?= PROOT; ?>Sales/draft" class="text-muted small">Clear PO link</a>
</div>
<?php endif; ?>

<form method="post" action="<?= PROOT; ?>Sales/save" autocomplete="off" id="rsInvoiceForm">
    <input type="hidden" name="client_po_id" value="<?= (int)($f['client_po_id'] ?? 0); ?>">
    <div class="card border-0 shadow-sm mb-3">
        <div class="card-header bg-white"><strong>Invoice header</strong></div>
        <div class="card-body p-3">
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label">Project *</label>
                    <select name="project_id" id="fldProject" class="form-select" required onchange="rsProjectChanged()">
                        <option value="">— select —</option>
                        <?php foreach ($projects as $p): ?>
                            <option value="<?= (int)$p['c0d']; ?>"
                                    data-cust-id="<?= (int)$p['project_customer_id']; ?>"
                                    data-cust-name="<?= htmlspecialchars($p['project_customer']); ?>"
                                    data-currency="<?= htmlspecialchars($p['currency']); ?>"
                                    data-source="<?= htmlspecialchars($p['project_type']); ?>"
                                    <?= (int)($f['project_id'] ?? 0)===(int)$p['c0d']?'selected':''; ?>>
                                <?= htmlspecialchars($p['project_no']); ?> · <?= htmlspecialchars($p['project_name']); ?> (<?= htmlspecialchars($p['project_customer']); ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <div class="form-text">Only projects that have passed CRM onboarding or are migrated appear here.</div>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Invoice date *</label>
                    <input type="date" name="invoice_date" class="form-control" value="<?= htmlspecialchars($f['invoice_date'] ?? date('Y-m-d')); ?>" required>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Due date</label>
                    <input type="date" name="due_date" class="form-control" value="<?= htmlspecialchars($f['due_date'] ?? ''); ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Currency</label>
                    <select name="currency" id="fldCurrency" 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-3">
                    <label class="form-label">VAT rate %</label>
                    <input type="number" step="0.01" name="vat_rate" id="fldVat" class="form-control" value="<?= htmlspecialchars($f['vat_rate'] ?? '18'); ?>" onchange="rsRecalc()">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Source module</label>
                    <select name="source_module" id="fldSource" class="form-select">
                        <?php foreach (['goods','services','works'] as $sm): ?>
                            <option value="<?= $sm; ?>" <?= (($f['source_module'] ?? 'goods')===$sm?'selected':''); ?>><?= ucfirst($sm); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Customer (auto)</label>
                    <input type="hidden" name="customer_id" id="fldCustomerId" value="<?= (int)($f['customer_id'] ?? 0); ?>">
                    <input type="text" id="fldCustomerName" class="form-control" value="" disabled>
                </div>

                <div class="col-12">
                    <label class="form-label">Narrative (optional)</label>
                    <textarea name="narrative" class="form-control" rows="2" placeholder="Any note that should appear on the invoice."><?= htmlspecialchars($f['narrative'] ?? ''); ?></textarea>
                </div>
            </div>
        </div>
    </div>

    <div class="card border-0 shadow-sm mb-3">
        <div class="card-header bg-white d-flex align-items-center justify-content-between">
            <strong>Line items</strong>
            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="rsAddLine()"><i class="fas fa-plus me-1"></i> Add line</button>
        </div>
        <div class="table-responsive">
            <table class="table table-sm mb-0 align-middle" id="rsItems">
                <thead class="table-light">
                    <tr>
                        <th style="width:40px;">#</th>
                        <th style="min-width:280px;">Description *</th>
                        <th style="width:110px;">Qty *</th>
                        <th style="width:90px;">Unit</th>
                        <th style="width:150px;">Unit price *</th>
                        <th style="width:160px;" class="text-end">Line total</th>
                        <th style="width:40px;"></th>
                    </tr>
                </thead>
                <tbody id="rsItemsBody">
                    <!-- rows injected by rsAddLine() -->
                </tbody>
                <tfoot class="table-light">
                    <tr>
                        <td colspan="5" class="text-end text-muted">Subtotal</td>
                        <td class="text-end" style="font-weight:600;" id="rsSubtotal">0</td>
                        <td></td>
                    </tr>
                    <tr>
                        <td colspan="5" class="text-end text-muted">VAT @ <span id="rsVatShow">18</span>%</td>
                        <td class="text-end text-muted" id="rsVat">0</td>
                        <td></td>
                    </tr>
                    <tr>
                        <td colspan="5" class="text-end" style="font-weight:600;">Total</td>
                        <td class="text-end" style="font-weight:700;font-size:1.05rem;" id="rsTotal">0</td>
                        <td></td>
                    </tr>
                </tfoot>
            </table>
        </div>
        <div class="card-footer bg-white text-end">
            <a href="<?= PROOT; ?>Sales" 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> Save as Draft
            </button>
        </div>
    </div>
</form>

<script>
let rsRow = 0;
function rsAddLine(desc='', qty='', unit='', unitPrice='') {
    rsRow++;
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td class="text-muted rs-rowno">${rsRow}</td>
      <td><input type="text"   name="item_description[]" class="form-control form-control-sm" value="${desc}"></td>
      <td><input type="number" step="0.0001" name="item_qty[]"        class="form-control form-control-sm rs-qty"  value="${qty}"   onchange="rsRecalc()"></td>
      <td><input type="text"   name="item_unit[]"       class="form-control form-control-sm" value="${unit}"></td>
      <td><input type="number" step="0.01"   name="item_unit_price[]" class="form-control form-control-sm rs-up"   value="${unitPrice}" onchange="rsRecalc()"></td>
      <td class="text-end rs-lt">0</td>
      <td class="text-end"><button type="button" class="btn btn-sm btn-outline-danger" onclick="this.closest('tr').remove(); rsRecalc();"><i class="fas fa-trash"></i></button></td>
    `;
    document.getElementById('rsItemsBody').appendChild(tr);
    rsRecalc();
}
function rsRecalc() {
    const rows = document.querySelectorAll('#rsItemsBody tr');
    let sub = 0;
    rows.forEach((tr, i) => {
        tr.querySelector('.rs-rowno').textContent = (i + 1);
        const q  = parseFloat(tr.querySelector('.rs-qty').value)  || 0;
        const up = parseFloat(tr.querySelector('.rs-up').value)   || 0;
        const lt = Math.round(q * up * 100) / 100;
        tr.querySelector('.rs-lt').textContent = lt.toLocaleString();
        sub += lt;
    });
    const vatRate = parseFloat(document.getElementById('fldVat').value) || 0;
    document.getElementById('rsVatShow').textContent = vatRate;
    const vat = Math.round(sub * vatRate / 100 * 100) / 100;
    document.getElementById('rsSubtotal').textContent = sub.toLocaleString();
    document.getElementById('rsVat').textContent      = vat.toLocaleString();
    document.getElementById('rsTotal').textContent    = (sub + vat).toLocaleString();
}
function rsProjectChanged() {
    const sel = document.getElementById('fldProject');
    const opt = sel.options[sel.selectedIndex];
    if (!opt || !opt.value) {
        document.getElementById('fldCustomerId').value = '';
        document.getElementById('fldCustomerName').value = '';
        return;
    }
    document.getElementById('fldCustomerId').value   = opt.dataset.custId || '';
    document.getElementById('fldCustomerName').value = opt.dataset.custName || '';
    document.getElementById('fldCurrency').value     = opt.dataset.currency || 'TZS';
    document.getElementById('fldSource').value       = opt.dataset.source   || 'goods';
}
// Prefill line items from Client PO if we came in from GoodsClientPos/view
const rsCpoItems = <?= json_encode(array_map(fn($it) => [
    'description' => (string)$it['description'],
    'qty'         => (float)$it['qty'],
    'unit'        => (string)$it['unit'],
    'unit_price'  => (float)$it['unit_price_sell'],
], $cpoItems)); ?>;
document.addEventListener('DOMContentLoaded', () => {
    if (rsCpoItems.length > 0) {
        rsCpoItems.forEach(it => rsAddLine(it.description, it.qty, it.unit, it.unit_price));
    } else {
        rsAddLine();
    }
    rsProjectChanged();
});
</script>

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