<?php
/**
 * Admin — Products Manager (Category → Company → Product)
 * Path: admin/products.php
 */
require_once 'layout-header.php';

if (!$conn) {
    echo "<main class='flex-1 p-6'><div class='p-4 bg-red-950/40 border border-red-800 text-red-200 text-sm rounded-xl'><i class='fa-solid fa-triangle-exclamation mr-2'></i>ডাটাবেজ কানেক্টেড নেই!</div></main>";
    require_once 'layout-footer.php';
    exit;
}

$prefix      = DB_PREFIX;
$msg_success = '';
$msg_error   = '';
$action      = isset($_GET['action']) ? $_GET['action'] : 'list';
$edit_id     = isset($_GET['id']) ? intval($_GET['id']) : 0;
$filter_cat  = isset($_GET['cat']) ? intval($_GET['cat']) : 0;
$filter_comp = isset($_GET['comp']) ? intval($_GET['comp']) : 0;

$all_categories    = get_categories(false);
$all_subcategories = get_subcategories(null, false);
$all_companies     = get_all_companies();

// Delete gallery image
if ($action === 'delete_image' && isset($_GET['image_id']) && $edit_id > 0) {
    $image_id = intval($_GET['image_id']);
    $stmt = $conn->prepare("SELECT image_url FROM `{$prefix}product_images` WHERE id = ? AND product_id = ?");
    $stmt->bind_param("ii", $image_id, $edit_id);
    $stmt->execute();
    if ($row = $stmt->get_result()->fetch_assoc()) {
        $fp = '../' . $row['image_url'];
        if (is_file($fp)) unlink($fp);
    }
    $stmt->close();
    $stmt_del = $conn->prepare("DELETE FROM `{$prefix}product_images` WHERE id = ? AND product_id = ?");
    $stmt_del->bind_param("ii", $image_id, $edit_id);
    $stmt_del->execute();
    $stmt_del->close();
    $msg_success = 'গ্যালারি ছবি মুছে ফেলা হয়েছে।';
    $action = 'edit';
}

// Delete product
if ($action === 'delete' && $edit_id > 0) {
    $stmt_imgs = $conn->prepare("SELECT image_url FROM `{$prefix}product_images` WHERE product_id = ?");
    $stmt_imgs->bind_param("i", $edit_id);
    $stmt_imgs->execute();
    $res = $stmt_imgs->get_result();
    while ($img = $res->fetch_assoc()) {
        $fp = '../' . $img['image_url'];
        if (is_file($fp)) unlink($fp);
    }
    $stmt_imgs->close();
    $stmt = $conn->prepare("DELETE FROM `{$prefix}services` WHERE id = ?");
    $stmt->bind_param("i", $edit_id);
    $stmt->execute() ? $msg_success = 'প্রডাক্ট মুছে ফেলা হয়েছে।' : $msg_error = $conn->error;
    $stmt->close();
    $action = 'list';
}

