<?php $this->start('body');
    $rows   = $this->data['rows']   ?? [];
    $types  = $this->data['asset_types'] ?? [];
    $filter = $this->data['filter_at'];
    $search = (string)($this->data['search'] ?? '');
?>
<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-cogs me-2 text-muted"></i>Spare Parts Catalogue
            <span class="text-muted ms-2" style="font-weight:400;font-size:.7rem;"><?= count($rows); ?> parts</span>
        </h5>
    </div>
    <div class="d-flex gap-2 align-items-center">
        <form method="get" action="<?= PROOT; ?>SpareParts" 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;">
                <option value="">All types</option>
                <?php foreach ($types as $t): ?>
                    <option value="<?= (int)$t['c0d']; ?>" <?= ((int)$filter === (int)$t['c0d']) ? 'selected' : ''; ?>><?= htmlspecialchars($t['code'] . ' · ' . $t['name']); ?></option>
                <?php endforeach; ?>
            </select>
            <input name="q" class="form-control form-control-sm" placeholder="SKU / name" value="<?= htmlspecialchars($search); ?>" style="max-width:200px;">
            <button class="btn btn-sm btn-outline-secondary"><i class="fas fa-search"></i></button>
        </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>Add part</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>SKU</th><th>Name</th><th>Asset type</th><th>Category</th><th class="text-end">Unit cost</th><th>UoM</th><th class="text-end">Markup</th><th>Status</th><th></th></tr></thead>
            <tbody id="sp_body">
                <?php foreach ($rows as $r): ?>
                    <tr data-id="<?= (int)$r['c0d']; ?>" data-json='<?= htmlspecialchars(json_encode($r), ENT_QUOTES); ?>'>
                        <td class="small"><strong><?= htmlspecialchars($r['sku']); ?></strong></td>
                        <td class="small"><?= htmlspecialchars($r['name']); ?><?php if (!empty($r['description'])): ?><div class="text-muted" style="font-size:.6rem;"><?= htmlspecialchars(mb_strimwidth((string)$r['description'], 0, 60, '…')); ?></div><?php endif; ?></td>
                        <td class="small text-muted"><?= htmlspecialchars((string)($r['asset_type_code'] ?? '—')); ?></td>
                        <td class="small text-muted"><?= htmlspecialchars((string)($r['category'] ?? '—')); ?></td>
                        <td class="text-end small"><?= $r['unit_cost'] !== null ? htmlspecialchars((string)$r['currency']) . ' ' . number_format((float)$r['unit_cost']) : '—'; ?></td>
                        <td class="small text-muted"><?= htmlspecialchars((string)$r['uom']); ?></td>
                        <td class="text-end small text-muted"><?= number_format((float)$r['default_markup_pct'], 1); ?>%</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">
                            <button type="button" class="btn btn-sm btn-link p-0 me-2 sp_edit"><i class="fas fa-pen" style="color:#7A8BA1;"></i></button>
                            <button type="button" class="btn btn-sm btn-link p-0 sp_del text-danger"><i class="fas fa-times"></i></button>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($rows)): ?><tr><td colspan="9" class="text-center text-muted py-4">No parts.</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]); }); }
    function form(d) {
        d = d || {};
        var typeOpts = '<option value="">— unassigned —</option>' + TYPES.map(function (t) {
            return '<option value="' + t.c0d + '"' + ((d.asset_type_id == t.c0d) ? ' selected' : '') + '>' + esc(t.code + ' · ' + t.name) + '</option>';
        }).join('');
        return '<form id="sp_form">' +
            '<input type="hidden" name="c0d" value="' + (d.c0d || '') + '">' +
            '<div class="row g-2 mb-2">' +
              '<div class="col-4"><label class="form-label small">SKU *</label><input name="sku" class="form-control form-control-sm" value="' + esc(d.sku||'') + '" required></div>' +
              '<div class="col-8"><label class="form-label small">Name *</label><input name="name" class="form-control form-control-sm" value="' + esc(d.name||'') + '" required></div>' +
            '</div>' +
            '<div class="mb-2"><label class="form-label small">Description</label><input name="description" class="form-control form-control-sm" value="' + esc(d.description||'') + '"></div>' +
            '<div class="row g-2 mb-2">' +
              '<div class="col-6"><label class="form-label small">Asset type</label><select name="asset_type_id" class="form-select form-select-sm">' + typeOpts + '</select></div>' +
              '<div class="col-6"><label class="form-label small">Category</label><input name="category" class="form-control form-control-sm" value="' + esc(d.category||'') + '" placeholder="oil/filter/cable…"></div>' +
            '</div>' +
            '<div class="row g-2 mb-2">' +
              '<div class="col-3"><label class="form-label small">Unit cost</label><input name="unit_cost" type="number" step="0.01" min="0" class="form-control form-control-sm" value="' + (d.unit_cost || '') + '"></div>' +
              '<div class="col-3"><label class="form-label small">Currency</label><input name="currency" class="form-control form-control-sm" value="' + (d.currency || 'TZS') + '"></div>' +
              '<div class="col-3"><label class="form-label small">UoM</label><input name="uom" class="form-control form-control-sm" value="' + (d.uom || 'ea') + '"></div>' +
              '<div class="col-3"><label class="form-label small">Markup %</label><input name="default_markup_pct" type="number" step="0.01" min="0" class="form-control form-control-sm" value="' + (d.default_markup_pct || 25) + '"></div>' +
            '</div>' +
            '<div class="form-check"><input type="checkbox" name="is_active" class="form-check-input" ' + (parseInt(d.is_active||1)===1?'checked':'') + '><label class="form-check-label small">Active</label></div>' +
        '</form>';
    }
    function save(d) {
        $.confirm({ title: d && d.c0d ? 'Edit part' : 'Add part', columnClass:'col-md-7', content: form(d), type:'green', buttons: {
            save: { text:'Save', btnClass:'btn-success', action: function () {
                var f = document.getElementById('sp_form');
                var p = {
                    c0d: f.c0d.value, sku: f.sku.value, name: f.name.value, description: f.description.value,
                    asset_type_id: f.asset_type_id.value, category: f.category.value,
                    unit_cost: f.unit_cost.value, currency: f.currency.value, uom: f.uom.value,
                    default_markup_pct: f.default_markup_pct.value,
                    is_active: f.is_active.checked ? 1 : 0
                };
                $.post(PROOT + 'SpareParts/saveAj', p, function (r) {
                    if (r && r.ok) { rsToast('Saved.','success'); setTimeout(function(){location.reload();}, 400); }
                    else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                }, 'json');
            }}, cancel: function () {}
        }});
    }
    document.getElementById('btn_add').addEventListener('click', function () { save({}); });
    document.getElementById('sp_body').addEventListener('click', function (e) {
        var editB = e.target.closest('.sp_edit'), delB = e.target.closest('.sp_del');
        if (!editB && !delB) return;
        var tr = (editB || delB).closest('tr');
        var data = JSON.parse(tr.getAttribute('data-json'));
        if (editB) { save(data); return; }
        $.confirm({ title:'Remove part?', type:'red', content:'<code>' + esc(data.sku) + '</code>', buttons: {
            yes: { text:'Remove', btnClass:'btn-danger', action: function () {
                $.post(PROOT + 'SpareParts/deleteAj', { 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(); ?>
