<?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-contract me-2 text-muted"></i>New Client PO</h5>
    <a href="<?= PROOT; ?>GoodsClientPos" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> Back</a>
</div>

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

<form method="post" action="<?= PROOT; ?>GoodsClientPos/save" autocomplete="off" id="rsCpoForm">
    <div class="card border-0 shadow-sm mb-3">
        <div class="card-header bg-white"><strong>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']); ?>"
                                    data-margin="<?= htmlspecialchars($p['default_margin_pct']); ?>"
                                    <?= (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>
                <div class="col-md-3"><label class="form-label">PO date *</label><input type="date" name="po_date" class="form-control" required value="<?= htmlspecialchars($f['po_date'] ?? date('Y-m-d')); ?>"></div>
                <div class="col-md-3"><label class="form-label">Delivery by</label><input type="date" name="delivery_by" class="form-control" value="<?= htmlspecialchars($f['delivery_by'] ?? ''); ?>"></div>

                <div class="col-md-4"><label class="form-label">Customer PO ref</label><input type="text" name="customer_po_ref" class="form-control" placeholder="Their PO number" value="<?= htmlspecialchars($f['customer_po_ref'] ?? ''); ?>"></div>
                <div class="col-md-2">
                    <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-2">
                    <label class="form-label">VAT %</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-2">
                    <label class="form-label">Default margin %</label>
                    <input type="number" step="0.01" name="default_margin_pct" id="fldMargin" class="form-control" value="<?= htmlspecialchars($f['default_margin_pct'] ?? '25'); ?>" onchange="rsMarginChanged()">
                </div>
                <div class="col-md-2">
                    <label class="form-label">Source</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-4"><label class="form-label">Payment terms</label><input type="text" name="payment_terms" class="form-control" placeholder="e.g. 30 days net" value="<?= htmlspecialchars($f['payment_terms'] ?? ''); ?>"></div>
                <div class="col-md-4"><label class="form-label">Delivery POC</label><input type="text" name="delivery_poc" class="form-control" value="<?= htmlspecialchars($f['delivery_poc'] ?? ''); ?>"></div>
                <div class="col-md-4"><label class="form-label">POC phone</label><input type="text" name="delivery_poc_phone" class="form-control" value="<?= htmlspecialchars($f['delivery_poc_phone'] ?? ''); ?>"></div>
                <div class="col-12"><label class="form-label">Delivery address</label><textarea name="delivery_address" class="form-control" rows="2"><?= htmlspecialchars($f['delivery_address'] ?? ''); ?></textarea></div>

                <input type="hidden" name="customer_id" id="fldCustomerId" value="<?= (int)($f['customer_id'] ?? 0); ?>">
            </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>
            <div>
                <button type="button" class="btn btn-sm btn-outline-secondary me-1" onclick="rsSuggestCog()" title="Auto-fill Cog = Sell × (1 − margin%)">
                    <i class="fas fa-magic me-1"></i> Suggest Cog from margin
                </button>
                <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>
        <div class="table-responsive">
            <table class="table table-sm mb-0 align-middle">
                <thead class="table-light">
                    <tr>
                        <th style="width:40px;">#</th>
                        <th style="min-width:260px;">Description *</th>
                        <th style="width:100px;">Qty *</th>
                        <th style="width:70px;">Unit</th>
                        <th style="width:130px;">Sell price *</th>
                        <th style="width:130px;">Cog (planned)</th>
                        <th style="width:110px;" class="text-end">Line sell</th>
                        <th style="width:80px;" class="text-end">Margin</th>
                        <th style="width:40px;"></th>
                    </tr>
                </thead>
                <tbody id="rsItemsBody"></tbody>
                <tfoot class="table-light">
                    <tr>
                        <td colspan="6" class="text-end text-muted">Subtotal (sell)</td>
                        <td class="text-end" style="font-weight:600;" id="rsSubSell">0</td>
                        <td></td><td></td>
                    </tr>
                    <tr>
                        <td colspan="6" class="text-end text-muted">Subtotal (planned cog)</td>
                        <td class="text-end text-muted" id="rsSubCog">0</td>
                        <td class="text-end" style="font-weight:600;" id="rsOverallMargin">0%</td>
                        <td></td>
                    </tr>
                    <tr>
                        <td colspan="6" class="text-end text-muted">VAT @ <span id="rsVatShow">18</span>%</td>
                        <td class="text-end text-muted" id="rsVat">0</td>
                        <td></td><td></td>
                    </tr>
                    <tr>
                        <td colspan="6" class="text-end" style="font-weight:600;">Total (incl VAT)</td>
                        <td class="text-end" style="font-weight:700;font-size:1.05rem;" id="rsTotal">0</td>
                        <td></td><td></td>
                    </tr>
                </tfoot>
            </table>
        </div>
        <div class="card-footer bg-white text-end">
            <a href="<?= PROOT; ?>GoodsClientPos" 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 Client PO
            </button>
        </div>
    </div>
</form>

<script>
let rsRow = 0;
function rsAddLine(desc='', qty='', unit='', sell='', cog='') {
    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_sell[]" class="form-control form-control-sm rs-sell" value="${sell}" onchange="rsRecalc()"></td>
      <td><input type="number" step="0.01"   name="item_unit_price_cog[]"  class="form-control form-control-sm rs-cog"  value="${cog}"  onchange="rsRecalc()"></td>
      <td class="text-end rs-lt">0</td>
      <td class="text-end rs-lmg">—</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 subSell = 0, subCog = 0;
    rows.forEach((tr, i) => {
        tr.querySelector('.rs-rowno').textContent = (i + 1);
        const q  = parseFloat(tr.querySelector('.rs-qty').value)  || 0;
        const s  = parseFloat(tr.querySelector('.rs-sell').value) || 0;
        const c  = parseFloat(tr.querySelector('.rs-cog').value)  || 0;
        const ls = Math.round(q * s * 100) / 100;
        const lc = Math.round(q * c * 100) / 100;
        subSell += ls;
        subCog  += lc;
        tr.querySelector('.rs-lt').textContent = ls.toLocaleString();
        tr.querySelector('.rs-lmg').textContent = (ls > 0) ? (((ls - lc) / ls) * 100).toFixed(1) + '%' : '—';
    });
    const vRate = parseFloat(document.getElementById('fldVat').value) || 0;
    document.getElementById('rsVatShow').textContent = vRate;
    const vat = Math.round(subSell * vRate / 100 * 100) / 100;
    document.getElementById('rsSubSell').textContent = subSell.toLocaleString();
    document.getElementById('rsSubCog').textContent  = subCog.toLocaleString();
    document.getElementById('rsOverallMargin').textContent = subSell > 0 ? (((subSell - subCog) / subSell) * 100).toFixed(1) + '%' : '—';
    document.getElementById('rsVat').textContent   = vat.toLocaleString();
    document.getElementById('rsTotal').textContent = (subSell + vat).toLocaleString();
}
function rsSuggestCog() {
    const mgn = parseFloat(document.getElementById('fldMargin').value) || 0;
    const factor = (100 - mgn) / 100;
    document.querySelectorAll('#rsItemsBody tr').forEach(tr => {
        const cogInp = tr.querySelector('.rs-cog');
        if (!cogInp.value || parseFloat(cogInp.value) === 0) {
            const sell = parseFloat(tr.querySelector('.rs-sell').value) || 0;
            cogInp.value = Math.round(sell * factor * 100) / 100;
        }
    });
    rsRecalc();
}
function rsMarginChanged() { /* triggers on-demand — no auto-recompute */ }
function rsProjectChanged() {
    const sel = document.getElementById('fldProject');
    const opt = sel.options[sel.selectedIndex];
    if (!opt || !opt.value) return;
    document.getElementById('fldCustomerId').value = opt.dataset.custId || '';
    document.getElementById('fldCurrency').value   = opt.dataset.currency || 'TZS';
    document.getElementById('fldSource').value     = opt.dataset.source   || 'goods';
    document.getElementById('fldMargin').value     = opt.dataset.margin   || 25;
}
document.addEventListener('DOMContentLoaded', () => { rsAddLine(); rsProjectChanged(); });
</script>

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