<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Catalogue Management - Superadmin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        * { font-family: 'Poppins', sans-serif; }
        body { background: #f5f5f5; }
        .sidebar {
            min-height: 100vh;
            background: linear-gradient(180deg, #1a237e 0%, #0d47a1 100%);
            box-shadow: 2px 0 10px rgba(0,0,0,0.1);
        }
        .sidebar .nav-link {
            color: rgba(255,255,255,0.85);
            padding: 14px 20px;
            border-radius: 10px;
            margin: 6px 0;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover, .sidebar .nav-link.active {
            background: rgba(255,255,255,0.15);
            color: #fff;
            transform: translateX(5px);
        }
        .sidebar .nav-link i { margin-right: 10px; width: 20px; }
        .card { border: none; border-radius: 15px; box-shadow: 0 2px 15px rgba(0,0,0,0.08); }
        .card-header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 15px 15px 0 0 !important; }
        .table-hover tbody tr:hover { background-color: #f8f9fa; }
        .badge-delete { cursor: pointer; }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 px-0 sidebar">
                <div class="p-3">
                    <h4 class="text-white mb-4"><i class="bi bi-shield-check"></i> Super Admin</h4>
                    <nav class="nav flex-column">
                        <a href="<?= base_url('superadmin/dashboard') ?>" class="nav-link">
                            <i class="bi bi-speedometer2"></i> Dashboard
                        </a>
                        <a href="<?= base_url('superadmin/users') ?>" class="nav-link">
                            <i class="bi bi-people"></i> Users
                        </a>
                        <a href="<?= base_url('superadmin/admins') ?>" class="nav-link">
                            <i class="bi bi-person-badge"></i> Admins
                        </a>
                        <a href="<?= base_url('superadmin/settings') ?>" class="nav-link">
                            <i class="bi bi-gear"></i> Settings
                        </a>
                        <a href="<?= base_url('superadmin/reports') ?>" class="nav-link">
                            <i class="bi bi-file-earmark-text"></i> Reports
                        </a>
                        <a href="<?= base_url('superadmin/manageTaxonomy') ?>" class="nav-link active">
                            <i class="bi bi-tags"></i> Catalogue
                        </a>
                        <a href="<?= base_url('superadmin/manageSubscriptionLimits') ?>" class="nav-link">
                            <i class="bi bi-card-list"></i> Subscription Limits
                        </a>
                        <a href="<?= base_url('superadmin/managePostingLimits') ?>" class="nav-link">
                            <i class="bi bi-clock-history"></i> Posting Limits
                        </a>
                        <a href="<?= base_url('auth/logout') ?>" class="nav-link mt-4">
                            <i class="bi bi-box-arrow-right"></i> Logout
                        </a>
                    </nav>
                </div>
            </div>

            <!-- Main Content -->
            <div class="col-md-9 col-lg-10 p-4">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <div>
                        <h2><i class="bi bi-tags"></i> Catalogue Management</h2>
                        <p class="text-muted mb-0">Manage Listing Types, Product Types, Categories & Sub-Categories</p>
                    </div>
                </div>

                <!-- Listing Types Section -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="bi bi-tag"></i> Listing Types</h5>
                    </div>
                    <div class="card-body">
                        <form id="formListingType" class="row g-3 mb-3">
                            <?= csrf_field() ?>
                            <div class="col-md-8">
                                <input type="text" name="name" class="form-control" placeholder="Enter Listing Type Name (e.g., Clothing, Electronics)" required>
                            </div>
                            <div class="col-md-4">
                                <button type="submit" class="btn btn-primary w-100"><i class="bi bi-plus-circle"></i> Add Listing Type</button>
                            </div>
                        </form>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Name</th>
                                        <th>Created</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody id="listingTypesTable">
                                    <?php if (!empty($listing_types)): ?>
                                        <?php foreach ($listing_types as $lt): ?>
                                            <tr>
                                                <td><?= $lt['id'] ?></td>
                                                <td><strong><?= esc($lt['type_name'] ?? $lt['name'] ?? '') ?></strong></td>
                                                <td><?= isset($lt['created_at']) ? date('M d, Y', strtotime($lt['created_at'])) : 'N/A' ?></td>
                                                <td>
                                                    <span class="badge bg-primary me-1" style="cursor: pointer;" onclick="editListingType(<?= $lt['id'] ?>, '<?= esc($lt['type_name'] ?? $lt['name'] ?? '') ?>')">
                                                        <i class="bi bi-pencil"></i> Edit
                                                    </span>
                                                    <span class="badge bg-danger" style="cursor: pointer;" onclick="deleteItem('listing_types', <?= $lt['id'] ?>)">
                                                        <i class="bi bi-trash"></i> Delete
                                                    </span>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr><td colspan="4" class="text-center text-muted">No listing types yet</td></tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Product Types Section -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="bi bi-box"></i> Product Types</h5>
                    </div>
                    <div class="card-body">
                        <form id="formProductType" class="row g-3 mb-3">
                            <?= csrf_field() ?>
                            <div class="col-md-4">
                                <select name="listing_type_id" class="form-select" required>
                                    <option value="">Select Listing Type</option>
                                    <?php foreach ($listing_types as $lt): ?>
                                        <option value="<?= $lt['id'] ?>"><?= esc($lt['type_name'] ?? $lt['name'] ?? '') ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <input type="text" name="name" class="form-control" placeholder="Product Type Name (e.g., Men, Women)" required>
                            </div>
                            <div class="col-md-4">
                                <button type="submit" class="btn btn-primary w-100"><i class="bi bi-plus-circle"></i> Add Product Type</button>
                            </div>
                        </form>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Product Type</th>
                                        <th>Listing Type</th>
                                        <th>Created</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody id="productTypesTable">
                                    <?php if (!empty($product_types)): ?>
                                        <?php foreach ($product_types as $pt): ?>
                                            <tr>
                                                <td><?= $pt['id'] ?></td>
                                                <td><strong><?= esc($pt['name']) ?></strong></td>
                                                <td>
                                                    <?php 
                                                        $lt = array_filter($listing_types, fn($l) => $l['id'] == $pt['listing_type_id']);
                                                        $lt = reset($lt);
                                                        echo $lt ? esc($lt['type_name'] ?? $lt['name'] ?? '') : 'N/A';
                                                    ?>
                                                </td>
                                                <td><?= isset($pt['created_at']) ? date('M d, Y', strtotime($pt['created_at'])) : 'N/A' ?></td>
                                                <td>
                                                    <span class="badge bg-primary me-1" style="cursor: pointer;" onclick="editProductType(<?= $pt['id'] ?>, '<?= esc($pt['name']) ?>', <?= $pt['listing_type_id'] ?>)">
                                                        <i class="bi bi-pencil"></i> Edit
                                                    </span>
                                                    <span class="badge bg-danger" style="cursor: pointer;" onclick="deleteItem('product_types', <?= $pt['id'] ?>)">
                                                        <i class="bi bi-trash"></i> Delete
                                                    </span>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr><td colspan="5" class="text-center text-muted">No product types yet</td></tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Categories Section -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="bi bi-grid"></i> Categories</h5>
                    </div>
                    <div class="card-body">
                        <form id="formCategory" class="row g-3 mb-3">
                            <?= csrf_field() ?>
                            <div class="col-md-4">
                                <select name="product_type_id" class="form-select">
                                    <option value="">Product Type (Optional)</option>
                                    <?php foreach ($product_types as $pt): ?>
                                        <option value="<?= $pt['id'] ?>"><?= esc($pt['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <input type="text" name="category_name" class="form-control" placeholder="Category Name (e.g., T-Shirts)" required>
                            </div>
                            <div class="col-md-4">
                                <button type="submit" class="btn btn-primary w-100"><i class="bi bi-plus-circle"></i> Add Category</button>
                            </div>
                        </form>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Category Name</th>
                                        <th>Product Type</th>
                                        <th>Created</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody id="categoriesTable">
                                    <?php if (!empty($categories)): ?>
                                        <?php foreach ($categories as $c): ?>
                                            <tr>
                                                <td><?= $c['id'] ?></td>
                                                <td><strong><?= esc($c['category_name'] ?? $c['name'] ?? '') ?></strong></td>
                                                <td>
                                                        <?php 
                                                        // Check both product_type_id (current schema) and parent_id (hierarchical schema)
                                                        $productTypeId = $c['product_type_id'] ?? $c['parent_id'] ?? null;
                                                        if ($productTypeId) {
                                                            $pt = array_filter($product_types, fn($p) => $p['id'] == $productTypeId);
                                                                $pt = reset($pt);
                                                                echo $pt ? esc($pt['name']) : 'N/A';
                                                            } else {
                                                                echo 'All';
                                                            }
                                                        ?>
                                                </td>
                                                <td><?= isset($c['created_at']) ? date('M d, Y', strtotime($c['created_at'])) : 'N/A' ?></td>
                                                <td>
                                                    <span class="badge bg-primary me-1" style="cursor: pointer;" onclick="editCategory(<?= $c['id'] ?>, '<?= esc($c['category_name'] ?? $c['name'] ?? '') ?>', <?= $c['product_type_id'] ?? $c['parent_id'] ?? 'null' ?>)">
                                                        <i class="bi bi-pencil"></i> Edit
                                                    </span>
                                                    <span class="badge bg-danger" style="cursor: pointer;" onclick="deleteItem('categories', <?= $c['id'] ?>)">
                                                        <i class="bi bi-trash"></i> Delete
                                                    </span>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr><td colspan="5" class="text-center text-muted">No categories yet</td></tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Sub-Categories Section -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="bi bi-list-nested"></i> Sub-Categories</h5>
                    </div>
                    <div class="card-body">
                        <form id="formSubCategory" class="row g-3 mb-3">
                            <?= csrf_field() ?>
                            <div class="col-md-4">
                                <select name="category_id" class="form-select" required>
                                    <option value="">Select Category</option>
                                    <?php foreach ($categories as $c): ?>
                                        <option value="<?= $c['id'] ?>"><?= esc($c['category_name'] ?? $c['name'] ?? '') ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <input type="text" name="name" class="form-control" placeholder="Sub-Category Name (e.g., Round Neck)" required>
                            </div>
                            <div class="col-md-4">
                                <button type="submit" class="btn btn-primary w-100"><i class="bi bi-plus-circle"></i> Add Sub-Category</button>
                            </div>
                        </form>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Sub-Category Name</th>
                                        <th>Category</th>
                                        <th>Created</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody id="subCategoriesTable">
                                    <?php if (!empty($sub_categories)): ?>
                                        <?php foreach ($sub_categories as $sc): ?>
                                            <tr>
                                                <td><?= $sc['id'] ?></td>
                                                <td><strong><?= esc($sc['name']) ?></strong></td>
                                                <td>
                                                    <?php 
                                                        $cat = array_filter($categories, fn($c) => $c['id'] == $sc['category_id']);
                                                        $cat = reset($cat);
                                                        echo $cat ? esc($cat['category_name'] ?? $cat['name'] ?? '') : 'N/A';
                                                    ?>
                                                </td>
                                                <td><?= isset($sc['created_at']) ? date('M d, Y', strtotime($sc['created_at'])) : 'N/A' ?></td>
                                                <td>
                                                    <span class="badge bg-primary me-1" style="cursor: pointer;" onclick="editSubCategory(<?= $sc['id'] ?>, '<?= esc($sc['name']) ?>', <?= $sc['category_id'] ?>)">
                                                        <i class="bi bi-pencil"></i> Edit
                                                    </span>
                                                    <span class="badge bg-danger" style="cursor: pointer;" onclick="deleteItem('sub_categories', <?= $sc['id'] ?>)">
                                                        <i class="bi bi-trash"></i> Delete
                                                    </span>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr><td colspan="5" class="text-center text-muted">No sub-categories yet</td></tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Add Listing Type
        document.getElementById('formListingType').addEventListener('submit', async function(e) {
            e.preventDefault();
            const fd = new FormData(this);
            try {
                const res = await fetch('<?= base_url('superadmin/add-listing-type') ?>', { method: 'POST', body: fd });
                const data = await res.json();
                if (data.success) {
                    Swal.fire({ icon: 'success', title: 'Success!', text: data.message, timer: 1500 });
                    setTimeout(() => location.reload(), 1500);
                } else {
                    Swal.fire({ icon: 'error', title: 'Error', text: data.message || 'Failed to add listing type' });
                }
            } catch (err) {
                Swal.fire({ icon: 'error', title: 'Error', text: 'Network error' });
            }
        });

        // Add Product Type
        document.getElementById('formProductType').addEventListener('submit', async function(e) {
            e.preventDefault();
            const fd = new FormData(this);
            try {
                const res = await fetch('<?= base_url('superadmin/add-product-type') ?>', { method: 'POST', body: fd });
                const data = await res.json();
                if (data.success) {
                    Swal.fire({ icon: 'success', title: 'Success!', text: data.message, timer: 1500 });
                    setTimeout(() => location.reload(), 1500);
                } else {
                    Swal.fire({ icon: 'error', title: 'Error', text: data.message || 'Failed to add product type' });
                }
            } catch (err) {
                Swal.fire({ icon: 'error', title: 'Error', text: 'Network error' });
            }
        });

        // Add Category
        document.getElementById('formCategory').addEventListener('submit', async function(e) {
            e.preventDefault();
            const fd = new FormData(this);
            try {
                const res = await fetch('<?= base_url('superadmin/add-category') ?>', { method: 'POST', body: fd });
                const data = await res.json();
                if (data.success) {
                    Swal.fire({ icon: 'success', title: 'Success!', text: data.message, timer: 1500 });
                    setTimeout(() => location.reload(), 1500);
                } else {
                    Swal.fire({ icon: 'error', title: 'Error', text: data.message || 'Failed to add category' });
                }
            } catch (err) {
                Swal.fire({ icon: 'error', title: 'Error', text: 'Network error' });
            }
        });

        // Add Sub-Category
        document.getElementById('formSubCategory').addEventListener('submit', async function(e) {
            e.preventDefault();
            const fd = new FormData(this);
            try {
                const res = await fetch('<?= base_url('superadmin/add-sub-category') ?>', { method: 'POST', body: fd });
                const data = await res.json();
                if (data.success) {
                    Swal.fire({ icon: 'success', title: 'Success!', text: data.message, timer: 1500 });
                    setTimeout(() => location.reload(), 1500);
                } else {
                    Swal.fire({ icon: 'error', title: 'Error', text: data.message || 'Failed to add sub-category' });
                }
            } catch (err) {
                Swal.fire({ icon: 'error', title: 'Error', text: 'Network error' });
            }
        });

        // Delete function - calls server endpoints
        async function deleteItem(table, id) {
            const mapping = {
                'listing_types': 'remove-listing-type',
                'product_types': 'remove-product-type',
                'categories': 'remove-category',
                'sub_categories': 'remove-sub-category'
            };

            const route = mapping[table];
            if (!route) return Swal.fire({ icon: 'error', title: 'Error', text: 'Unknown item type' });

            const confirmed = await Swal.fire({
                title: 'Are you sure?',
                text: "This action cannot be undone.",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Yes, delete it!'
            });

            if (!confirmed.isConfirmed) return;

            // collect CSRF hidden inputs from existing forms
            const fd = new FormData();
            document.querySelectorAll('form input[type=hidden]').forEach(inp => {
                if (inp.name && inp.value) fd.append(inp.name, inp.value);
            });

            try {
                const res = await fetch('<?= base_url('superadmin') ?>/' + route + '/' + id, { method: 'POST', body: fd, credentials: 'same-origin' });
                const data = await res.json();
                if (data.success) {
                    Swal.fire({ icon: 'success', title: 'Deleted', text: data.message, timer: 1200 });
                    setTimeout(() => location.reload(), 1200);
                } else {
                    Swal.fire({ icon: 'error', title: 'Error', text: data.message || 'Delete failed' });
                }
            } catch (err) {
                Swal.fire({ icon: 'error', title: 'Error', text: 'Network error' });
            }
        }

        // Edit functions
        async function editListingType(id, currentName) {
            const { value: name } = await Swal.fire({
                title: 'Edit Listing Type',
                input: 'text',
                inputLabel: 'Listing Type Name',
                inputValue: currentName,
                showCancelButton: true,
                inputValidator: (value) => {
                    if (!value) return 'Please enter a name!';
                }
            });

            if (!name) return;

            const fd = new FormData();
            fd.append('type_name', name);
            document.querySelectorAll('form input[type=hidden]').forEach(inp => {
                if (inp.name && inp.value) fd.append(inp.name, inp.value);
            });

            try {
                const res = await fetch('<?= base_url('superadmin/update-listing-type') ?>/' + id, { method: 'POST', body: fd });
                const data = await res.json();
                if (data.success) {
                    Swal.fire({ icon: 'success', title: 'Updated!', text: data.message, timer: 1200 });
                    setTimeout(() => location.reload(), 1200);
                } else {
                    Swal.fire({ icon: 'error', title: 'Error', text: data.message });
                }
            } catch (err) {
                Swal.fire({ icon: 'error', title: 'Error', text: 'Network error' });
            }
        }

        async function editProductType(id, currentName, currentListingTypeId) {
            const listingTypesOptions = <?= json_encode(array_map(fn($lt) => ['value' => $lt['id'], 'text' => $lt['type_name'] ?? $lt['name'] ?? ''], $listing_types)) ?>;
            const optionsHtml = listingTypesOptions.map(opt => 
                `<option value="${opt.value}" ${opt.value == currentListingTypeId ? 'selected' : ''}>${opt.text}</option>`
            ).join('');

            const { value: formValues } = await Swal.fire({
                title: 'Edit Product Type',
                html:
                    `<input id="swal-input1" class="swal2-input" placeholder="Product Type Name" value="${currentName}">` +
                    `<select id="swal-input2" class="swal2-input" style="width: 80%;">${optionsHtml}</select>`,
                focusConfirm: false,
                showCancelButton: true,
                preConfirm: () => {
                    return {
                        name: document.getElementById('swal-input1').value,
                        listing_type_id: document.getElementById('swal-input2').value
                    };
                }
            });

            if (!formValues || !formValues.name) return;

            const fd = new FormData();
            fd.append('name', formValues.name);
            fd.append('listing_type_id', formValues.listing_type_id);
            document.querySelectorAll('form input[type=hidden]').forEach(inp => {
                if (inp.name && inp.value) fd.append(inp.name, inp.value);
            });

            try {
                const res = await fetch('<?= base_url('superadmin/update-product-type') ?>/' + id, { method: 'POST', body: fd });
                const data = await res.json();
                if (data.success) {
                    Swal.fire({ icon: 'success', title: 'Updated!', text: data.message, timer: 1200 });
                    setTimeout(() => location.reload(), 1200);
                } else {
                    Swal.fire({ icon: 'error', title: 'Error', text: data.message });
                }
            } catch (err) {
                Swal.fire({ icon: 'error', title: 'Error', text: 'Network error' });
            }
        }

        async function editCategory(id, currentName, currentProductTypeId) {
            const productTypesOptions = <?= json_encode(array_map(fn($pt) => ['value' => $pt['id'], 'text' => $pt['name']], $product_types)) ?>;
            const optionsHtml = '<option value="">All</option>' + productTypesOptions.map(opt => 
                `<option value="${opt.value}" ${opt.value == currentProductTypeId ? 'selected' : ''}>${opt.text}</option>`
            ).join('');

            const { value: formValues } = await Swal.fire({
                title: 'Edit Category',
                html:
                    `<input id="swal-input1" class="swal2-input" placeholder="Category Name" value="${currentName}">` +
                    `<select id="swal-input2" class="swal2-input" style="width: 80%;"><option value="">Product Type (Optional)</option>${optionsHtml}</select>`,
                focusConfirm: false,
                showCancelButton: true,
                preConfirm: () => {
                    return {
                        category_name: document.getElementById('swal-input1').value,
                        product_type_id: document.getElementById('swal-input2').value
                    };
                }
            });

            if (!formValues || !formValues.category_name) return;

            const fd = new FormData();
            fd.append('category_name', formValues.category_name);
            fd.append('product_type_id', formValues.product_type_id || '');
            document.querySelectorAll('form input[type=hidden]').forEach(inp => {
                if (inp.name && inp.value) fd.append(inp.name, inp.value);
            });

            try {
                const res = await fetch('<?= base_url('superadmin/update-category') ?>/' + id, { method: 'POST', body: fd });
                const data = await res.json();
                if (data.success) {
                    Swal.fire({ icon: 'success', title: 'Updated!', text: data.message, timer: 1200 });
                    setTimeout(() => location.reload(), 1200);
                } else {
                    Swal.fire({ icon: 'error', title: 'Error', text: data.message });
                }
            } catch (err) {
                Swal.fire({ icon: 'error', title: 'Error', text: 'Network error' });
            }
        }

        async function editSubCategory(id, currentName, currentCategoryId) {
            const categoriesOptions = <?= json_encode(array_map(fn($c) => ['value' => $c['id'], 'text' => $c['category_name'] ?? $c['name'] ?? ''], $categories)) ?>;
            const optionsHtml = categoriesOptions.map(opt => 
                `<option value="${opt.value}" ${opt.value == currentCategoryId ? 'selected' : ''}>${opt.text}</option>`
            ).join('');

            const { value: formValues } = await Swal.fire({
                title: 'Edit Sub-Category',
                html:
                    `<input id="swal-input1" class="swal2-input" placeholder="Sub-Category Name" value="${currentName}">` +
                    `<select id="swal-input2" class="swal2-input" style="width: 80%;">${optionsHtml}</select>`,
                focusConfirm: false,
                showCancelButton: true,
                preConfirm: () => {
                    return {
                        name: document.getElementById('swal-input1').value,
                        category_id: document.getElementById('swal-input2').value
                    };
                }
            });

            if (!formValues || !formValues.name) return;

            const fd = new FormData();
            fd.append('name', formValues.name);
            fd.append('category_id', formValues.category_id);
            document.querySelectorAll('form input[type=hidden]').forEach(inp => {
                if (inp.name && inp.value) fd.append(inp.name, inp.value);
            });

            try {
                const res = await fetch('<?= base_url('superadmin/update-sub-category') ?>/' + id, { method: 'POST', body: fd });
                const data = await res.json();
                if (data.success) {
                    Swal.fire({ icon: 'success', title: 'Updated!', text: data.message, timer: 1200 });
                    setTimeout(() => location.reload(), 1200);
                } else {
                    Swal.fire({ icon: 'error', title: 'Error', text: data.message });
                }
            } catch (err) {
                Swal.fire({ icon: 'error', title: 'Error', text: 'Network error' });
            }
        }
    </script>
</body>
</html>
