<?php
require_once __DIR__ . '/../../includes/functions.php';
requireLogin();

// ── AJAX handler ─────────────────────────────────────────────
if (($_GET['ajax'] ?? '') === 'quick_add') {
    header('Content-Type: application/json');
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        echo json_encode(['success'=>false,'error'=>'Invalid token']); exit;
    }
    $type = $_POST['type'] ?? '';

    if ($type === 'category') {
        $name = trim($_POST['name'] ?? '');
        if (!$name) { echo json_encode(['success'=>false,'error'=>'Name required']); exit; }
        $pdo->prepare("INSERT IGNORE INTO categories (category_name) VALUES (?)")->execute([$name]);
        $id = $pdo->lastInsertId() ?: $pdo->query("SELECT id FROM categories WHERE category_name=".$pdo->quote($name))->fetchColumn();
        echo json_encode(['success'=>true,'id'=>$id,'name'=>$name]); exit;
    }
    if ($type === 'brand') {
        $name = trim($_POST['name'] ?? '');
        $catId = (int)($_POST['category_id'] ?? 0);
        if (!$name) { echo json_encode(['success'=>false,'error'=>'Name required']); exit; }
        $pdo->prepare("INSERT IGNORE INTO item_brands (brand_name, category_id) VALUES (?,?)")->execute([$name, $catId ?: null]);
        $id = $pdo->lastInsertId() ?: $pdo->query("SELECT id FROM item_brands WHERE brand_name=".$pdo->quote($name)." AND category_id=".($catId ?: 'NULL'))->fetchColumn();
        echo json_encode(['success'=>true,'id'=>$id,'name'=>$name]); exit;
    }
    if ($type === 'model') {
        $name = trim($_POST['name'] ?? '');
        $brandId = (int)($_POST['brand_id'] ?? 0);
        if (!$name || !$brandId) { echo json_encode(['success'=>false,'error'=>'Brand and name required']); exit; }
        $pdo->prepare("INSERT INTO item_models (brand_id, model_name) VALUES (?,?)")->execute([$brandId, $name]);
        $id = $pdo->lastInsertId();
        echo json_encode(['success'=>true,'id'=>$id,'name'=>$name]); exit;
    }
    if ($type === 'config') {
        $name = trim($_POST['name'] ?? '');
        $catId = (int)($_POST['category_id'] ?? 0);
        if (!$name || !$catId) { echo json_encode(['success'=>false,'error'=>'Category and name required']); exit; }
        $pdo->prepare("INSERT IGNORE INTO item_configurations (category_id, config_name) VALUES (?,?)")->execute([$catId, $name]);
        $id = $pdo->lastInsertId() ?: $pdo->query("SELECT id FROM item_configurations WHERE category_id=$catId AND config_name=".$pdo->quote($name))->fetchColumn();
        echo json_encode(['success'=>true,'id'=>$id,'name'=>$name]); exit;
    }
    if ($type === 'config_value') {
        $name = trim($_POST['name'] ?? '');
        $configId = (int)($_POST['config_id'] ?? 0);
        if (!$name || !$configId) { echo json_encode(['success'=>false,'error'=>'Config and value required']); exit; }
        $pdo->prepare("INSERT IGNORE INTO item_configuration_values (config_id, value) VALUES (?,?)")->execute([$configId, $name]);
        $id = $pdo->lastInsertId() ?: $pdo->query("SELECT id FROM item_configuration_values WHERE config_id=$configId AND value=".$pdo->quote($name))->fetchColumn();
        echo json_encode(['success'=>true,'id'=>$id,'name'=>$name]); exit;
    }
    // Load brands/models/configs for a category (called on category change)
    if ($type === 'load_category_data') {
        $catId = (int)($_POST['category_id'] ?? 0);
        $brands = $pdo->prepare("SELECT id, brand_name FROM item_brands WHERE category_id=? AND status=1 ORDER BY brand_name");
        $brands->execute([$catId]);
        $configs = $pdo->prepare("SELECT ic.id, ic.config_name, GROUP_CONCAT(cv.id,'|',cv.value ORDER BY cv.value SEPARATOR '||') as values_str
                                   FROM item_configurations ic
                                   LEFT JOIN item_configuration_values cv ON cv.config_id=ic.id AND cv.status=1
                                   WHERE ic.category_id=? AND ic.status=1
                                   GROUP BY ic.id ORDER BY ic.sort_order, ic.config_name");
        $configs->execute([$catId]);
        echo json_encode([
            'success' => true,
            'brands'  => $brands->fetchAll(PDO::FETCH_ASSOC),
            'configs' => $configs->fetchAll(PDO::FETCH_ASSOC),
        ]); exit;
    }
    // Load single item data for edit modal
    if ($type === 'load_item') {
        $itemId = (int)($_POST['item_id'] ?? 0);
        $stmt = $pdo->prepare("SELECT * FROM items WHERE id=?");
        $stmt->execute([$itemId]);
        $item = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$item) { echo json_encode(['success'=>false,'error'=>'Not found']); exit; }
        $specStmt = $pdo->prepare("SELECT config_id, config_value_id FROM item_specs WHERE item_id=?");
        $specStmt->execute([$itemId]);
        $specs = $specStmt->fetchAll(PDO::FETCH_KEY_PAIR);
        echo json_encode(['success'=>true,'item'=>$item,'specs'=>$specs]); exit;
    }
    // Load models for a brand
    if ($type === 'load_models') {
        $brandId = (int)($_POST['brand_id'] ?? 0);
        $models = $pdo->prepare("SELECT id, model_name FROM item_models WHERE brand_id=? ORDER BY model_name");
        $models->execute([$brandId]);
        echo json_encode(['success'=>true,'models'=>$models->fetchAll(PDO::FETCH_ASSOC)]); exit;
    }
    echo json_encode(['success'=>false,'error'=>'Unknown type']); exit;
}

