<?php $this->start('body');
    $pack  = $this->data['pack'];
    $items = $this->data['items'] ?? [];
    $parts = $this->data['parts'] ?? [];
    // Group items by interval
    $byInterval = [];
    foreach ($items as $it) {
        $key = ($it['interval_hrs'] !== null) ? ((int)$it['interval_hrs'] . ' hrs') : ((int)$it['interval_months'] . ' months');
        $byInterval[$key][] = $it;
    }
    ksort($byInterval);
?>
<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-boxes-stacked me-2 text-muted"></i><?= htmlspecialchars($pack['code']); ?></h5>
        <div class="text-muted small mt-1" style="font-size:.72rem;">
            <?= htmlspecialchars($pack['name']); ?>
            &middot; <i class="fas <?= htmlspecialchars((string)$pack['asset_icon']); ?>"></i> <?= htmlspecialchars((string)$pack['asset_type_code']); ?>
            <?php if ($pack['size_min'] !== null || $pack['size_max'] !== null): ?>
                &middot; <?= $pack['size_min'] !== null ? number_format((float)$pack['size_min']) : ''; ?> – <?= $pack['size_max'] !== null ? number_format((float)$pack['size_max']) : ''; ?> <?= htmlspecialchars((string)$pack['size_unit']); ?>
            <?php endif; ?>
        </div>
    </div>
    <div class="d-flex gap-2">
        <button type="button" id="btn_add_item" class="btn btn-sm" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;"><i class="fas fa-plus me-1"></i>Add item</button>
        <a href="<?= PROOT; ?>ServicePacks" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back</a>
    </div>
</div>

<?php foreach ($byInterval as $interval => $rows):
    $intervalCost = 0.0;
    foreach ($rows as $r) $intervalCost += (float)$r['line_cost'];
?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header py-2 d-flex justify-content-between align-items-center" style="background:#F8FAFC;border-bottom:1px solid #E2E8F0;">
        <strong style="font-weight:600;color:#334155;font-size:.85rem;">Interval: <?= htmlspecialchars($interval); ?></strong>
        <span class="text-muted small">Sub-total: <strong style="color:#334155;">TZS <?= number_format($intervalCost); ?></strong></span>
    </div>
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light"><tr><th>SKU</th><th>Part</th><th class="text-end">Qty</th><th>UoM</th><th class="text-end">Unit cost</th><th class="text-end">Line cost</th><th>Notes</th><th></th></tr></thead>
            <tbody>
                <?php foreach ($rows as $it): ?>
                    <tr data-id="<?= (int)$it['c0d']; ?>" data-json='<?= htmlspecialchars(json_encode($it), ENT_QUOTES); ?>'>
                        <td class="small"><code><?= htmlspecialchars((string)$it['sku']); ?></code></td>
                        <td class="small"><?= htmlspecialchars((string)$it['part_name']); ?></td>
                        <td class="text-end small"><?= number_format((float)$it['qty'], (fmod((float)$it['qty'],1)==0?0:2)); ?></td>
                        <td class="small text-muted"><?= htmlspecialchars((string)$it['uom']); ?></td>
                        <td class="text-end small text-muted"><?= $it['unit_cost'] !== null ? number_format((float)$it['unit_cost']) : '—'; ?></td>
                        <td class="text-end small" style="font-weight:600;"><?= number_format((float)$it['line_cost']); ?></td>
                        <td class="small text-muted"><?= htmlspecialchars((string)($it['notes'] ?? '')); ?></td>
                        <td class="text-end">
                            <button type="button" class="btn btn-sm btn-link p-0 pk_del text-danger"><i class="fas fa-times"></i></button>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endforeach; ?>

<?php if (empty($items)): ?>
<div class="card border-0 shadow-sm"><div class="card-body p-4 text-center text-muted small">No items yet — click <strong>Add item</strong> to bind spare parts to service intervals.</div></div>
<?php endif; ?>

<script>
(function () {
    var PACK_ID = <?= (int)$pack['c0d']; ?>;
    var PROOT   = '<?= PROOT; ?>';
    var PARTS   = <?= json_encode(array_map(fn($p) => ['c0d'=>(int)$p['c0d'],'sku'=>$p['sku'],'name'=>$p['name']], $parts)); ?>;
    function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]); }); }
    document.getElementById('btn_add_item').addEventListener('click', function () {
        var partOpts = PARTS.map(function (p) { return '<option value="' + p.c0d + '">' + esc(p.sku + ' · ' + p.name) + '</option>'; }).join('');
        $.confirm({
            title:'Add pack item', columnClass:'col-md-6', type:'green',
            content: '<form id="pi_form">' +
                '<input type="hidden" name="pack_id" value="' + PACK_ID + '">' +
                '<div class="mb-2"><label class="form-label small">Part *</label><select name="part_id" class="form-select form-select-sm" required>' + (partOpts || '<option value="">— no parts for this asset type yet —</option>') + '</select></div>' +
                '<div class="row g-2 mb-2">' +
                  '<div class="col-4"><label class="form-label small">Interval hrs</label><input name="interval_hrs" type="number" min="0" class="form-control form-control-sm" placeholder="250, 500, 1000"></div>' +
                  '<div class="col-4"><label class="form-label small">OR months</label><input name="interval_months" type="number" min="0" class="form-control form-control-sm" placeholder="3, 6, 12"></div>' +
                  '<div class="col-4"><label class="form-label small">Qty *</label><input name="qty" type="number" step="0.01" min="0" class="form-control form-control-sm" value="1" required></div>' +
                '</div>' +
                '<div class="mb-2"><label class="form-label small">Notes</label><input name="notes" class="form-control form-control-sm"></div>' +
            '</form>',
            buttons: {
                save: { text:'Add', btnClass:'btn-success', action: function () {
                    var f = document.getElementById('pi_form');
                    var p = { pack_id: f.pack_id.value, part_id: f.part_id.value, interval_hrs: f.interval_hrs.value, interval_months: f.interval_months.value, qty: f.qty.value, notes: f.notes.value };
                    $.post(PROOT + 'ServicePacks/saveItemAj', p, function (r) {
                        if (r && r.ok) { rsToast('Added.','success'); setTimeout(function(){location.reload();}, 400); }
                        else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json');
                }}, cancel: function () {}
            }
        });
    });
    document.querySelectorAll('.pk_del').forEach(function (b) {
        b.addEventListener('click', function () {
            var tr = b.closest('tr'); var data = JSON.parse(tr.getAttribute('data-json'));
            $.confirm({ title:'Remove?', type:'red', content: esc(data.sku + ' · ' + data.part_name), buttons: {
                yes: { text:'Remove', btnClass:'btn-danger', action: function () {
                    $.post(PROOT + 'ServicePacks/deleteItemAj', { id: data.c0d }, function (r) {
                        if (r && r.ok) { rsToast('Removed.','success'); setTimeout(function(){location.reload();}, 300); }
                        else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json');
                }}, cancel: function () {}
            }});
        });
    });
})();
</script>
<?php $this->end(); ?>