// Save product
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['form_action'])) {
    $title       = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $image_url   = trim($_POST['image_url'] ?? '');
    $category_id    = intval($_POST['category_id'] ?? 0);
    $subcategory_id = intval($_POST['subcategory_id'] ?? 0);
    $company_id     = intval($_POST['company_id'] ?? 0);
    $slug        = preg_replace('/[^a-z0-9\-]/', '', str_replace(' ', '-', strtolower($title)));

    if (empty($title) || empty($description)) {
        $msg_error = 'টাইটেল ও বিবরণ বাধ্যতামূলক।';
    } else {
        if (isset($_FILES['image_file']) && $_FILES['image_file']['error'] === UPLOAD_ERR_OK) {
            $ext = strtolower(pathinfo($_FILES['image_file']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, ['jpg','jpeg','png','webp','gif'])) {
                $dir = '../uploads/';
                if (!is_dir($dir)) mkdir($dir, 0755, true);
                $fname = time() . '_main_' . bin2hex(random_bytes(3)) . '.' . $ext;
                if (move_uploaded_file($_FILES['image_file']['tmp_name'], $dir . $fname)) {
                    $image_url = 'uploads/' . $fname;
                }
            }
        }

        if (empty($msg_error)) {
            $conn->begin_transaction();
            try {
                $product_id = 0;
                if ($_POST['form_action'] === 'add_product') {
                    $stmt = $conn->prepare("INSERT INTO `{$prefix}services` (title, description, image_url, slug, category_id, subcategory_id, company_id) VALUES (?,?,?,?,?,?,?)");
                    $stmt->bind_param("ssssiii", $title, $description, $image_url, $slug, $category_id, $subcategory_id, $company_id);
                    $stmt->execute();
                    $product_id = $conn->insert_id;
                    $stmt->close();
                } elseif ($_POST['form_action'] === 'edit_product' && $edit_id > 0) {
                    $stmt = $conn->prepare("UPDATE `{$prefix}services` SET title=?, description=?, image_url=?, slug=?, category_id=?, subcategory_id=?, company_id=? WHERE id=?");
                    $stmt->bind_param("ssssiiii", $title, $description, $image_url, $slug, $category_id, $subcategory_id, $company_id, $edit_id);
                    $stmt->execute();
                    $stmt->close();
                    $product_id = $edit_id;
                }

                if ($product_id > 0) {
                    // Gallery upload
                    if (isset($_FILES['gallery_files']) && !empty($_FILES['gallery_files']['name'][0])) {
                        $dir = '../uploads/';
                        for ($i = 0; $i < count($_FILES['gallery_files']['name']); $i++) {
                            if ($_FILES['gallery_files']['error'][$i] === UPLOAD_ERR_OK) {
                                $ext = strtolower(pathinfo($_FILES['gallery_files']['name'][$i], PATHINFO_EXTENSION));
                                if (in_array($ext, ['jpg','jpeg','png','webp','gif'])) {
                                    $fname = time() . '_gal_' . $i . '_' . bin2hex(random_bytes(2)) . '.' . $ext;
                                    if (move_uploaded_file($_FILES['gallery_files']['tmp_name'][$i], $dir . $fname)) {
                                        $gal = 'uploads/' . $fname;
                                        $sg = $conn->prepare("INSERT INTO `{$prefix}product_images` (product_id, image_url) VALUES (?,?)");
                                        $sg->bind_param("is", $product_id, $gal);
                                        $sg->execute();
                                        $sg->close();
                                    }
                                }
                            }
                        }
                    }
                    // Specs
                    $sd = $conn->prepare("DELETE FROM `{$prefix}product_specs` WHERE product_id = ?");
                    $sd->bind_param("i", $product_id);
                    $sd->execute();
                    $sd->close();
                    if (isset($_POST['spec_keys'], $_POST['spec_values'])) {
                        for ($i = 0; $i < count($_POST['spec_keys']); $i++) {
                            $k = trim($_POST['spec_keys'][$i]);
                            $v = trim($_POST['spec_values'][$i]);
                            if ($k && $v) {
                                $ss = $conn->prepare("INSERT INTO `{$prefix}product_specs` (product_id, spec_key, spec_value) VALUES (?,?,?)");
                                $ss->bind_param("iss", $product_id, $k, $v);
                                $ss->execute();
                                $ss->close();
                            }
                        }
                    }
                    $conn->commit();
                    $msg_success = 'প্রডাক্ট সফলভাবে সেভ হয়েছে!';
                    $action = 'list';
                }
            } catch (Exception $e) {
                $conn->rollback();
                $msg_error = 'সেভ করতে সমস্যা: ' . $e->getMessage();
            }
        }
    }
}
?>