// ── Item CRUD ─────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save_item') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        setFlash('danger','Invalid token.'); header('Location: items.php'); exit;
    }
    // Auto-generate item_name from brand + model if brand/model selected
    $manualName = trim($_POST['item_name'] ?? '');
    $brandId    = (int)($_POST['brand_id'] ?? 0);
    $modelId    = (int)($_POST['model_id'] ?? 0);
    if ($brandId && $modelId) {
        $bRow = $pdo->prepare("SELECT brand_name FROM item_brands WHERE id=?"); $bRow->execute([$brandId]); $bRow=$bRow->fetch();
        $mRow = $pdo->prepare("SELECT model_name FROM item_models WHERE id=?"); $mRow->execute([$modelId]); $mRow=$mRow->fetch();
        if ($bRow && $mRow) {
            $autoName = trim($bRow['brand_name'] . ' ' . $mRow['model_name']);
            $itemName = $autoName; // auto-generated takes priority
        } else { $itemName = $manualName; }
    } else { $itemName = $manualName; }
    if (empty($itemName)) { setFlash('danger','Item name is required (or select brand + model to auto-generate).'); header('Location: items.php'); exit; }

    $data = [
        $itemName,
        trim($_POST['item_code']),
        $_POST['category_id'] ?: null,
        $brandId ?: null,
        $modelId ?: null,
        trim($_POST['unit'] ?? 'Nos'),
        trim($_POST['hsn_code'] ?? ''),
        $_POST['gst_percent'] ?? 18,
        $_POST['sale_price'] ?? 0,
        $_POST['min_stock_level'] ?? 0,
        trim($_POST['description'] ?? ''),
        $_POST['item_id'] ?? null,
    ];
    if ($_POST['item_id']) {
        $pdo->prepare("UPDATE items SET item_name=?,item_code=?,category_id=?,brand_id=?,model_id=?,unit=?,hsn_code=?,gst_percent=?,sale_price=?,min_stock_level=?,description=? WHERE id=?")
            ->execute($data);
        $itemId = $_POST['item_id'];
    } else {
        $pdo->prepare("INSERT INTO items (item_name,item_code,category_id,brand_id,model_id,unit,hsn_code,gst_percent,sale_price,min_stock_level,description) VALUES (?,?,?,?,?,?,?,?,?,?,?)")
            ->execute(array_slice($data, 0, 11));
        $itemId = $pdo->lastInsertId();
        ensureStockLedger($itemId);
    }
    // Save specs
    $pdo->prepare("DELETE FROM item_specs WHERE item_id=?")->execute([$itemId]);
    if (!empty($_POST['specs']) && is_array($_POST['specs'])) {
        $insSpec = $pdo->prepare("INSERT IGNORE INTO item_specs (item_id, config_id, config_value_id) VALUES (?,?,?)");
        foreach ($_POST['specs'] as $configId => $valueId) {
            if ($configId && $valueId) $insSpec->execute([$itemId, $configId, $valueId]);
        }
    }
    setFlash('success', 'Item saved successfully.');
    header('Location: items.php'); exit;
}

