<?php
session_start();
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] !== 1) {
    header('Location: login.php');
    exit();
}

// Fetch menu items
$sql = "SELECT m.*, p.menu_name as parent_name 
        FROM menu_items m 
        LEFT JOIN menu_items p ON m.parent_id = p.menu_id 
        ORDER BY COALESCE(m.parent_id, m.menu_id), m.menu_order";
$result = $conn->query($sql);

// Fetch parent menu items for dropdown
$parent_sql = "SELECT menu_id, menu_name FROM menu_items WHERE parent_id IS NULL ORDER BY menu_order";
$parent_result = $conn->query($parent_sql);
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Menu Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .menu-item {
            transition: all 0.3s;
        }
        .menu-item:hover {
            background-color: #f8f9fa;
        }
        .child-menu {
            margin-left: 2rem;
            border-left: 2px solid #eee;
        }
        .inactive-menu {
            opacity: 0.6;
            background-color: #fff3cd;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'System Settings', 'title' => 'Menu Management')); ?>
                    
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header d-flex align-items-center">
                                    <h4 class="card-title mb-0 flex-grow-1">Menu Management</h4>
                                    <div class="d-flex gap-2">
                                        <div class="form-check form-switch">
                                            <input class="form-check-input" type="checkbox" id="showInactive" onchange="toggleInactiveDisplay()">
                                            <label class="form-check-label" for="showInactive">Show Inactive</label>
                                        </div>
                                        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addMenuModal">
                                            <i class="ri-add-line align-middle me-1"></i> Add Menu Item
                                        </button>
                                    </div>
                                </div>
                                
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered">
                                            <thead>
                                                <tr>
                                                    <th style="width: 40px;"></th>
                                                    <th>Menu Name</th>
                                                    <th>URL</th>
                                                    <th>Icon</th>
                                                    <th>Parent</th>
                                                    <th>Order</th>
                                                    <th>Status</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php 
                                                $current_parent = null;
                                                while ($menu = $result->fetch_assoc()):
                                                    $is_parent = is_null($menu['parent_id']);
                                                    $is_active = $menu['is_active'];
                                                ?>
                                                <tr class="menu-item <?php echo $is_parent ? '' : 'child-menu'; ?> <?php echo !$is_active ? 'inactive-menu d-none' : ''; ?>" data-active="<?php echo $is_active; ?>">
                                                    <td>
                                                        <i class="<?php echo $menu['menu_icon']; ?>"></i>
                                                    </td>
                                                    <td><?php echo htmlspecialchars($menu['menu_name']); ?></td>
                                                    <td><?php echo htmlspecialchars($menu['menu_url'] ?? ''); ?></td>
                                                    <td><?php echo htmlspecialchars($menu['menu_icon'] ?? ''); ?></td>
                                                    <td><?php echo htmlspecialchars($menu['parent_name'] ?? '-'); ?></td>
                                                    <td><?php echo $menu['menu_order']; ?></td>
                                                    <td>
                                                        <span class="badge <?php echo $is_active ? 'bg-success' : 'bg-warning'; ?>">
                                                            <?php echo $is_active ? 'Active' : 'Inactive'; ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <div class="d-flex gap-2">
                                                            <button class="btn btn-sm btn-info" 
                                                                    onclick="editMenu(<?php echo $menu['menu_id']; ?>)">
                                                                <i class="ri-edit-2-line"></i>
                                                            </button>
                                                            <?php if ($is_active): ?>
                                                                <button class="btn btn-sm btn-warning" 
                                                                        onclick="deactivateMenu(<?php echo $menu['menu_id']; ?>)"
                                                                        title="Deactivate">
                                                                    <i class="ri-eye-off-line"></i>
                                                                </button>
                                                            <?php else: ?>
                                                                <button class="btn btn-sm btn-success" 
                                                                        onclick="activateMenu(<?php echo $menu['menu_id']; ?>)"
                                                                        title="Activate">
                                                                    <i class="ri-eye-line"></i>
                                                                </button>
                                                            <?php endif; ?>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Add Menu Modal -->
    <div class="modal fade" id="addMenuModal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Add Menu Item</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="menuForm">
                        <div class="mb-3">
                            <label class="form-label">Menu Name</label>
                            <input type="text" class="form-control" name="menu_name" required>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">URL</label>
                            <input type="text" class="form-control" name="menu_url">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Icon Class</label>
                            <input type="text" class="form-control" name="menu_icon" 
                                   placeholder="e.g. ri-dashboard-line">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Parent Menu</label>
                            <select class="form-select" name="parent_id">
                                <option value="">None (Top Level)</option>
                                <?php 
                                $parent_result->data_seek(0);
                                while ($parent = $parent_result->fetch_assoc()): 
                                ?>
                                <option value="<?php echo $parent['menu_id']; ?>">
                                    <?php echo htmlspecialchars($parent['menu_name']); ?>
                                </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Order</label>
                            <input type="number" class="form-control" name="menu_order" value="0">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="saveMenu()">Save Menu</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Menu Modal -->
    <div class="modal fade" id="editMenuModal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Menu Item</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="editMenuForm">
                        <input type="hidden" name="menu_id" id="edit_menu_id">
                        
                        <div class="mb-3">
                            <label class="form-label">Menu Name</label>
                            <input type="text" class="form-control" name="menu_name" id="edit_menu_name" required>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">URL</label>
                            <input type="text" class="form-control" name="menu_url" id="edit_menu_url">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Icon Class</label>
                            <input type="text" class="form-control" name="menu_icon" id="edit_menu_icon"
                                   placeholder="e.g. ri-dashboard-line">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Parent Menu</label>
                            <select class="form-select" name="parent_id" id="edit_parent_id">
                                <option value="">None (Top Level)</option>
                                <?php 
                                $parent_result->data_seek(0);
                                while ($parent = $parent_result->fetch_assoc()): 
                                ?>
                                <option value="<?php echo $parent['menu_id']; ?>">
                                    <?php echo htmlspecialchars($parent['menu_name']); ?>
                                </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Order</label>
                            <input type="number" class="form-control" name="menu_order" id="edit_menu_order">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="updateMenu()">Update Menu</button>
                </div>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
        function toggleInactiveDisplay() {
            const showInactive = document.getElementById('showInactive').checked;
            const inactiveRows = document.querySelectorAll('.inactive-menu');
            
            inactiveRows.forEach(row => {
                if (showInactive) {
                    row.classList.remove('d-none');
                } else {
                    row.classList.add('d-none');
                }
            });
        }

        function saveMenu() {
            const form = document.getElementById('menuForm');
            const formData = new FormData(form);

            Swal.fire({
                title: 'Saving...',
                text: 'Please wait while we save the menu item',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });

            fetch('save_menu.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: 'Menu item saved successfully!'
                    }).then(() => {
                        window.location.reload();
                    });
                } else {
                    throw new Error(data.error);
                }
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: error.message
                });
            });
        }

        function editMenu(menuId) {
            Swal.fire({
                title: 'Loading...',
                text: 'Please wait while we load the menu details',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });

            fetch('get_menu.php?id=' + menuId)
            .then(response => response.json())
            .then(data => {
                Swal.close();
                
                if (data.success) {
                    document.getElementById('edit_menu_id').value = data.menu.menu_id;
                    document.getElementById('edit_menu_name').value = data.menu.menu_name;
                    document.getElementById('edit_menu_url').value = data.menu.menu_url || '';
                    document.getElementById('edit_menu_icon').value = data.menu.menu_icon || '';
                    document.getElementById('edit_parent_id').value = data.menu.parent_id || '';
                    document.getElementById('edit_menu_order').value = data.menu.menu_order;
                    
                    const editModal = new bootstrap.Modal(document.getElementById('editMenuModal'));
                    editModal.show();
                } else {
                    throw new Error(data.error);
                }
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: error.message
                });
            });
        }

        function updateMenu() {
            const form = document.getElementById('editMenuForm');
            const formData = new FormData(form);

            Swal.fire({
                title: 'Updating...',
                text: 'Please wait while we update the menu item',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });

            fetch('update_menu.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: 'Menu item updated successfully!'
                    }).then(() => {
                        window.location.reload();
                    });
                } else {
                    throw new Error(data.error);
                }
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: error.message
                });
            });
        }

        function deactivateMenu(menuId) {
            Swal.fire({
                title: 'Deactivate Menu Item?',
                text: 'This will also deactivate any child menu items. The menu will be hidden from navigation.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#f39c12',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Yes, Deactivate',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    updateMenuStatus(menuId, false, 'Deactivating...');
                }
            });
        }

        function activateMenu(menuId) {
            Swal.fire({
                title: 'Activate Menu Item?',
                text: 'This menu item will be visible in navigation again.',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#28a745',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Yes, Activate',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    updateMenuStatus(menuId, true, 'Activating...');
                }
            });
        }

        function updateMenuStatus(menuId, status, loadingText) {
            Swal.fire({
                title: loadingText,
                text: 'Please wait...',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });

            fetch('toggle_menu_status.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    menu_id: menuId,
                    status: status
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: `Menu item ${status ? 'activated' : 'deactivated'} successfully!`
                    }).then(() => {
                        window.location.reload();
                    });
                } else {
                    throw new Error(data.error);
                }
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: error.message
                });
            });
        }
    </script>
</body>
</html>