<?php $this->start('body');
    $rows   = $this->data['rows']   ?? [];
    $types  = $this->data['asset_types'] ?? [];
    $filter = $this->data['filter_at'];
?>
<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>Service Packs
            <span class="text-muted ms-2" style="font-weight:400;font-size:.7rem;"><?= count($rows); ?> packs</span>
        </h5>
        <div class="text-muted small mt-1" style="font-size:.72rem;">Spares BOM per (asset type × size range × service interval). Assets auto-match by size.</div>
    </div>
    <div class="d-flex gap-2 align-items-center">
        <form method="get" action="<?= PROOT; ?>ServicePacks" class="d-flex align-items-center gap-2" style="font-size:.75rem;">
            <select name="asset_type_id" class="form-select form-select-sm" style="width:auto;" onchange="this.form.submit()">
                <option value="">All types</option>
                <?php foreach ($types as $t): ?>
                    <option value="<?= (int)$t['c0d']; ?>" <?= ($filter !== null && (int)$filter === (int)$t['c0d']) ? 'selected' : ''; ?>><?= htmlspecialchars($t['code'] . ' · ' . $t['name']); ?></option>
                <?php endforeach; ?>
            </select>
        </form>
        <button type="button" class="btn btn-sm" id="btn_add" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;"><i class="fas fa-plus me-1"></i>New pack</button>
    </div>
</div>

<div class="card border-0 shadow-sm">
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light"><tr><th>Code</th><th>Name</th><th>Asset type</th><th>Size range</th><th class="text-end">Items</th><th class="text-end">Pack cost</th><th>Status</th><th></th></tr></thead>
            <tbody>
                <?php foreach ($rows as $r):
                    $sizeRange = '';
                    if ($r['size_min'] !== null || $r['size_max'] !== null) {
                        $sizeRange = ($r['size_min'] !== null ? number_format((float)$r['size_min']) : '') . ' – ' . ($r['size_max'] !== null ? number_format((float)$r['size_max']) : '') . ' ' . $r['size_unit'];
                    }
                ?>
                    <tr>
                        <td class="small"><strong><?= htmlspecialchars($r['code']); ?></strong></td>
                        <td class="small"><?= htmlspecialchars($r['name']); ?></td>
                        <td class="small text-muted"><?php if (!empty($r['asset_icon'])): ?><i class="fas <?= htmlspecialchars($r['asset_icon']); ?> me-1"></i><?php endif; ?><?= htmlspecialchars((string)($r['asset_type_code'] ?? '—')); ?></td>
                        <td class="small text-muted"><?= htmlspecialchars($sizeRange ?: '—'); ?></td>
                        <td class="text-end small"><?= (int)$r['item_count']; ?></td>
                        <td class="text-end small text-muted"><?= number_format((float)$r['pack_cost_total']); ?></td>
                        <td><?= (int)$r['is_active'] === 1 ? '<span class="badge bg-success" style="font-size:.6rem;">Active</span>' : '<span class="badge bg-light text-muted" style="font-size:.6rem;">Inactive</span>'; ?></td>
                        <td class="text-end"><a href="<?= PROOT; ?>ServicePacks/view/<?= (int)$r['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-right"></i></a></td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($rows)): ?><tr><td colspan="8" class="text-center text-muted py-4">No packs yet.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
(function () {
    var PROOT = '<?= PROOT; ?>';
    var TYPES = <?= json_encode(array_map(fn($t) => ['c0d'=>(int)$t['c0d'],'code'=>$t['code'],'name'=>$t['name']], $types)); ?>;
    function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]); }); }
    document.getElementById('btn_add').addEventListener('click', function () {
        var typeOpts = TYPES.map(function (t) { return '<option value="' + t.c0d + '">' + esc(t.code + ' · ' + t.name) + '</option>'; }).join('');
        $.confirm({
            title:'New Service Pack', columnClass:'col-md-6', type:'green',
            content: '<form id="pk_form">' +
                '<div class="row g-2 mb-2">' +
                  '<div class="col-4"><label class="form-label small">Code *</label><input name="code" class="form-control form-control-sm" required></div>' +
                  '<div class="col-8"><label class="form-label small">Name *</label><input name="name" class="form-control form-control-sm" required></div>' +
                '</div>' +
                '<div class="mb-2"><label class="form-label small">Asset type *</label><select name="asset_type_id" class="form-select form-select-sm" required>' + typeOpts + '</select></div>' +
                '<div class="row g-2 mb-2">' +
                  '<div class="col-4"><label class="form-label small">Size min</label><input name="size_min" type="number" min="0" class="form-control form-control-sm"></div>' +
                  '<div class="col-4"><label class="form-label small">Size max</label><input name="size_max" type="number" min="0" class="form-control form-control-sm"></div>' +
                  '<div class="col-4"><label class="form-label small">Unit</label><input name="size_unit" class="form-control form-control-sm" value="kVA"></div>' +
                '</div>' +
                '<div class="mb-2"><label class="form-label small">Description</label><input name="description" class="form-control form-control-sm"></div>' +
                '<div class="form-check"><input type="checkbox" name="is_active" class="form-check-input" checked><label class="form-check-label small">Active</label></div>' +
            '</form>',
            buttons: {
                save: { text:'Create', btnClass:'btn-success', action: function () {
                    var f = document.getElementById('pk_form');
                    var p = { code: f.code.value, name: f.name.value, asset_type_id: f.asset_type_id.value, size_min: f.size_min.value, size_max: f.size_max.value, size_unit: f.size_unit.value, description: f.description.value, is_active: f.is_active.checked ? 1 : 0 };
                    $.post(PROOT + 'ServicePacks/saveHeaderAj', p, function (r) {
                        if (r && r.ok) { rsToast('Created.','success'); setTimeout(function(){window.location.href = PROOT + 'ServicePacks/view/' + r.id;}, 500); }
                        else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json');
                }}, cancel: function () {}
            }
        });
    });
})();
</script>
<?php $this->end(); ?>
