<?php
// This file is included by the AdminController, which will handle the layout
// No need to set variables here as they're already set in the controller
?>

<div class="admin-card">
    <div class="flex justify-between items-center mb-6">
        <h2 class="text-xl font-semibold">Edit Menu: <?= htmlspecialchars($menuData['name']) ?></h2>
        <a href="/admin/menus" class="btn-secondary">
            <i class="fas fa-arrow-left mr-2"></i>Back to Menus
        </a>
    </div>
    
    <?php if (isset($error) && !empty($error)): ?>
    <div class="bg-red-800 text-white p-4 rounded-md mb-6">
        <i class="fas fa-exclamation-circle mr-2"></i> <?= htmlspecialchars($error) ?>
    </div>
    <?php endif; ?>
    
    <?php if (isset($success) && $success): ?>
    <div class="bg-green-800 text-white p-4 rounded-md mb-6">
        <i class="fas fa-check-circle mr-2"></i> Menu updated successfully!
    </div>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['admin_error'])): ?>
    <div class="bg-red-800 text-white p-4 rounded-md mb-6">
        <i class="fas fa-exclamation-circle mr-2"></i> <?= htmlspecialchars($_SESSION['admin_error']) ?>
    </div>
    <?php unset($_SESSION['admin_error']); ?>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['admin_success'])): ?>
    <div class="bg-green-800 text-white p-4 rounded-md mb-6">
        <i class="fas fa-check-circle mr-2"></i> <?= htmlspecialchars($_SESSION['admin_success']) ?>
    </div>
    <?php unset($_SESSION['admin_success']); ?>
    <?php endif; ?>
    
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Menu Settings -->
        <div class="lg:col-span-1">
            <div class="bg-dark p-4 rounded-lg mb-6">
                <h3 class="text-lg font-medium mb-4">Menu Settings</h3>
                
                <form method="POST" action="/admin/menus/edit?id=<?= $menuData['id'] ?>" class="admin-form">
                    <input type="hidden" name="action" value="update_menu">
                    
                    <div class="mb-4">
                        <label for="name" class="block mb-2">Menu Name</label>
                        <input type="text" id="name" name="name" value="<?= htmlspecialchars($menuData['name']) ?>" required>
                    </div>
                    
                    <div class="mb-4">
                        <label for="location" class="block mb-2">Menu Location</label>
                        <select id="location" name="location">
                            <option value="">Not assigned</option>
                            <option value="header" <?= $menuData['location'] === 'header' ? 'selected' : '' ?>>Header</option>
                            <option value="footer" <?= $menuData['location'] === 'footer' ? 'selected' : '' ?>>Footer</option>
                        </select>
                        <p class="text-sm text-gray-400 mt-1">Choose where to display this menu on your site.</p>
                    </div>
                    
                    <button type="submit" class="btn-primary w-full">
                        <i class="fas fa-save mr-2"></i>Save Settings
                    </button>
                </form>
            </div>
            
            <div class="bg-dark p-4 rounded-lg">
                <h3 class="text-lg font-medium mb-4">Add Menu Item</h3>
                
                <div class="admin-form mb-4">
                    <label for="item_type" class="block mb-2">Item Type</label>
                    <select id="item_type" class="w-full" required>
                        <option value="">Select type</option>
                        <option value="custom">Custom Link</option>
                        <option value="page">Page</option>
                    </select>
                </div>
                
                <!-- Custom Link Form -->
                <form id="custom_link_form" method="POST" action="/admin/menus/edit?id=<?= $menuData['id'] ?>" class="item-form admin-form">
                    <input type="hidden" name="action" value="add_item">
                    <input type="hidden" name="item_type" value="custom">
                    
                    <div class="mb-4">
                        <label for="item_title" class="block mb-2">Title</label>
                        <input type="text" id="item_title" name="item_title" required>
                    </div>
                    
                    <div class="mb-4">
                        <label for="item_icon" class="block mb-2">Icon (Optional)</label>
                        <div class="flex gap-2">
                            <input type="text" id="item_icon" name="item_icon" placeholder="e.g. fas fa-home" class="flex-1">
                            <button type="button" class="btn-secondary icon-picker-btn" data-target="item_icon">
                                <i class="fas fa-icons"></i>
                            </button>
                        </div>
                        <p class="text-sm text-gray-400 mt-1">Enter Font Awesome icon class or click the icon button to select</p>
                    </div>
                    
                    <div class="mb-4">
                        <label for="item_url" class="block mb-2">URL</label>
                        <input type="text" id="item_url" name="item_url" required>
                    </div>
                    
                    <div class="mb-4">
                        <label for="item_target" class="block mb-2">Open in</label>
                        <select id="item_target" name="item_target">
                            <option value="_self">Same Window</option>
                            <option value="_blank">New Window</option>
                        </select>
                    </div>
                    
                    <button type="submit" class="btn-primary w-full">
                        <i class="fas fa-plus mr-2"></i>Add to Menu
                    </button>
                </form>
                
                <!-- Page Link Form -->
                <form id="page_link_form" method="POST" action="/admin/menus/edit?id=<?= $menuData['id'] ?>" class="item-form admin-form" style="display: none;">
                    <input type="hidden" name="action" value="add_item">
                    <input type="hidden" name="item_type" value="page">
                    
                    <div class="mb-4">
                        <label for="page_id" class="block mb-2">Select Page</label>
                        <select id="page_id" name="page_id" required>
                            <option value="">Select a page</option>
                            <?php foreach ($pages as $page): ?>
                            <option value="<?= $page['id'] ?>"><?= htmlspecialchars($page['title']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="mb-4">
                        <label for="page_item_title" class="block mb-2">Custom Title (Optional)</label>
                        <input type="text" id="page_item_title" name="item_title">
                        <p class="text-sm text-gray-400 mt-1">Leave empty to use the page title.</p>
                    </div>
                    
                    <div class="mb-4">
                        <label for="page_item_icon" class="block mb-2">Icon (Optional)</label>
                        <div class="flex gap-2">
                            <input type="text" id="page_item_icon" name="item_icon" placeholder="e.g. fas fa-home" class="flex-1">
                            <button type="button" class="btn-secondary icon-picker-btn" data-target="page_item_icon">
                                <i class="fas fa-icons"></i>
                            </button>
                        </div>
                        <p class="text-sm text-gray-400 mt-1">Enter Font Awesome icon class or click the icon button to select</p>
                    </div>
                    
                    <div class="mb-4">
                        <label for="page_item_target" class="block mb-2">Open in</label>
                        <select id="page_item_target" name="item_target">
                            <option value="_self">Same Window</option>
                            <option value="_blank">New Window</option>
                        </select>
                    </div>
                    
                    <button type="submit" class="btn-primary w-full">
                        <i class="fas fa-plus mr-2"></i>Add to Menu
                    </button>
                </form>
            </div>
        </div>
        
        <!-- Menu Structure -->
        <div class="lg:col-span-2">
            <div class="bg-dark p-4 rounded-lg">
                <h3 class="text-lg font-medium mb-4">Menu Structure</h3>
                
                <?php if (empty($menuItems)): ?>
                <div class="text-center py-8 text-gray-400">
                    <i class="fas fa-info-circle text-2xl mb-2"></i>
                    <p>Your menu is empty. Add items using the form on the left.</p>
                </div>
                <?php else: ?>
                <form id="menu_structure_form" method="POST" action="/admin/menus/edit?id=<?= $menuData['id'] ?>">
                    <input type="hidden" name="action" value="update_items_order">
                    
                    <div id="menu_items_container" class="mb-4">
                        <ul id="menu_items" class="menu-items-sortable">
                            <?php foreach ($menuItems as $item): ?>
                            <li class="menu-item" data-id="<?= $item['id'] ?>">
                                <div class="menu-item-header">
                                    <div class="menu-item-title">
                                        <i class="fas fa-bars handle mr-2"></i>
                                        <span><?= htmlspecialchars($item['title']) ?></span>
                                    </div>
                                    <div class="menu-item-actions">
                                        <button type="button" class="edit-item-btn" title="Edit">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button type="button" class="delete-item-btn" title="Delete" data-id="<?= $item['id'] ?>" data-menu-id="<?= $menuData['id'] ?>">
                                            <i class="fas fa-trash-alt"></i>
                                        </button>
                                    </div>
                                </div>
                                <div class="menu-item-edit" style="display: none;">
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                                        <div class="bg-darker rounded-lg p-4">
                                            <label class="block mb-2 font-medium">Title</label>
                                            <input type="text" class="admin-form item-title w-full bg-dark border border-gray-700 rounded-lg" value="<?= htmlspecialchars($item['title']) ?>" data-id="<?= $item['id'] ?>">
                                        </div>
                                        <div class="bg-darker rounded-lg p-4">
                                            <label class="block mb-2 font-medium">URL</label>
                                            <input type="text" class="admin-form item-url w-full bg-dark border border-gray-700 rounded-lg" value="<?= htmlspecialchars($item['url']) ?>" data-id="<?= $item['id'] ?>">
                                        </div>
                                    </div>
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                                        <div class="bg-darker rounded-lg p-4">
                                            <label class="block mb-2 font-medium">Icon</label>
                                            <div class="flex gap-2">
                                                <input type="text" class="admin-form item-icon flex-1 bg-dark border border-gray-700 rounded-lg" value="<?= htmlspecialchars($item['icon'] ?? '') ?>" data-id="<?= $item['id'] ?>" placeholder="e.g. fas fa-home">
                                                <button type="button" class="btn-secondary icon-picker-btn px-3 rounded-lg" data-target="item-icon-<?= $item['id'] ?>">
                                                    <i class="fas fa-icons"></i>
                                                </button>
                                            </div>
                                        </div>
                                        <div class="bg-darker rounded-lg p-4">
                                            <label class="block mb-2 font-medium">Open in</label>
                                            <select class="admin-form item-target w-full bg-dark border border-gray-700 rounded-lg" data-id="<?= $item['id'] ?>">
                                                <option value="_self" <?= $item['target'] === '_self' ? 'selected' : '' ?>>Same Window</option>
                                                <option value="_blank" <?= $item['target'] === '_blank' ? 'selected' : '' ?>>New Window</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="flex justify-end gap-2 mt-4">
                                        <button type="button" class="btn-secondary btn-sm cancel-edit-btn px-4 py-2 rounded-lg">
                                            Cancel
                                        </button>
                                        <button type="button" class="btn-primary btn-sm save-item-btn px-4 py-2 rounded-lg" data-id="<?= $item['id'] ?>" data-menu-id="<?= $menuData['id'] ?>">
                                            Save Changes
                                        </button>
                                    </div>
                                </div>
                                
                                <?php if (!empty($item['children'])): ?>
                                <ul class="menu-items-sortable submenu">
                                    <?php foreach ($item['children'] as $child): ?>
                                    <li class="menu-item" data-id="<?= $child['id'] ?>">
                                        <div class="menu-item-header">
                                            <div class="menu-item-title">
                                                <i class="fas fa-bars handle mr-2"></i>
                                                <span><?= htmlspecialchars($child['title']) ?></span>
                                            </div>
                                            <div class="menu-item-actions">
                                                <button type="button" class="edit-item-btn" title="Edit">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button type="button" class="delete-item-btn" title="Delete" data-id="<?= $child['id'] ?>" data-menu-id="<?= $menuData['id'] ?>">
                                                    <i class="fas fa-trash-alt"></i>
                                                </button>
                                            </div>
                                        </div>
                                        <div class="menu-item-edit" style="display: none;">
                                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-2">
                                                <div>
                                                    <label class="block mb-1 text-sm">Title</label>
                                                    <input type="text" class="admin-form item-title" value="<?= htmlspecialchars($child['title']) ?>" data-id="<?= $child['id'] ?>">
                                                </div>
                                                <div>
                                                    <label class="block mb-1 text-sm">URL</label>
                                                    <input type="text" class="admin-form item-url" value="<?= htmlspecialchars($child['url']) ?>" data-id="<?= $child['id'] ?>">
                                                </div>
                                            </div>
                                            <div class="mb-2">
                                                <label class="block mb-1 text-sm">Icon</label>
                                                <div class="flex gap-2">
                                                    <input type="text" class="admin-form item-icon flex-1" value="<?= htmlspecialchars($child['icon'] ?? '') ?>" data-id="<?= $child['id'] ?>" placeholder="e.g. fas fa-home">
                                                    <button type="button" class="btn-secondary icon-picker-btn" data-target="item-icon-<?= $child['id'] ?>">
                                                        <i class="fas fa-icons"></i>
                                                    </button>
                                                </div>
                                            </div>
                                            <div class="mb-2">
                                                <label class="block mb-1 text-sm">Open in</label>
                                                <select class="admin-form item-target" data-id="<?= $child['id'] ?>">
                                                    <option value="_self" <?= $child['target'] === '_self' ? 'selected' : '' ?>>Same Window</option>
                                                    <option value="_blank" <?= $child['target'] === '_blank' ? 'selected' : '' ?>>New Window</option>
                                                </select>
                                            </div>
                                            <div class="flex justify-end">
                                                <button type="button" class="btn-secondary btn-sm mr-2 cancel-edit-btn">
                                                    Cancel
                                                </button>
                                                <button type="button" class="btn-primary btn-sm save-item-btn" data-id="<?= $child['id'] ?>" data-menu-id="<?= $menuData['id'] ?>">
                                                    Save
                                                </button>
                                            </div>
                                        </div>
                                    </li>
                                    <?php endforeach; ?>
                                </ul>
                                <?php endif; ?>
                            </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                    
                    <button type="submit" class="btn-primary">
                        <i class="fas fa-save mr-2"></i>Save Menu Structure
                    </button>
                </form>
                
                <!-- Delete Item Form (Hidden) -->
                <form id="delete_item_form" method="POST" action="/admin/menu-items/delete" style="display: none;">
                    <input type="hidden" name="id" id="delete_item_id">
                    <input type="hidden" name="menu_id" id="delete_menu_id">
                </form>
                
                <!-- Edit Item Form (Hidden) -->
                <form id="edit_item_form" method="POST" action="/admin/menu-items/edit" style="display: none;">
                    <input type="hidden" name="id" id="edit_item_id">
                    <input type="hidden" name="menu_id" id="edit_menu_id">
                    <input type="hidden" name="title" id="edit_item_title">
                    <input type="hidden" name="url" id="edit_item_url">
                    <input type="hidden" name="target" id="edit_item_target">
                </form>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Icon Picker Modal -->
<div id="iconPickerModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center hidden">
    <div class="bg-dark rounded-lg shadow-lg p-6 w-full max-w-4xl max-h-[80vh] overflow-y-auto">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-xl font-bold">Select Icon</h3>
            <button id="closeIconPicker" class="text-gray-400 hover:text-white">
                <i class="fas fa-times"></i>
            </button>
        </div>
        
        <div class="mb-4">
            <input type="text" id="iconSearch" class="admin-form w-full" placeholder="Search icons...">
        </div>
        
        <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4" id="iconGrid">
            <!-- Icons will be populated by JavaScript -->
        </div>
    </div>
</div>

<!-- Include Sortable.js from CDN -->
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.14.0/Sortable.min.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Toggle between custom link and page link forms
    const itemTypeSelect = document.getElementById('item_type');
    const customLinkForm = document.getElementById('custom_link_form');
    const pageLinkForm = document.getElementById('page_link_form');
    
    itemTypeSelect.addEventListener('change', function() {
        if (this.value === 'custom') {
            customLinkForm.style.display = 'block';
            pageLinkForm.style.display = 'none';
        } else if (this.value === 'page') {
            customLinkForm.style.display = 'none';
            pageLinkForm.style.display = 'block';
        }
    });
    
    // Initialize Sortable for menu items
    const menuItemsContainer = document.getElementById('menu_items');
    if (menuItemsContainer) {
        const sortable = new Sortable(menuItemsContainer, {
            animation: 150,
            handle: '.handle',
            group: 'menu-items',
            onEnd: updateItemsOrder
        });
        
        // Initialize Sortable for submenus
        document.querySelectorAll('.submenu').forEach(submenu => {
            new Sortable(submenu, {
                animation: 150,
                handle: '.handle',
                group: 'menu-items',
                onEnd: updateItemsOrder
            });
        });
    }
    
    // Toggle menu item edit panel
    document.querySelectorAll('.edit-item-btn').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.stopPropagation();
            const menuItem = this.closest('.menu-item');
            const editPanel = menuItem.querySelector('.menu-item-edit');
            editPanel.style.display = editPanel.style.display === 'none' ? 'block' : 'none';
        });
    });
    
    // Cancel edit button
    document.querySelectorAll('.cancel-edit-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const editPanel = this.closest('.menu-item-edit');
            editPanel.style.display = 'none';
        });
    });
    
    // Delete menu item
    document.querySelectorAll('.delete-item-btn').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.stopPropagation();
            if (confirm('Are you sure you want to delete this menu item?')) {
                const itemId = this.getAttribute('data-id');
                const menuId = this.getAttribute('data-menu-id');
                
                document.getElementById('delete_item_id').value = itemId;
                document.getElementById('delete_menu_id').value = menuId;
                document.getElementById('delete_item_form').submit();
            }
        });
    });
    
    // Save menu item changes
    document.querySelectorAll('.save-item-btn').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.stopPropagation();
            const itemId = this.getAttribute('data-id');
            const menuId = this.getAttribute('data-menu-id');
            
            const title = document.querySelector(`.item-title[data-id="${itemId}"]`).value;
            const url = document.querySelector(`.item-url[data-id="${itemId}"]`).value;
            const target = document.querySelector(`.item-target[data-id="${itemId}"]`).value;
            
            document.getElementById('edit_item_id').value = itemId;
            document.getElementById('edit_menu_id').value = menuId;
            document.getElementById('edit_item_title').value = title;
            document.getElementById('edit_item_url').value = url;
            document.getElementById('edit_item_target').value = target;
            
            document.getElementById('edit_item_form').submit();
        });
    });
    
    // Update items order in the form before submission
    function updateItemsOrder() {
        if (!document.getElementById('menu_structure_form')) return;
        
        const form = document.getElementById('menu_structure_form');
        const items = [];
        
        // Process top-level items
        document.querySelectorAll('#menu_items > .menu-item').forEach((item, index) => {
            const itemId = item.getAttribute('data-id');
            items.push({
                id: itemId,
                parent_id: 0,
                order_position: index
            });
            
            // Process submenu items
            const submenu = item.querySelector('.submenu');
            if (submenu) {
                submenu.querySelectorAll('.menu-item').forEach((subItem, subIndex) => {
                    const subItemId = subItem.getAttribute('data-id');
                    items.push({
                        id: subItemId,
                        parent_id: itemId,
                        order_position: subIndex
                    });
                });
            }
        });
        
        // Clear existing hidden inputs
        form.querySelectorAll('input[name^="items_order"]').forEach(input => {
            input.remove();
        });
        
        // Add new hidden inputs for each item
        items.forEach((item, index) => {
            const idInput = document.createElement('input');
            idInput.type = 'hidden';
            idInput.name = `items_order[${index}][id]`;
            idInput.value = item.id;
            form.appendChild(idInput);
            
            const parentInput = document.createElement('input');
            parentInput.type = 'hidden';
            parentInput.name = `items_order[${index}][parent_id]`;
            parentInput.value = item.parent_id;
            form.appendChild(parentInput);
            
            const orderInput = document.createElement('input');
            orderInput.type = 'hidden';
            orderInput.name = `items_order[${index}][order_position]`;
            orderInput.value = item.order_position;
            form.appendChild(orderInput);
        });
    }
    
    // Add event listener to the form
    const menuStructureForm = document.getElementById('menu_structure_form');
    if (menuStructureForm) {
        menuStructureForm.addEventListener('submit', function(e) {
            updateItemsOrder();
        });
    }
    
    // Icon picker functionality
    const iconPickerModal = document.getElementById('iconPickerModal');
    const closeIconPicker = document.getElementById('closeIconPicker');
    const iconSearch = document.getElementById('iconSearch');
    const iconGrid = document.getElementById('iconGrid');
    let currentIconInput = null;
    
    // Common Font Awesome icons
    const commonIcons = [
        'fas fa-home', 'fas fa-user', 'fas fa-cog', 'fas fa-envelope', 'fas fa-bell',
        'fas fa-search', 'fas fa-star', 'fas fa-heart', 'fas fa-file', 'fas fa-folder',
        'fas fa-calendar', 'fas fa-clock', 'fas fa-image', 'fas fa-video', 'fas fa-music',
        'fas fa-book', 'fas fa-bookmark', 'fas fa-map', 'fas fa-phone', 'fas fa-camera',
        'fas fa-link', 'fas fa-chart-bar', 'fas fa-users', 'fas fa-comments', 'fas fa-shopping-cart',
        'fas fa-globe', 'fas fa-desktop', 'fas fa-mobile', 'fas fa-tablet', 'fas fa-laptop',
        'fas fa-gamepad', 'fas fa-headphones', 'fas fa-microphone', 'fas fa-trophy', 'fas fa-flag',
        'fas fa-tag', 'fas fa-tags', 'fas fa-gift', 'fas fa-fire', 'fas fa-bolt',
        'fas fa-cloud', 'fas fa-sun', 'fas fa-moon', 'fas fa-umbrella', 'fas fa-car',
        'fas fa-plane', 'fas fa-train', 'fas fa-ship', 'fas fa-bicycle', 'fas fa-truck'
    ];
    
    function populateIconGrid(searchTerm = '') {
        iconGrid.innerHTML = '';
        const filteredIcons = commonIcons.filter(icon => 
            icon.toLowerCase().includes(searchTerm.toLowerCase())
        );
        
        filteredIcons.forEach(icon => {
            const iconDiv = document.createElement('div');
            iconDiv.className = 'p-4 bg-sidebar-bg rounded-lg text-center cursor-pointer hover:bg-primary/20 transition-colors';
            iconDiv.innerHTML = `<i class="${icon} text-2xl mb-2"></i><div class="text-xs text-gray-400">${icon}</div>`;
            iconDiv.addEventListener('click', () => {
                if (currentIconInput) {
                    currentIconInput.value = icon;
                }
                iconPickerModal.classList.add('hidden');
            });
            iconGrid.appendChild(iconDiv);
        });
    }
    
    // Show icon picker when clicking the icon button
    document.querySelectorAll('.icon-picker-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const targetId = this.getAttribute('data-target');
            currentIconInput = document.getElementById(targetId);
            populateIconGrid();
            iconPickerModal.classList.remove('hidden');
        });
    });
    
    // Close icon picker
    closeIconPicker.addEventListener('click', () => {
        iconPickerModal.classList.add('hidden');
    });
    
    // Search icons
    iconSearch.addEventListener('input', (e) => {
        populateIconGrid(e.target.value);
    });
    
    // Close modal when clicking outside
    iconPickerModal.addEventListener('click', (e) => {
        if (e.target === iconPickerModal) {
            iconPickerModal.classList.add('hidden');
        }
    });
});
</script> 