<main class="flex-1 p-6 md:p-8 space-y-6">

    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 border-b border-slate-800/80 pb-5">
        <div>
            <h1 class="text-2xl font-black text-white uppercase tracking-wider">Products Manager</h1>
            <p class="text-xs text-slate-400 mt-1">ক্যাটাগরি → কোম্পানি → প্রডাক্ট ফিল্টার ও ম্যানেজমেন্ট</p>
        </div>
        <?php if ($action === 'list'): ?>
        <a href="?action=add" class="bg-sky-500 hover:bg-sky-600 text-slate-950 font-black px-5 py-2.5 rounded-xl text-xs uppercase flex items-center">
            <i class="fa-solid fa-plus-circle mr-2"></i> Add Product
        </a>
        <?php else: ?>
        <a href="products.php" class="bg-slate-800 hover:bg-slate-700 text-slate-300 px-5 py-2.5 rounded-xl text-xs uppercase flex items-center">
            <i class="fa-solid fa-arrow-left mr-2"></i> Back to List
        </a>
        <?php endif; ?>
    </div>

    <?php if ($msg_success): ?>
    <div class="p-4 bg-emerald-950/40 border border-emerald-800 text-emerald-200 text-xs rounded-xl flex items-center">
        <i class="fa-solid fa-circle-check mr-3"></i> <?php echo $msg_success; ?>
    </div>
    <?php endif; ?>
    <?php if ($msg_error): ?>
    <div class="p-4 bg-red-950/40 border border-red-800 text-red-200 text-xs rounded-xl flex items-center">
        <i class="fa-solid fa-triangle-exclamation mr-3"></i> <?php echo $msg_error; ?>
    </div>
    <?php endif; ?>

    <?php if ($action === 'add' || $action === 'edit'):
        $form_action = 'add_product';
        $val = ['title'=>'','description'=>'','image_url'=>'','category_id'=>0,'subcategory_id'=>0,'company_id'=>0];
        $existing_specs = [];
        $existing_gallery = [];

        if ($action === 'edit' && $edit_id > 0) {
            $form_action = 'edit_product';
            $stmt = $conn->prepare("SELECT * FROM `{$prefix}services` WHERE id = ?");
            $stmt->bind_param("i", $edit_id);
            $stmt->execute();
            if ($row = $stmt->get_result()->fetch_assoc()) $val = array_merge($val, $row);
            $stmt->close();

            $sg = $conn->prepare("SELECT * FROM `{$prefix}product_images` WHERE product_id = ?");
            $sg->bind_param("i", $edit_id);
            $sg->execute();
            $res = $sg->get_result();
            while ($g = $res->fetch_assoc()) $existing_gallery[] = $g;
            $sg->close();

            $ss = $conn->prepare("SELECT * FROM `{$prefix}product_specs` WHERE product_id = ?");
            $ss->bind_param("i", $edit_id);
            $ss->execute();
            $res = $ss->get_result();
            while ($s = $res->fetch_assoc()) $existing_specs[] = $s;
            $ss->close();
        }
    ?>
    <div class="bg-slate-900 border border-slate-800/80 rounded-2xl p-6">
        <form method="post" action="" enctype="multipart/form-data" class="space-y-6">
            <input type="hidden" name="form_action" value="<?php echo $form_action; ?>">

            <!-- Category, Sub-category & Company -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div>
                    <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Category *</label>
                    <select name="category_id" id="cat-select" required
                        class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100 focus:ring-2 focus:ring-sky-500">
                        <option value="">— Select Category —</option>
                        <?php foreach ($all_categories as $cat): ?>
                        <option value="<?php echo $cat['id']; ?>" <?php echo ($val['category_id'] == $cat['id']) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($cat['name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Sub-category</label>
                    <select name="subcategory_id" id="sub-select"
                        class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100 focus:ring-2 focus:ring-sky-500">
                        <option value="">— Select Sub-category —</option>
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Company / Brand *</label>
                    <select name="company_id" id="comp-select" required
                        class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100 focus:ring-2 focus:ring-sky-500">
                        <option value="">— Select Company —</option>
                    </select>
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Product Title *</label>
                    <input type="text" name="title" value="<?php echo htmlspecialchars($val['title']); ?>" required
                        class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
                </div>
                <div>
                    <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Cover Image</label>
                    <div class="grid grid-cols-2 gap-3">
                        <input type="file" name="image_file" accept="image/*" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-2 py-2 text-xs text-slate-400">
                        <input type="url" name="image_url" value="<?php echo htmlspecialchars($val['image_url']); ?>" placeholder="https://..."
                            class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-slate-100">
                    </div>
                </div>
            </div>

            <div>
                <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Description *</label>
                <textarea name="description" rows="4" required
                    class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100"><?php echo htmlspecialchars($val['description']); ?></textarea>
            </div>

            <!-- Gallery -->
            <div class="bg-slate-950/40 p-4 border border-slate-800 rounded-xl space-y-3">
                <h3 class="text-xs font-black uppercase text-slate-300">Gallery Images</h3>
                <input type="file" name="gallery_files[]" multiple accept="image/*" class="w-full text-xs text-slate-400">
                <?php if (!empty($existing_gallery)): ?>
                <div class="flex flex-wrap gap-3 pt-2">
                    <?php foreach ($existing_gallery as $img):
                        $src = (strpos($img['image_url'],'uploads/')===0) ? '../'.$img['image_url'] : $img['image_url'];
                    ?>
                    <div class="relative w-16 h-16 rounded-lg overflow-hidden border border-slate-700 group">
                        <img src="<?php echo htmlspecialchars($src); ?>" class="w-full h-full object-cover">
                        <a href="?action=delete_image&image_id=<?php echo $img['id']; ?>&id=<?php echo $edit_id; ?>"
                            onclick="return confirm('মুছে ফেলবেন?');"
                            class="absolute inset-0 bg-red-600/80 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity text-white text-xs">
                            <i class="fa-solid fa-trash"></i>
                        </a>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>

            <!-- Specs -->
            <div class="bg-slate-950/40 p-4 border border-slate-800 rounded-xl space-y-3">
                <div class="flex justify-between items-center">
                    <h3 class="text-xs font-black uppercase text-slate-300">Specifications</h3>
                    <button type="button" onclick="addSpecRow()" class="text-xs font-bold text-sky-400 hover:text-sky-300">
                        <i class="fa-solid fa-circle-plus mr-1"></i> Add Field
                    </button>
                </div>
                <div id="specs-container" class="space-y-2">
                    <?php foreach ($existing_specs as $spec): ?>
                    <div class="flex gap-3 spec-row">
                        <input type="text" name="spec_keys[]" value="<?php echo htmlspecialchars($spec['spec_key']); ?>" placeholder="Key" class="w-1/2 bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-slate-100">
                        <input type="text" name="spec_values[]" value="<?php echo htmlspecialchars($spec['spec_value']); ?>" placeholder="Value" class="w-1/2 bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-slate-100">
                        <button type="button" onclick="this.parentElement.remove()" class="text-red-400 p-1"><i class="fa-solid fa-trash"></i></button>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <button type="submit" class="bg-sky-500 hover:bg-sky-600 text-slate-950 font-black px-8 py-3.5 rounded-xl text-xs uppercase">
                <i class="fa-solid fa-floppy-disk mr-2"></i> Save Product
            </button>
        </form>
    </div>

    <script>
        const companiesData = <?php echo json_encode($all_companies); ?>;
        const subcategoriesData = <?php echo json_encode($all_subcategories); ?>;
        const catSelect  = document.getElementById('cat-select');
        const subSelect  = document.getElementById('sub-select');
        const compSelect = document.getElementById('comp-select');
        const savedSubId  = <?php echo (int)($val['subcategory_id'] ?? 0); ?>;
        const savedCompId = <?php echo (int)($val['company_id'] ?? 0); ?>;

        function loadSubs(catId, selectId) {
            subSelect.innerHTML = '<option value="">— Select Sub-category —</option>';
            subcategoriesData.filter(s => s.category_id == catId).forEach(s => {
                const opt = document.createElement('option');
                opt.value = s.id;
                opt.textContent = s.name;
                if (s.id == selectId) opt.selected = true;
                subSelect.appendChild(opt);
            });
        }

        function loadCompanies(catId, subId, selectId) {
            compSelect.innerHTML = '<option value="">— Select Company —</option>';
            // Category-level brands (shared across all sub-categories)
            companiesData.filter(c => c.category_id == catId).forEach(c => {
                const opt = document.createElement('option');
                opt.value = c.id;
                opt.textContent = c.name;
                if (c.id == selectId) opt.selected = true;
                compSelect.appendChild(opt);
            });
        }

        catSelect.addEventListener('change', () => {
            loadSubs(catSelect.value, 0);
            loadCompanies(catSelect.value, 0, 0);
        });
        subSelect.addEventListener('change', () => loadCompanies(catSelect.value, subSelect.value, 0));
        if (catSelect.value) {
            loadSubs(catSelect.value, savedSubId);
            loadCompanies(catSelect.value, savedSubId, savedCompId);
        }

        function addSpecRow() {
            const row = document.createElement('div');
            row.className = 'flex gap-3 spec-row';
            row.innerHTML = `<input type="text" name="spec_keys[]" placeholder="Key" class="w-1/2 bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-slate-100">
                <input type="text" name="spec_values[]" placeholder="Value" class="w-1/2 bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-slate-100">
                <button type="button" onclick="this.parentElement.remove()" class="text-red-400 p-1"><i class="fa-solid fa-trash"></i></button>`;
            document.getElementById('specs-container').appendChild(row);
        }
        <?php if (empty($existing_specs)): ?> document.addEventListener('DOMContentLoaded', addSpecRow); <?php endif; ?>
    </script>

    <?php else:
        // Build filtered list query
        $sql = "SELECT s.*, c.name as category_name, sc.name as subcategory_name, co.name as company_name
                FROM `{$prefix}services` s
                LEFT JOIN `{$prefix}categories` c ON s.category_id = c.id
                LEFT JOIN `{$prefix}subcategories` sc ON s.subcategory_id = sc.id
                LEFT JOIN `{$prefix}companies` co ON s.company_id = co.id
                WHERE 1=1";
        if ($filter_cat)  $sql .= " AND s.category_id = " . intval($filter_cat);
        if ($filter_comp) $sql .= " AND s.company_id = " . intval($filter_comp);
        $sql .= " ORDER BY c.sort_order, co.name, s.id DESC";
        $result = $conn->query($sql);
    ?>

    <!-- Filter Bar -->
    <div class="bg-slate-900 border border-slate-800/80 rounded-2xl p-4 flex flex-wrap gap-3 items-end">
        <div class="flex-1 min-w-[160px]">
            <label class="block text-[10px] font-bold uppercase text-slate-500 mb-1">Filter by Category</label>
            <select id="filter-cat" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-slate-100">
                <option value="">All Categories</option>
                <?php foreach ($all_categories as $cat): ?>
                <option value="<?php echo $cat['id']; ?>" <?php echo $filter_cat == $cat['id'] ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($cat['name']); ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="flex-1 min-w-[160px]">
            <label class="block text-[10px] font-bold uppercase text-slate-500 mb-1">Filter by Company</label>
            <select id="filter-comp" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-slate-100">
                <option value="">All Companies</option>
            </select>
        </div>
        <button onclick="applyFilter()" class="bg-sky-500 hover:bg-sky-600 text-slate-950 font-bold px-5 py-2 rounded-xl text-xs uppercase">
            <i class="fa-solid fa-filter mr-1"></i> Filter
        </button>
        <?php if ($filter_cat || $filter_comp): ?>
        <a href="products.php" class="text-xs text-slate-400 hover:text-white px-3 py-2">Clear</a>
        <?php endif; ?>
    </div>

    <div class="bg-slate-900 border border-slate-800/80 rounded-2xl overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full text-left text-sm">
                <thead>
                    <tr class="bg-slate-950 text-slate-400 text-xs font-bold uppercase border-b border-slate-800">
                        <th class="p-4 pl-6 w-16">Img</th>
                        <th class="p-4">Product</th>
                        <th class="p-4 hidden md:table-cell">Category</th>
                        <th class="p-4 hidden lg:table-cell">Sub-category</th>
                        <th class="p-4 hidden lg:table-cell">Company</th>
                        <th class="p-4 text-right pr-6">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-800">
                    <?php if ($result && $result->num_rows > 0):
                        while ($row = $result->fetch_assoc()):
                            $img = $row['image_url'];
                            if (strpos($img,'uploads/')===0) $img = '../'.$img;
                    ?>
                    <tr class="hover:bg-slate-800/30 transition-colors">
                        <td class="p-4 pl-6">
                            <img src="<?php echo htmlspecialchars($img); ?>" class="w-10 h-10 rounded-lg object-cover border border-slate-700" alt="">
                        </td>
                        <td class="p-4">
                            <span class="font-bold text-white text-sm block"><?php echo htmlspecialchars($row['title']); ?></span>
                            <span class="text-[10px] text-slate-500 font-mono">/<?php echo htmlspecialchars($row['slug']); ?></span>
                        </td>
                        <td class="p-4 hidden md:table-cell">
                            <span class="text-xs bg-sky-500/10 text-sky-400 px-2 py-1 rounded-full font-semibold">
                                <?php echo htmlspecialchars($row['category_name'] ?? '—'); ?>
                            </span>
                        </td>
                        <td class="p-4 hidden lg:table-cell text-xs text-slate-400">
                            <?php echo htmlspecialchars($row['subcategory_name'] ?? '—'); ?>
                        </td>
                        <td class="p-4 hidden lg:table-cell text-xs text-slate-400">
                            <?php echo htmlspecialchars($row['company_name'] ?? '—'); ?>
                        </td>
                        <td class="p-4 text-right pr-6">
                            <div class="inline-flex gap-2">
                                <a href="?action=edit&id=<?php echo $row['id']; ?>" class="p-2 bg-slate-800 hover:bg-sky-500 hover:text-slate-950 text-sky-400 rounded-lg text-xs"><i class="fa-solid fa-pen"></i></a>
                                <a href="?action=delete&id=<?php echo $row['id']; ?>" onclick="return confirm('মুছে ফেলবেন?');" class="p-2 bg-slate-800 hover:bg-red-500 hover:text-white text-red-400 rounded-lg text-xs"><i class="fa-solid fa-trash"></i></a>
                            </div>
                        </td>
                    </tr>
                    <?php endwhile; else: ?>
                    <tr><td colspan="6" class="p-8 text-center text-slate-500 text-sm">কোনো প্রডাক্ট পাওয়া যায়নি।</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <script>
        const companiesData = <?php echo json_encode($all_companies); ?>;
        const filterCat  = document.getElementById('filter-cat');
        const filterComp = document.getElementById('filter-comp');
        const savedFilterComp = <?php echo $filter_comp; ?>;

        function loadFilterCompanies(catId) {
            filterComp.innerHTML = '<option value="">All Companies</option>';
            companiesData.filter(c => !catId || c.category_id == catId).forEach(c => {
                const opt = document.createElement('option');
                opt.value = c.id; opt.textContent = c.name;
                if (c.id == savedFilterComp) opt.selected = true;
                filterComp.appendChild(opt);
            });
        }
        filterCat.addEventListener('change', () => loadFilterCompanies(filterCat.value));
        loadFilterCompanies(filterCat.value);

        function applyFilter() {
            let url = 'products.php?';
            if (filterCat.value)  url += 'cat='  + filterCat.value + '&';
            if (filterComp.value) url += 'comp=' + filterComp.value;
            location.href = url;
        }
    </script>
    <?php endif; ?>

</main>

<?php require_once 'layout-footer.php'; ?>