if (isset($_GET['delete'])) {
    $pdo->prepare("UPDATE items SET status=0 WHERE id=?")->execute([(int)$_GET['delete']]);
    setFlash('success','Item removed.'); header('Location: items.php'); exit;
}
if (isset($_GET['toggle'])) {
    $pdo->prepare("UPDATE items SET status = 1-status WHERE id=?")->execute([(int)$_GET['toggle']]);
    header('Location: items.php'); exit;
}

// ── Load data ─────────────────────────────────────────────────
$search = trim($_GET['search'] ?? '');
$filterCat = (int)($_GET['cat'] ?? 0);
$where = ['i.status = 1']; $params = [];
if ($search) { $where[] = "(i.item_name LIKE ? OR i.item_code LIKE ?)"; $params[] = "%$search%"; $params[] = "%$search%"; }
if ($filterCat) { $where[] = "i.category_id = ?"; $params[] = $filterCat; }
$whereSql = 'WHERE ' . implode(' AND ', $where);

$stmt = $pdo->prepare("SELECT i.*, c.category_name, ib.brand_name, im.model_name,
                        COALESCE(sl.available_qty,0) available_qty,
                        COALESCE(sl.freeze_qty,0) freeze_qty,
                        COALESCE(sl.sold_qty,0) sold_qty
                        FROM items i
                        LEFT JOIN categories c ON c.id=i.category_id
                        LEFT JOIN item_brands ib ON ib.id=i.brand_id
                        LEFT JOIN item_models im ON im.id=i.model_id
                        LEFT JOIN stock_ledger sl ON sl.item_id=i.id
                        $whereSql ORDER BY i.item_name");
$stmt->execute($params);
$items = $stmt->fetchAll();

$categories  = $pdo->query("SELECT * FROM categories ORDER BY category_name")->fetchAll();
$editItem    = null;
$editSpecs   = [];
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM items WHERE id=?");
    $stmt->execute([(int)$_GET['edit']]); $editItem = $stmt->fetch();
    if ($editItem) {
        $stmt2 = $pdo->prepare("SELECT config_id, config_value_id FROM item_specs WHERE item_id=?");
        $stmt2->execute([$editItem['id']]); $editSpecs = $stmt2->fetchAll(PDO::FETCH_KEY_PAIR);
    }
}

$csrf = generateCSRFToken();
$pageTitle = 'Item Master';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div>
        <div class="eyebrow">Stock</div>
        <h2 class="mb-0">Item Master</h2>
    </div>
    <div class="flex gap-8">
        <button class="btn btn-primary" onclick="openAddItem()"><?= icon('plus') ?> Add Item</button>
    </div>
</div>

<!-- Filter bar -->
<div class="card" style="padding:12px 16px;">
    <form method="GET" class="flex gap-8" style="flex-wrap:wrap;align-items:center;">
        <input type="text" name="search" placeholder="Search items..." value="<?= sanitize($search) ?>" style="width:200px;">
        <select name="cat" onchange="this.form.submit()" style="width:180px;">
            <option value="">All Categories</option>
            <?php foreach ($categories as $c): ?>
            <option value="<?= $c['id'] ?>" <?= $filterCat==$c['id']?'selected':'' ?>><?= sanitize($c['category_name']) ?></option>
            <?php endforeach; ?>
        </select>
        <button class="btn btn-icon" title="Search" style="width:38px;height:38px;"><?= icon('search') ?></button>
        <?php if ($search || $filterCat): ?>
        <a href="items.php" class="btn"><?= icon('x') ?> Clear</a>
        <?php endif; ?>
    </form>
