/**
 * CMS Menu Management Script
 */
$(document).ready(function () {
    const apiBase = 'APIs/cms_api.php';
    let selectedMenuId = null;

    loadMenus();

    function loadMenus() {
        $.getJSON(`${apiBase}?action=get_menus`, function (res) {
            if (res.success) {
                let html = '';
                res.data.forEach(m => {
                    html += `
                        <button type="button" class="list-group-item list-group-item-action py-3 border-0 menu-item-select urdu-regular" data-id="${m.id}" data-name="${m.menu_name}">
                            <div class="d-flex justify-content-between align-items-center">
                                <span><i class="bi bi-list me-2"></i>${m.menu_name}</span>
                                <i class="bi bi-chevron-left small opacity-50"></i>
                            </div>
                        </button>
                    `;
                });
                $('#menuList').html(html || '<p class="text-center p-3 text-muted">کوئی مینیو نہیں ملا</p>');
            }
        });
    }

    $(document).on('click', '.menu-item-select', function () {
        const id = $(this).data('id');
        const name = $(this).data('name');
        selectedMenuId = id;

        $('.menu-item-select').removeClass('active bg-primary text-white');
        $(this).addClass('active bg-primary text-white');

        $('#menuEditorPlaceholder').addClass('d-none');
        $('#menuStructureCard').removeClass('d-none');
        $('#currentMenuName').text(name);

        loadMenuItems(id);
    });

    function loadMenuItems(menuId) {
        $.getJSON(`${apiBase}?action=get_menu_items&menu_id=${menuId}`, function (res) {
            if (res.success) {
                renderMenuItems(res.data);
                updateParentSelect(res.data);
            }
        });
    }

    function renderMenuItems(items) {
        let html = '';
        if (items.length === 0) {
            html = '<div class="text-center p-4 text-muted urdu-regular">اس مینیو میں کوئی آئیٹم نہیں ہے</div>';
        } else {
            // Simple flat display for now, could be improved with nesting UI
            items.forEach(item => {
                const indent = item.parent_id > 0 ? 'ms-4 border-start ps-3' : '';
                html += `
                    <div class="card border mb-2 ${indent} shadow-xs">
                        <div class="card-body p-2 d-flex justify-content-between align-items-center">
                            <div class="d-flex align-items-center">
                                <i class="bi bi-grip-vertical text-muted me-2"></i>
                                <span class="urdu-bold">${item.label}</span>
                                <span class="badge bg-light text-dark ms-2 border small font-monospace">${item.link_type === 'page' ? 'Page' : 'URL'}</span>
                            </div>
                            <div class="btn-group btn-group-sm">
                                <button class="btn btn-link text-primary btn-edit-item" data-item='${JSON.stringify(item)}'><i class="bi bi-pencil"></i></button>
                                <button class="btn btn-link text-danger btn-delete-item" data-id="${item.id}"><i class="bi bi-trash"></i></button>
                            </div>
                        </div>
                    </div>
                `;
            });
        }
        $('#menuItemsContainer').html(html);
    }

    function updateParentSelect(items) {
        let html = '<option value="0">کوئی نہیں (Root)</option>';
        items.filter(i => i.parent_id == 0).forEach(i => {
            html += `<option value="${i.id}">${i.label}</option>`;
        });
        $('#parentSelect').html(html);
    }

    $('#btnNewMenu').on('click', function () {
        $('#menuForm')[0].reset();
        $('#menuId').val('');
        $('#menuModalTitle').text('نیا مینیو');
        $('#menuModal').modal('show');
    });

    $('#menuForm').on('submit', function (e) {
        e.preventDefault();
        const data = {
            action: 'save_menu',
            id: $('#menuId').val(),
            name: $('#menuName').val()
        };

        $.ajax({
            url: apiBase,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function (res) {
                if (res.success) {
                    $('#menuModal').modal('hide');
                    loadMenus();
                    Swal.fire('کامیابی', 'مینیو محفوظ کرلیا گیا', 'success');
                }
            }
        });
    });

    $('#btnAddMenuItem').on('click', function () {
        if (!selectedMenuId) return;
        $('#menuItemForm')[0].reset();
        $('#menuItemId').val('');

        // Load pages for selection
        $.getJSON(`APIs/cms_api.php?action=get_pages`, function (res) {
            if (res.success) {
                let html = '';
                res.data.forEach(p => {
                    html += `<option value="${p.id}">${p.title}</option>`;
                });
                $('#pageSelect').html(html);
            }
        });

        $('#menuItemModal').modal('show');
    });

    $(document).on('click', '.btn-edit-item', function () {
        const item = $(this).data('item');
        $('#menuItemId').val(item.id);
        $('#itemLabel').val(item.label);
        $('#linkType').val(item.link_type).change();
        $('#parentSelect').val(item.parent_id);

        if (item.link_type === 'page') {
            // Load pages then set value
            $.getJSON(`APIs/cms_api.php?action=get_pages`, function (res) {
                if (res.success) {
                    let html = '';
                    res.data.forEach(p => {
                        html += `<option value="${p.id}">${p.title}</option>`;
                    });
                    $('#pageSelect').html(html).val(item.page_id);
                }
            });
        } else {
            $('#customUrl').val(item.custom_url);
        }

        $('#menuItemModal').modal('show');
    });

    $('#linkType').on('change', function () {
        if ($(this).val() === 'page') {
            $('#pageSelectDiv').removeClass('d-none');
            $('#customUrlDiv').addClass('d-none');
        } else {
            $('#pageSelectDiv').addClass('d-none');
            $('#customUrlDiv').removeClass('d-none');
        }
    });

    $('#menuItemForm').on('submit', function (e) {
        e.preventDefault();
        const data = {
            action: 'save_menu_item',
            id: $('#menuItemId').val(),
            menu_id: selectedMenuId,
            label: $('#itemLabel').val(),
            link_type: $('#linkType').val(),
            page_id: $('#pageSelect').val(),
            custom_url: $('#customUrl').val(),
            parent_id: $('#parentSelect').val()
        };

        $.ajax({
            url: apiBase,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function (res) {
                if (res.success) {
                    $('#menuItemModal').modal('hide');
                    loadMenuItems(selectedMenuId);
                }
            }
        });
    });

    $(document).on('click', '.btn-delete-item', function () {
        const id = $(this).data('id');
        Swal.fire({
            title: 'کیا آپ واقعی یہ آئیٹم مٹانا چاہتے ہیں؟',
            icon: 'warning',
            showCancelButton: true
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: apiBase,
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({ action: 'delete_menu_item', id: id }),
                    success: function (res) {
                        if (res.success) loadMenuItems(selectedMenuId);
                    }
                });
            }
        });
    });
});
