

<?php $__env->startSection('title', 'Category Master - Industrial Pump Logic'); ?>

<?php $__env->startSection('content'); ?>
<style>
    .status-badge {
        font-size: 11px;
        font-weight: 700;
        padding: 4px 12px;
        border-radius: 20px;
        display: inline-block;
    }
    .status-active { background: #dcfce7; color: #16a34a; }
    .status-inactive { background: #fee2e2; color: #ef4444; }
</style>
<main>
    <div class="master-container" style="flex:1; padding: 32px; overflow-y: auto;">
        <div class="header-flex" style="display:flex; justify-content:space-between; align-items:center; margin-bottom:24px;">
            <div>
                <h2 style="font-size:20px; font-weight:700; color:var(--text-main)">Category Explorer</h2>
                <p style="font-size:13px; color:var(--text-muted)">Drill down into categories to manage your 8-level hierarchy.</p>
            </div>
            <button class="btn btn-primary" onclick="openCreateModal()">
                <i data-lucide="plus" size="14"></i> Add Category
            </button>
        </div>

        <!-- Breadcrumbs Explorer -->
        <div class="explorer-nav" style="margin-bottom: 24px; padding: 12px 16px; background:white; border:1px solid var(--border); border-radius:8px; display:flex; align-items:center; gap:8px; font-size:13px;">
            <div id="breadcrumbs" style="display:flex; align-items:center; gap:8px;">
                <!-- Dynamically Generated -->
            </div>
        </div>

        <div class="card" style="background:white; border:1px solid var(--border); border-radius:12px; overflow:hidden; box-shadow:0 1px 3px rgba(0,0,0,0.05)">
            <table style="width:100%; border-collapse: collapse; text-align:left;">
                <thead>
                    <tr style="background:var(--bg-main); border-bottom:1px solid var(--border)">
                        <th style="padding:16px; font-size:11px; text-transform:uppercase; color:var(--text-muted); font-weight:700">ID</th>
                        <th style="padding:16px; font-size:11px; text-transform:uppercase; color:var(--text-muted); font-weight:700">Name</th>
                        <th style="padding:16px; font-size:11px; text-transform:uppercase; color:var(--text-muted); font-weight:700">Status</th>
                        <th style="padding:16px; font-size:11px; text-transform:uppercase; color:var(--text-muted); font-weight:700">Created At</th>
                        <th style="padding:16px; font-size:11px; text-transform:uppercase; color:var(--text-muted); font-weight:700; text-align:right">Actions</th>
                    </tr>
                </thead>
                <tbody id="category-table-body">
                    <!-- Loaded via AJAX -->
                </tbody>
            </table>
        </div>
    </div>

    <!-- Right Sidebar Form (Edit/Create) -->
    <aside class="panel properties-panel collapsed" id="right-panel" style="width: var(--properties-width); border-left: 1px solid var(--border);">
        <div class="panel-header">
            <h2 id="panel-title">Add Category</h2>
            <button class="btn" onclick="toggleRightPanel()"><i data-lucide="x" size="14"></i></button>
        </div>
        <div class="property-group">
            <input type="hidden" id="edit-id">
            <div class="field">
                <label>Parent Category (Current Context)</label>
                <div id="parent-context-display" style="font-weight:600; color:var(--primary); font-size:13px; padding:8px; background:var(--bg-main); border-radius:6px;">Root</div>
            </div>
            <div class="field">
                <label>Category Name</label>
                <input type="text" class="input" id="cat-name" placeholder="Enter name...">
            </div>
            <div class="field">
                <label>Status</label>
                <select class="input" id="cat-status">
                    <option value="1">Active</option>
                    <option value="0">Inactive</option>
                </select>
            </div>
            <div style="margin-top:20px;">
                <button class="btn btn-primary" style="width:100%; justify-content:center" onclick="saveCategory()">
                    <i data-lucide="save" size="14"></i> Save Category
                </button>
            </div>
        </div>
    </aside>
</main>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
    let currentParentId = null;
    let allCategories = [];
    let breadcrumbStack = []; // {id, name}

    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;

    function apiFetch(url, options = {}) {
        options.headers = {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': csrfToken,
            'Accept': 'application/json',
            ...options.headers
        };
        return fetch(url, options).then(res => {
            if (!res.ok) {
                return res.json().then(err => { throw new Error(err.message || 'API Error'); });
            }
            return res.status === 204 ? null : res.json();
        });
    }

    function loadData() {
        apiFetch(`${baseUrl}/admin/categories`)
            .then(data => {
                allCategories = data;
                renderView();
            });
    }

    function navigateTo(id, name) {
        currentParentId = id;
        
        // Update breadcrumb stack
        if (id === null) {
            breadcrumbStack = [];
        } else {
            const index = breadcrumbStack.findIndex(b => b.id === id);
            if (index !== -1) {
                breadcrumbStack = breadcrumbStack.slice(0, index + 1);
            } else {
                breadcrumbStack.push({id, name});
            }
        }
        
        renderView();
    }

    function renderView() {
        renderBreadcrumbs();
        renderTable();
        
        // Update add/edit context display
        const parentName = currentParentId ? (allCategories.find(c => c.id === currentParentId)?.name || 'Unknown') : 'Root';
        document.getElementById('parent-context-display').innerText = parentName;
    }

    function renderBreadcrumbs() {
        const container = document.getElementById('breadcrumbs');
        let html = `<a href="javascript:void(0)" onclick="navigateTo(null, 'Root')" style="color:var(--primary); text-decoration:none; font-weight:600">Root</a>`;
        
        breadcrumbStack.forEach(b => {
            html += ` <i data-lucide="chevron-right" size="14" style="color:var(--text-muted)"></i> 
                       <a href="javascript:void(0)" onclick="navigateTo(${b.id}, '${b.name}')" style="color:var(--primary); text-decoration:none; font-weight:600">${b.name}</a>`;
        });
        
        container.innerHTML = html;
        lucide.createIcons();
    }

    function renderTable() {
        const body = document.getElementById('category-table-body');
        const levelCategories = allCategories.filter(c => c.parent_id == currentParentId);
        
        if(levelCategories.length === 0) {
            body.innerHTML = `<tr><td colspan="4" style="padding:32px; text-align:center; color:var(--text-muted)">No child categories found here.</td></tr>`;
            return;
        }

        body.innerHTML = levelCategories.map(cat => {
            const hasChildren = allCategories.some(c => c.parent_id == cat.id);
            return `
                <tr style="border-bottom:1px solid var(--border)">
                    <td style="padding:16px; color:var(--text-muted)">#${cat.id}</td>
                    <td style="padding:16px; font-weight:600">
                        <div style="display:flex; align-items:center; gap:8px">
                            <i data-lucide="folder" size="14" style="color:#eab308"></i>
                            <a href="javascript:void(0)" onclick="navigateTo(${cat.id}, '${cat.name}')" style="text-decoration:none; color:var(--text-main); font-weight:600">${cat.name}</a>
                        </div>
                    </td>
                    <td style="padding:16px;">
                        <span class="status-badge ${cat.status ? 'status-active' : 'status-inactive'}">
                            ${cat.status ? 'Active' : 'Inactive'}
                        </span>
                    </td>
                    <td style="padding:16px; color:var(--text-muted); font-size:12px">${new Date(cat.created_at).toLocaleDateString()}</td>
                    <td style="padding:16px; text-align:right">
                        <div style="display:flex; gap:8px; justify-content:flex-end">
                            <button class="btn btn-primary" style="padding:4px 8px" onclick="navigateTo(${cat.id}, '${cat.name}')" title="Explore Children">
                                <i data-lucide="eye" size="14"></i>
                            </button>
                            <button class="btn" style="padding:4px" onclick="editCategory(${cat.id})"><i data-lucide="edit-3" size="14"></i></button>
                            <button class="btn" style="padding:4px; color:#ef4444; border-color:#fee2e2" onclick="deleteCategory(${cat.id})"><i data-lucide="trash-2" size="14"></i></button>
                        </div>
                    </td>
                </tr>
            `;
        }).join('');
        lucide.createIcons();
    }

    async function openCreateModal() {
        let choice = await showModal({
            title: 'Add New Category',
            message: 'How would you like to proceed?',
            mode: 'choice',
            choices: [
                { label: 'Create from Scratch', icon: 'edit-3', desc: 'Add a single category manually' },
                { label: 'Copy from Template', icon: 'copy', desc: 'Import structure from existing template' }
            ]
        });

        if (choice === 0) {
            document.getElementById('edit-id').value = '';
            document.getElementById('cat-name').value = '';
            document.getElementById('cat-status').value = '1';
            document.getElementById('panel-title').innerText = 'Add Category under ' + (currentParentId ? allCategories.find(c => c.id === currentParentId).name : 'Root');
            const panel = document.getElementById('right-panel');
            if(panel.classList.contains('collapsed')) toggleRightPanel();
        } else if (choice === 1) {
            openTemplatePicker();
        }
    }

    async function openTemplatePicker() {
        const templates = await apiFetch(`${baseUrl}/admin/templates/list-all`);
        
        if (templates.length === 0) {
            customAlert("No templates found to import from.");
            return;
        }

        let choice = await showModal({
            title: 'Select Template',
            message: `Importing categories under: ${currentParentId ? allCategories.find(c => c.id === currentParentId).name : 'Root'}`,
            mode: 'choice',
            choices: templates.map(t => ({
                label: t.name,
                icon: 'layout',
                desc: 'Pick this template'
            }))
        });

        if (choice !== undefined && choice !== null) {
            const template = templates[choice];
            importTemplate(template.id);
        }
    }

    async function importTemplate(templateId) {
        showModal({ title: 'Importing...', message: 'Please wait while we clone the category structure.', showCancel: false, confirmText: 'Please Wait' });
        
        apiFetch(`${baseUrl}/admin/templates/${templateId}/import`, {
            method: 'POST',
            body: JSON.stringify({ parent_id: currentParentId })
        })
        .then(() => {
            showModal({ title: 'Success', message: 'Template categories imported successfully!', type: 'success', showCancel: false });
            loadData();
        })
        .catch(err => customAlert("Import failed: " + err.message));
    }

    function editCategory(id) {
        const cat = allCategories.find(c => c.id === id);
        document.getElementById('edit-id').value = cat.id;
        document.getElementById('cat-name').value = cat.name;
        document.getElementById('cat-status').value = cat.status ? '1' : '0';
        document.getElementById('panel-title').innerText = 'Edit Category';
        const panel = document.getElementById('right-panel');
        if(panel.classList.contains('collapsed')) toggleRightPanel();
    }

    function saveCategory() {
        const id = document.getElementById('edit-id').value;
        const name = document.getElementById('cat-name').value;
        const status = document.getElementById('cat-status').value;
        const parent_id = currentParentId;

        if(!name) return customAlert('Name is required');

        const method = id ? 'PUT' : 'POST';
        const url = id ? `${baseUrl}/admin/categories/${id}` : `${baseUrl}/admin/categories`;

        apiFetch(url, {
            method: method,
            body: JSON.stringify({ name, parent_id, status })
        })
        .then(() => {
            loadData();
            toggleRightPanel();
        })
        .catch(err => customAlert("Validation Error: " + err.message));
    }

    async function deleteCategory(id) {
        let confirmed = await showModal({
            title: 'Delete Category?',
            message: 'Are you sure? All children will be automatically deleted. This action cannot be undone.',
            type: 'danger',
            confirmText: 'Delete Category'
        });

        if(!confirmed) return;

        apiFetch(`${baseUrl}/admin/categories/${id}`, { method: 'DELETE' })
            .then(() => loadData())
            .catch(err => customAlert("Error: " + err.message));
    }

    // Initial Load
    document.addEventListener('DOMContentLoaded', () => {
        loadData();
    });
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.master', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH D:\xampp\htdocs\pump-selection-backend\resources\views/pages/category-master.blade.php ENDPATH**/ ?>