</div>

<!-- Items table -->
<div class="card">
    <?php if ($items): ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Code</th><th>Item Name</th><th>Category</th>
                    <th>Brand / Model</th><th>Specs</th>
                    <th class="text-right">Sale Price</th><th class="text-right">GST</th>
                    <th class="text-right">Available</th><th class="text-right">Freeze</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($items as $item):
                // Load specs for this item inline
                $specStmt = $pdo->prepare("SELECT ic.config_name, cv.value
                    FROM item_specs isp
                    JOIN item_configurations ic ON ic.id=isp.config_id
                    JOIN item_configuration_values cv ON cv.id=isp.config_value_id
                    WHERE isp.item_id=? ORDER BY ic.sort_order");
                $specStmt->execute([$item['id']]);
                $specs = $specStmt->fetchAll();
            ?>
            <tr>
                <td class="mono"><?= sanitize($item['item_code']) ?></td>
                <td><strong><?= sanitize($item['item_name']) ?></strong></td>
                <td><span class="badge"><?= sanitize($item['category_name'] ?? '-') ?></span></td>
                <td class="text-sm"><?= sanitize($item['brand_name'] ?? '') ?><?= $item['model_name'] ? ' / '.$item['model_name'] : '' ?></td>
                <td class="text-sm text-muted">
                    <?php foreach ($specs as $s): ?>
                    <span class="badge badge-muted" style="margin:1px;"><?= sanitize($s['config_name']) ?>: <?= sanitize($s['value']) ?></span>
                    <?php endforeach; ?>
                </td>
                <td class="num mono"><?= formatMoney($item['sale_price']) ?></td>
                <td class="num"><?= $item['gst_percent'] ?>%</td>
                <td class="num <?= $item['available_qty'] <= ($item['min_stock_level'] ?? 0) ? 'text-danger' : 'text-success' ?>"><?= $item['available_qty'] ?></td>
                <td class="num"><?= $item['freeze_qty'] ?></td>
                <td>
                    <div class="flex gap-4">
                        <a href="?edit=<?= $item['id'] ?>" class="btn btn-icon btn-sm" title="Edit" onclick="openEditItem(<?= $item['id'] ?>); return false;"><?= icon('edit') ?></a>
                        <a href="?toggle=<?= $item['id'] ?>" class="btn btn-icon btn-sm" title="Toggle status"><?= icon('power') ?></a>
                        <a href="?delete=<?= $item['id'] ?>" class="btn btn-icon btn-sm" title="Remove" onclick="return confirm('Remove this item?')"><?= icon('trash') ?></a>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div class="empty-state"><?= icon('package') ?> No items found. Add your first item!</div>
    <?php endif; ?>
</div>

<!-- ══ ADD / EDIT ITEM MODAL ══════════════════════════════════ -->
<div id="itemModal" class="modal">
    <div class="modal-box" style="max-width:700px;max-height:90vh;overflow-y:auto;">
        <div class="modal-header">
            <span id="itemModalTitle">Add Item</span>
            <button class="btn btn-icon" onclick="closeItemModal()"><?= icon('x') ?></button>
        </div>

        <form method="POST" id="itemForm">
            <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
            <input type="hidden" name="action" value="save_item">
            <input type="hidden" name="item_id" id="form_item_id" value="">

            <!-- BASIC INFO -->
            <div class="form-grid">
                <div class="form-group full">
                    <label>Item Name <span class="req">*</span></label>
                    <input type="text" name="item_name" id="f_item_name" required placeholder="e.g. Dell Latitude 3520 Laptop">
                    <div class="text-sm text-faint" style="margin-top:4px;"><?= icon('info-circle') ?> Select Brand + Model above to auto-fill this field.</div>
                </div>
                <div class="form-group">
                    <label>Item Code <span class="req">*</span></label>
                    <input type="text" name="item_code" id="f_item_code" required placeholder="Auto or custom code">
                </div>
                <div class="form-group">
                    <label>Unit</label>
                    <select name="unit" id="f_unit">
                        <option value="Nos">Nos</option><option value="Box">Box</option>
                        <option value="Kg">Kg</option><option value="Ltr">Ltr</option>
                        <option value="Mtr">Mtr</option><option value="Set">Set</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>HSN Code</label>
                    <input type="text" name="hsn_code" id="f_hsn_code" placeholder="e.g. 8471">
                </div>
                <div class="form-group">
                    <label>Sale Price</label>
                    <input type="number" step="0.01" name="sale_price" id="f_sale_price" value="0">
                </div>
                <div class="form-group">
                    <label>GST %</label>
                    <select name="gst_percent" id="f_gst_percent">
                        <option value="0">0%</option><option value="5">5%</option>
                        <option value="12">12%</option><option value="18" selected>18%</option>
                        <option value="28">28%</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Min Stock Level</label>
                    <input type="number" name="min_stock_level" id="f_min_stock" value="0">
                </div>
            </div>

            <div class="divider"></div>
            <div style="font-weight:600; margin-bottom:12px;"><?= icon('tag') ?> Category &amp; Configuration</div>

            <!-- CATEGORY — always first, drives everything else -->
            <div class="form-group">
                <label>Category <span class="req">*</span></label>
                <div class="flex gap-8">
                    <select name="category_id" id="f_category" onchange="onCategoryChange(this.value)" style="flex:1;" required>
                        <option value="">-- Select Category --</option>
                        <?php foreach ($categories as $c): ?>
                        <option value="<?= $c['id'] ?>"><?= sanitize($c['category_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <button type="button" class="btn btn-icon" style="width:36px;height:36px;flex-shrink:0;"
                        onclick="toggleRow('cat_add_row')" title="Add new category"><?= icon('plus') ?></button>
                </div>
                <div id="cat_add_row" style="display:none;margin-top:6px;" class="flex gap-8">
                    <input type="text" id="new_cat_name" placeholder="New category name" style="flex:1;">
                    <button type="button" class="btn btn-sm btn-primary" onclick="quickAddCategory()">Add</button>
                    <button type="button" class="btn btn-sm" onclick="toggleRow('cat_add_row')">Cancel</button>
                </div>
            </div>

            <!-- BRAND — filtered by selected category -->
            <div class="form-group">
                <label>Brand</label>
                <div class="flex gap-8">
                    <select name="brand_id" id="f_brand" onchange="onBrandChange(this.value)" style="flex:1;">
                        <option value="">-- Select Brand --</option>
                    </select>
                    <button type="button" class="btn btn-icon" style="width:36px;height:36px;flex-shrink:0;"
                        onclick="toggleRow('brand_add_row')" title="Add new brand"><?= icon('plus') ?></button>
                </div>
                <div id="brand_add_row" style="display:none;margin-top:6px;" class="flex gap-8">
                    <input type="text" id="new_brand_name" placeholder="New brand name" style="flex:1;">
                    <button type="button" class="btn btn-sm btn-primary" onclick="quickAddBrand()">Add</button>
                    <button type="button" class="btn btn-sm" onclick="toggleRow('brand_add_row')">Cancel</button>
                </div>
            </div>

            <!-- MODEL — filtered by selected brand -->
            <div class="form-group">
                <label>Model</label>
                <div class="flex gap-8">
                    <select name="model_id" id="f_model" style="flex:1;" onchange="autoFillItemName()">
                        <option value="">-- Select Model --</option>
                    </select>
                    <button type="button" class="btn btn-icon" style="width:36px;height:36px;flex-shrink:0;"
                        onclick="toggleRow('model_add_row')" title="Add new model"><?= icon('plus') ?></button>
                </div>
                <div id="model_add_row" style="display:none;margin-top:6px;" class="flex gap-8">
                    <input type="text" id="new_model_name" placeholder="New model name" style="flex:1;">
                    <button type="button" class="btn btn-sm btn-primary" onclick="quickAddModel()">Add</button>
                    <button type="button" class="btn btn-sm" onclick="toggleRow('model_add_row')">Cancel</button>
                </div>
            </div>

            <!-- DYNAMIC SPECS — shown only after category selected, specific to that category -->
            <div id="specsSection" style="display:none;">
                <div class="divider"></div>
                <div style="font-weight:600;margin-bottom:12px;"><?= icon('settings') ?> Specifications</div>
                <div id="specsGrid" class="form-grid"></div>
            </div>

            <div class="form-group full" style="margin-top:8px;">
                <label>Description</label>
                <textarea name="description" id="f_description" rows="2" placeholder="Optional notes about this item"></textarea>
            </div>

            <div class="flex-end gap-8 mt-16">
                <button type="button" class="btn" onclick="closeItemModal()">Cancel</button>
                <button type="submit" class="btn btn-primary"><?= icon('check') ?> Save Item</button>
            </div>
        </form>
    </div>
</div>

<style>
.spec-row { margin-bottom: 0; }
.spec-val-row { display:none; margin-top:4px; }
</style>

<script>
const CSRF = '<?= $csrf ?>';

// ── Utility ───────────────────────────────────────────────────
function toggleRow(id) {
    const el = document.getElementById(id);
    el.style.display = el.style.display === 'none' ? 'flex' : 'none';
}

async function ajaxQuickAdd(data) {
    const fd = new FormData();
    fd.append('csrf_token', CSRF);
    for (const [k,v] of Object.entries(data)) fd.append(k, v);
    const res = await fetch('?ajax=quick_add', {method:'POST', body:fd});
    return res.json();
}

// ── Modal open/close ──────────────────────────────────────────
function openAddItem() {
    document.getElementById('itemModalTitle').textContent = 'Add New Item';
    document.getElementById('itemForm').reset();
    document.getElementById('form_item_id').value = '';
    document.getElementById('f_brand').innerHTML = '<option value="">-- Select Brand --</option>';
    document.getElementById('f_model').innerHTML = '<option value="">-- Select Model --</option>';
    document.getElementById('specsSection').style.display = 'none';
    document.getElementById('specsGrid').innerHTML = '';
    // Auto-generate item code
    fetch('?ajax=quick_add', {method:'POST', body: (() => { const f=new FormData(); f.append('csrf_token',CSRF); f.append('type','gen_code'); return f; })()})
    document.getElementById('itemModal').classList.add('show');
}

function openEditItem(itemId) {
    // fetch item data
    fetch(`items.php?ajax=quick_add`, {method:'POST', body: (() => {
        const f = new FormData();
        f.append('csrf_token', CSRF);
        f.append('type', 'load_item');
        f.append('item_id', itemId);
        return f;
    })()}).then(r => r.json()).then(async data => {
        if (!data.success) { alert('Could not load item.'); return; }
        const it = data.item;
        document.getElementById('itemModalTitle').textContent = 'Edit Item';
        document.getElementById('form_item_id').value = it.id;
        document.getElementById('f_item_name').value = it.item_name;
        document.getElementById('f_item_code').value = it.item_code;
        document.getElementById('f_unit').value = it.unit;
        document.getElementById('f_hsn_code').value = it.hsn_code || '';
        document.getElementById('f_sale_price').value = it.sale_price;
        document.getElementById('f_gst_percent').value = it.gst_percent;
        document.getElementById('f_min_stock').value = it.min_stock_level;
        document.getElementById('f_description').value = it.description || '';
        document.getElementById('f_category').value = it.category_id || '';
        if (it.category_id) {
            await onCategoryChange(it.category_id, it.brand_id, it.model_id, data.specs);
        }
        document.getElementById('itemModal').classList.add('show');
    });
}

function closeItemModal() {
    document.getElementById('itemModal').classList.remove('show');
}

// ── Category change: load brands + configs ────────────────────
async function onCategoryChange(catId, preselectBrand, preselectModel, preselectSpecs) {
    const brandSel = document.getElementById('f_brand');
    const modelSel = document.getElementById('f_model');
    const specsGrid = document.getElementById('specsGrid');
    const specsSection = document.getElementById('specsSection');

    brandSel.innerHTML = '<option value="">-- Select Brand --</option>';
    modelSel.innerHTML = '<option value="">-- Select Model --</option>';
    specsGrid.innerHTML = '';
    specsSection.style.display = 'none';

    if (!catId) return;

    const fd = new FormData();
    fd.append('csrf_token', CSRF);
    fd.append('type', 'load_category_data');
    fd.append('category_id', catId);
    const res = await fetch('?ajax=quick_add', {method:'POST', body:fd});
    const data = await res.json();

    // Populate brands
    data.brands.forEach(b => {
        const opt = new Option(b.brand_name, b.id);
        brandSel.appendChild(opt);
    });
    if (preselectBrand) {
        brandSel.value = preselectBrand;
        await onBrandChange(preselectBrand, preselectModel);
    }

    // Render spec dropdowns
    if (data.configs.length > 0) {
        specsSection.style.display = 'block';
        data.configs.forEach(cfg => {
            const values = cfg.values_str ? cfg.values_str.split('||').map(v => {
                const [id, name] = v.split('|');
                return {id, name};
            }) : [];

            const preselectVal = preselectSpecs ? preselectSpecs[cfg.id] : null;

            specsGrid.innerHTML += `
            <div class="form-group spec-row" id="spec_row_${cfg.id}">
                <label>${cfg.config_name}</label>
                <div class="flex gap-8">
                    <select name="specs[${cfg.id}]" id="spec_${cfg.id}" style="flex:1;">
                        <option value="">-- Select ${cfg.config_name} --</option>
                        ${values.map(v => `<option value="${v.id}" ${preselectVal==v.id?'selected':''}>${v.name}</option>`).join('')}
                    </select>
                    <button type="button" class="btn btn-icon" style="width:36px;height:36px;flex-shrink:0;"
                        onclick="toggleRow('spec_add_${cfg.id}')" title="Add value">${'<?= icon('plus') ?>'}</button>
                </div>
                <div id="spec_add_${cfg.id}" style="display:none;margin-top:4px;" class="flex gap-8">
                    <input type="text" id="spec_val_${cfg.id}" placeholder="New ${cfg.config_name} value" style="flex:1;">
                    <button type="button" class="btn btn-sm btn-primary"
                        onclick="quickAddConfigValue(${cfg.id}, ${catId})">Add</button>
                    <button type="button" class="btn btn-sm"
                        onclick="toggleRow('spec_add_${cfg.id}')">Cancel</button>
                </div>
            </div>`;
        });

        // Also add a "New Config" button at the bottom
        specsGrid.innerHTML += `
        <div class="form-group full">
            <button type="button" class="btn btn-sm" onclick="toggleRow('config_add_row_${catId}')">
                ${'<?= icon('plus') ?>'} Add New Spec Type for this Category
            </button>
            <div id="config_add_row_${catId}" style="display:none;margin-top:6px;" class="flex gap-8">
                <input type="text" id="new_config_name_${catId}" placeholder="New spec name (e.g. Display Type)" style="flex:1;">
                <button type="button" class="btn btn-sm btn-primary"
                    onclick="quickAddConfig(${catId})">Add</button>
                <button type="button" class="btn btn-sm"
                    onclick="toggleRow('config_add_row_${catId}')">Cancel</button>
            </div>
        </div>`;
    } else {
        specsSection.style.display = 'block';
        specsGrid.innerHTML = `
        <div class="form-group full">
            <div class="text-sm text-muted">No specifications defined for this category yet.</div>
            <div class="flex gap-8" style="margin-top:8px;">
                <input type="text" id="new_config_name_${catId}" placeholder="Add spec (e.g. Processor, RAM)" style="flex:1;">
                <button type="button" class="btn btn-sm btn-primary"
                    onclick="quickAddConfig(${catId})">Add Spec</button>
            </div>
        </div>`;
    }
}

// ── Brand change: load models ─────────────────────────────────
async function onBrandChange(brandId, preselectModel) {
    const modelSel = document.getElementById('f_model');
    modelSel.innerHTML = '<option value="">-- Select Model --</option>';
    if (!brandId) return;

    const fd = new FormData();
    fd.append('csrf_token', CSRF);
    fd.append('type', 'load_models');
    fd.append('brand_id', brandId);
    const res = await fetch('?ajax=quick_add', {method:'POST', body:fd});
    const data = await res.json();
    data.models.forEach(m => {
        const opt = new Option(m.model_name, m.id);
        modelSel.appendChild(opt);
    });
    if (preselectModel) modelSel.value = preselectModel;
    autoFillItemName();
}

// ── Auto-generate item name from brand + model ────────────────
function autoFillItemName() {
    const brandSel = document.getElementById('f_brand');
    const modelSel = document.getElementById('f_model');
    const nameInput = document.getElementById('f_item_name');
    const brandText = brandSel.options[brandSel.selectedIndex]?.text || '';
    const modelText = modelSel.options[modelSel.selectedIndex]?.text || '';
    if (brandSel.value && modelSel.value && brandText !== '-- Select Brand --' && modelText !== '-- Select Model --') {
        nameInput.value = brandText + ' ' + modelText;
        nameInput.style.background = 'var(--color-surface-2)';
        nameInput.title = 'Auto-generated from Brand + Model. You can still edit this.';
    }
}

// ── Quick-add functions ───────────────────────────────────────
async function quickAddCategory() {
    const input = document.getElementById('new_cat_name');
    const name = input.value.trim();
    if (!name) { alert('Enter category name.'); return; }
    const r = await ajaxQuickAdd({type:'category', name});
    if (!r.success) { alert(r.error); return; }
    const sel = document.getElementById('f_category');
    sel.appendChild(new Option(r.name, r.id, true, true));
    sel.value = r.id;
    onCategoryChange(r.id);
    input.value = ''; toggleRow('cat_add_row');
}

async function quickAddBrand() {
    const input = document.getElementById('new_brand_name');
    const name = input.value.trim();
    const catId = document.getElementById('f_category').value;
    if (!name) { alert('Enter brand name.'); return; }
    const r = await ajaxQuickAdd({type:'brand', name, category_id: catId});
    if (!r.success) { alert(r.error); return; }
    const sel = document.getElementById('f_brand');
    sel.appendChild(new Option(r.name, r.id, true, true));
    sel.value = r.id;
    onBrandChange(r.id);
    input.value = ''; toggleRow('brand_add_row');
}

async function quickAddModel() {
    const input = document.getElementById('new_model_name');
    const name = input.value.trim();
    const brandId = document.getElementById('f_brand').value;
    if (!brandId) { alert('Select a brand first.'); return; }
    if (!name) { alert('Enter model name.'); return; }
    const r = await ajaxQuickAdd({type:'model', name, brand_id: brandId});
    if (!r.success) { alert(r.error); return; }
    const sel = document.getElementById('f_model');
    sel.appendChild(new Option(r.name, r.id, true, true));
    sel.value = r.id;
    input.value = ''; toggleRow('model_add_row');
}

async function quickAddConfig(catId) {
    const input = document.getElementById(`new_config_name_${catId}`);
    const name = input.value.trim();
    if (!name) { alert('Enter spec name.'); return; }
    const r = await ajaxQuickAdd({type:'config', name, category_id: catId});
    if (!r.success) { alert(r.error); return; }
    // Reload category data to show the new spec
    const brandId = document.getElementById('f_brand').value;
    const modelId = document.getElementById('f_model').value;
    await onCategoryChange(catId, brandId, modelId, null);
    alert(`Spec "${name}" added! Add values to it using the + button.`);
}

async function quickAddConfigValue(configId, catId) {
    const input = document.getElementById(`spec_val_${configId}`);
    const name = input.value.trim();
    if (!name) { alert('Enter a value.'); return; }
    const r = await ajaxQuickAdd({type:'config_value', name, config_id: configId});
    if (!r.success) { alert(r.error); return; }
    const sel = document.getElementById(`spec_${configId}`);
    sel.appendChild(new Option(r.name, r.id, true, true));
    sel.value = r.id;
    input.value = ''; toggleRow(`spec_add_${configId}`);
}
</script>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
