<?php $this->start('body');
    $p       = $this->data['project'];
    $groups  = $this->data['groups'] ?? [];
    $total   = 0.0; foreach ($groups as $g) if ($g['already_lpo_id'] === 0) $total += (float)$g['total'];
    $pending = 0;   foreach ($groups as $g) if ($g['already_lpo_id'] === 0) $pending++;
    $already = count($groups) - $pending;
?>
<div class="d-flex align-items-center justify-content-between mb-3">
    <div>
        <h5 class="mb-0" style="font-weight:600;"><i class="fas fa-file-invoice me-1 text-muted"></i>
            Draft supplier LPOs · <?= htmlspecialchars($p['project_no']); ?> · <?= htmlspecialchars($p['project_name']); ?>
        </h5>
        <div class="text-muted" style="font-size:.72rem;">
            <?= htmlspecialchars($p['project_customer']); ?> ·
            <span style="text-transform:capitalize;"><?= htmlspecialchars($p['project_type']); ?></span> ·
            <?= htmlspecialchars($p['currency']); ?> <?= number_format((float)$p['contract_value']); ?>
        </div>
    </div>
    <a href="<?= PROOT; ?>ProjectStarter/index/<?= (int)$p['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> Back to checklist</a>
</div>

<?php if (empty($groups)): ?>
    <div class="alert py-3" style="background:#F8FAFC;border:1px solid #E2E8F0;color:#334155;">
        <i class="fas fa-info-circle me-1" style="color:#7A8BA1;"></i>
        <strong>Nothing to draft yet.</strong>
        No awarded RFQ quotes found for this project. Complete the <a href="<?= PROOT; ?>GoodsRfq/fromProject/<?= (int)$p['c0d']; ?>" style="color:#7A8BA1;font-weight:600;">RFQ assessment</a> and award at least one supplier line first.
    </div>
<?php else: ?>

<div class="card border-0 shadow-sm mb-3">
    <div class="card-body p-3 d-flex align-items-center justify-content-between">
        <div>
            <div style="text-transform:uppercase;letter-spacing:.4px;font-size:.66rem;color:#64748B;">Ready to draft</div>
            <div style="color:#334155;">
                <strong><?= $pending; ?></strong> supplier LPO<?= $pending === 1 ? '' : 's' ?> ·
                total <strong><?= htmlspecialchars($p['currency']); ?> <?= number_format($total); ?></strong>
                <?php if ($already > 0): ?>
                    <span class="text-muted small">· <?= $already; ?> already drafted (will be skipped)</span>
                <?php endif; ?>
            </div>
        </div>
        <?php if ($pending > 0): ?>
        <button type="button" id="btn_draft_batch" class="btn btn-sm" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;">
            <i class="fas fa-magic me-1"></i> Create <?= $pending; ?> draft LPO<?= $pending === 1 ? '' : 's' ?>
        </button>
        <?php endif; ?>
    </div>
</div>

<?php foreach ($groups as $i => $g):
    $isDone = $g['already_lpo_id'] > 0;
?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white d-flex align-items-center justify-content-between" style="border-bottom:1px solid #E2E8F0;">
        <div>
            <strong style="color:#334155;">
                <i class="fas fa-truck me-2" style="color:#7A8BA1;"></i>
                Supplier · <?= htmlspecialchars($g['vendor_name']); ?>
            </strong>
            <?php if ($g['vendor_tin']): ?><span class="text-muted small ms-2">TIN <?= htmlspecialchars($g['vendor_tin']); ?></span><?php endif; ?>
            <div class="text-muted small mt-1" style="font-size:.72rem;">
                From RFQ #<?= (int)$g['rfq_id']; ?> · client PO #<?= (int)$g['client_po_id']; ?> · <?= count($g['lines']); ?> line<?= count($g['lines']) === 1 ? '' : 's' ?>
            </div>
        </div>
        <div class="text-end">
            <?php if ($isDone): ?>
                <span class="badge" style="background:#7A9E7E;color:#fff;font-size:.68rem;">Already drafted</span>
                <div class="small mt-1"><a href="<?= PROOT; ?>Lpos/view/<?= (int)$g['already_lpo_id']; ?>"><?= htmlspecialchars($g['already_lpo_no']); ?></a></div>
            <?php else: ?>
                <div style="color:#334155;font-size:1.05rem;font-weight:600;"><?= number_format((float)$g['total']); ?></div>
                <div class="text-muted small" style="font-size:.66rem;text-transform:uppercase;letter-spacing:.4px;">line total</div>
            <?php endif; ?>
        </div>
    </div>
    <div class="card-body p-0">
        <table class="table table-sm mb-0 align-middle">
            <thead style="background:#F1F5F9;">
                <tr>
                    <th style="width:50px;">#</th>
                    <th>Item</th>
                    <th style="width:90px;">Qty</th>
                    <th style="width:70px;">UoM</th>
                    <th style="width:120px;" class="text-end">Unit price</th>
                    <th style="width:130px;" class="text-end">Line total</th>
                    <th style="width:80px;">Lead</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($g['lines'] as $ln): ?>
                    <tr>
                        <td class="text-muted"><?= (int)$ln['item_no']; ?></td>
                        <td><?= htmlspecialchars($ln['description']); ?></td>
                        <td><?= number_format((float)$ln['qty'], 2); ?></td>
                        <td><?= htmlspecialchars($ln['unit']); ?></td>
                        <td class="text-end"><?= number_format((float)$ln['unit_price']); ?></td>
                        <td class="text-end"><strong><?= number_format((float)$ln['line_total']); ?></strong></td>
                        <td class="text-muted small"><?= $ln['lead_time_days'] > 0 ? ($ln['lead_time_days'] . 'd') : '—'; ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endforeach; ?>

<div class="alert py-2 mb-3" style="background:#F8FAFC;border:1px solid #E2E8F0;color:#64748B;font-size:.78rem;">
    <i class="fas fa-info-circle me-1" style="color:#7A8BA1;"></i>
    After creation each LPO lands in <strong>DRAFT</strong> status. Open it in the LPO register to submit for the <code>GOODS_LPO_APPROVAL</code> chain (PC → PM → FM → Exec).
</div>

<?php endif; ?>

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

<?php $this->start('section_js'); ?>
<script>
$('#btn_draft_batch').on('click', function () {
    var $btn = $(this).prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i>Creating…');
    $.post('<?= PROOT; ?>Lpos/draftBatchAj', { project_id: <?= (int)$p['c0d']; ?> }, 'json')
        .done(function (res) {
            if (res && res.ok) {
                if (typeof rsToast === 'function') rsToast(res.msg, 'success');
                else alert(res.msg);
                setTimeout(function () { location.reload(); }, 700);
            } else {
                alert('Failed: ' + (res.msg || 'unknown'));
                $btn.prop('disabled', false).html('<i class="fas fa-magic me-1"></i> Create draft LPOs');
            }
        })
        .fail(function () {
            alert('Network error');
            $btn.prop('disabled', false).html('<i class="fas fa-magic me-1"></i> Create draft LPOs');
        });
});
</script>
<?php $this->end(); ?>
