<?php
/**
 * CMS - Menu Items Management
 * Manage menu items with drag-and-drop ordering
 */

require_once '../config/config.php';
requireLogin();
requireAdmin();

$pageTitle = 'Menu Items Management';
$success = '';
$error = '';

$db = getDB();

// Get menu ID
$menuId = isset($_GET['menu_id']) ? (int)$_GET['menu_id'] : 0;

if (!$menuId) {
    redirect(SITE_URL . '/admin/cms-menus.php');
}

// Get menu details
$stmt = $db->prepare("SELECT * FROM cms_menus WHERE id = ?");
$stmt->execute([$menuId]);
$menu = $stmt->fetch();

if (!$menu) {
    redirect(SITE_URL . '/admin/cms-menus.php');
}

// Handle delete action
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    validateCSRF();
    
    $itemId = (int)$_GET['id'];
    
    try {
        $stmt = $db->prepare("DELETE FROM cms_menu_items WHERE id = ?");
        $stmt->execute([$itemId]);
        
        $success = 'Menu item deleted successfully.';
        logAudit($_SESSION['user_id'], 'delete', 'cms_menu_items', $itemId, 'Deleted menu item');
    } catch (PDOException $e) {
        $error = 'Error deleting menu item: ' . $e->getMessage();
    }
}

// Handle create/update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_item') {
    validateCSRF();
    
    try {
        $title = sanitize($_POST['title'] ?? '');
        $url = sanitize($_POST['url'] ?? '');
        $linkType = sanitize($_POST['link_type'] ?? 'internal');
        $target = sanitize($_POST['target'] ?? '_self');
        $icon = sanitize($_POST['icon'] ?? '');
        $cssClass = sanitize($_POST['css_class'] ?? '');
        $visibility = sanitize($_POST['visibility'] ?? 'public');
        $status = sanitize($_POST['status'] ?? 'active');
        $parentId = !empty($_POST['parent_id']) ? (int)$_POST['parent_id'] : null;
        
        if (empty($title)) {
            throw new Exception('Menu item title is required');
        }
        
        if (isset($_POST['item_id']) && !empty($_POST['item_id'])) {
            // Update existing item
            $itemId = (int)$_POST['item_id'];
            
            $stmt = $db->prepare("
                UPDATE cms_menu_items 
                SET title = ?, url = ?, link_type = ?, target = ?, icon = ?, 
                    css_class = ?, visibility = ?, status = ?, parent_id = ?
                WHERE id = ? AND menu_id = ?
            ");
            $stmt->execute([$title, $url, $linkType, $target, $icon, $cssClass, 
                          $visibility, $status, $parentId, $itemId, $menuId]);
            
            $success = 'Menu item updated successfully.';
            logAudit($_SESSION['user_id'], 'update', 'cms_menu_items', $itemId, 'Updated menu item');
        } else {
            // Create new item
            // Get max order number
            $stmt = $db->prepare("SELECT COALESCE(MAX(order_num), 0) + 1 as next_order FROM cms_menu_items WHERE menu_id = ?");
            $stmt->execute([$menuId]);
            $orderNum = $stmt->fetchColumn();
            
            $stmt = $db->prepare("
                INSERT INTO cms_menu_items (menu_id, parent_id, title, url, link_type, target, 
                                           icon, css_class, order_num, visibility, status)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([$menuId, $parentId, $title, $url, $linkType, $target, 
                          $icon, $cssClass, $orderNum, $visibility, $status]);
            
            $itemId = $db->lastInsertId();
            $success = 'Menu item created successfully.';
            logAudit($_SESSION['user_id'], 'create', 'cms_menu_items', $itemId, 'Created menu item');
        }
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

// Handle order update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_order') {
    validateCSRF();
    
    try {
        $items = json_decode($_POST['items'], true);
        
        foreach ($items as $index => $itemId) {
            $stmt = $db->prepare("UPDATE cms_menu_items SET order_num = ? WHERE id = ? AND menu_id = ?");
            $stmt->execute([$index, $itemId, $menuId]);
        }
        
        echo json_encode(['success' => true]);
        exit;
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        exit;
    }
}

// Get all menu items
$stmt = $db->prepare("
    SELECT * FROM cms_menu_items 
    WHERE menu_id = ? 
    ORDER BY order_num ASC, id ASC
");
$stmt->execute([$menuId]);
$menuItems = $stmt->fetchAll();

// Get all pages for dropdown
$stmt = $db->prepare("SELECT id, title, slug FROM cms_pages WHERE status = 'published' ORDER BY title");
$stmt->execute();
$pages = $stmt->fetchAll();

include '../templates/admin-header.php';
?>

<div class="container-fluid">
    <div class="row">
        <?php include 'sidebar-new.php'; ?>

        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4" style="margin-top: 56px;">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <div>
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="cms-menus.php">Menus</a></li>
                            <li class="breadcrumb-item active"><?php echo e($menu['name']); ?></li>
                        </ol>
                    </nav>
                    <h1 class="h2"><i class="fas fa-list"></i> Menu Items: <?php echo e($menu['name']); ?></h1>
                </div>
                <div class="btn-toolbar">
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#itemModal">
                        <i class="fas fa-plus"></i> Add Item
                    </button>
                </div>
            </div>

            <?php if ($success): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <?php echo e($success); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <?php if ($error): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <?php echo e($error); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <div class="card shadow-sm">
                <div class="card-header">
                    <h5 class="mb-0">Menu Structure</h5>
                    <small class="text-muted">Drag and drop to reorder items</small>
                </div>
                <div class="card-body">
                    <?php if (empty($menuItems)): ?>
                        <div class="text-center py-5">
                            <i class="fas fa-list fa-3x text-muted mb-3"></i>
                            <h5>No Menu Items Yet</h5>
                            <p class="text-muted">Add your first menu item to get started.</p>
                            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#itemModal">
                                <i class="fas fa-plus"></i> Add First Item
                            </button>
                        </div>
                    <?php else: ?>
                        <div id="menuItemsList" class="list-group">
                            <?php foreach ($menuItems as $item): ?>
                                <div class="list-group-item" data-id="<?php echo $item['id']; ?>">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div class="d-flex align-items-center">
                                            <i class="fas fa-grip-vertical text-muted me-3" style="cursor: move;"></i>
                                            <?php if ($item['icon']): ?>
                                                <i class="<?php echo e($item['icon']); ?> me-2"></i>
                                            <?php endif; ?>
                                            <div>
                                                <strong><?php echo e($item['title']); ?></strong>
                                                <?php if ($item['url']): ?>
                                                    <br><small class="text-muted"><?php echo e($item['url']); ?></small>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <div>
                                            <span class="badge bg-<?php echo $item['status'] === 'active' ? 'success' : 'secondary'; ?> me-2">
                                                <?php echo ucfirst($item['status']); ?>
                                            </span>
                                            <span class="badge bg-info me-2">
                                                <?php echo ucfirst($item['visibility']); ?>
                                            </span>
                                            <div class="btn-group btn-group-sm">
                                                <button type="button" class="btn btn-outline-primary" 
                                                        onclick="editItem(<?php echo htmlspecialchars(json_encode($item)); ?>)">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <a href="?menu_id=<?php echo $menuId; ?>&action=delete&id=<?php echo $item['id']; ?>&csrf_token=<?php echo $_SESSION['csrf_token']; ?>" 
                                                   class="btn btn-outline-danger"
                                                   onclick="return confirm('Delete this menu item?')">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</div>

<!-- Item Modal -->
<div class="modal fade" id="itemModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="POST">
                <?php echo csrfField(); ?>
                <input type="hidden" name="action" value="save_item">
                <input type="hidden" name="item_id" id="itemId">
                
                <div class="modal-header">
                    <h5 class="modal-title" id="itemModalTitle">Add Menu Item</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-8 mb-3">
                            <label class="form-label">Title <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="title" id="itemTitle" required>
                        </div>
                        
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Icon (FontAwesome)</label>
                            <input type="text" class="form-control" name="icon" id="itemIcon" 
                                   placeholder="fas fa-home">
                            <small class="form-text text-muted">e.g., fas fa-home</small>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Link Type</label>
                        <select class="form-select" name="link_type" id="itemLinkType" onchange="toggleLinkFields()">
                            <option value="internal">Internal Link</option>
                            <option value="external">External Link</option>
                            <option value="page">CMS Page</option>
                            <option value="custom">Custom URL</option>
                        </select>
                    </div>
                    
                    <div class="mb-3" id="urlField">
                        <label class="form-label">URL</label>
                        <input type="text" class="form-control" name="url" id="itemUrl" 
                               placeholder="/page-slug or https://example.com">
                    </div>
                    
                    <div class="mb-3 d-none" id="pageField">
                        <label class="form-label">Select Page</label>
                        <select class="form-select" name="page_id" id="itemPageId">
                            <option value="">-- Select Page --</option>
                            <?php foreach ($pages as $page): ?>
                                <option value="<?php echo $page['id']; ?>" data-slug="<?php echo $page['slug']; ?>">
                                    <?php echo e($page['title']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Target</label>
                            <select class="form-select" name="target" id="itemTarget">
                                <option value="_self">Same Window</option>
                                <option value="_blank">New Window</option>
                            </select>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Parent Item</label>
                            <select class="form-select" name="parent_id" id="itemParentId">
                                <option value="">-- Top Level --</option>
                                <?php foreach ($menuItems as $item): ?>
                                    <?php if (!$item['parent_id']): ?>
                                        <option value="<?php echo $item['id']; ?>">
                                            <?php echo e($item['title']); ?>
                                        </option>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Visibility</label>
                            <select class="form-select" name="visibility" id="itemVisibility">
                                <option value="public">Public</option>
                                <option value="logged_in">Logged In Only</option>
                                <option value="logged_out">Logged Out Only</option>
                                <option value="admin">Admin Only</option>
                            </select>
                        </div>
                        
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Status</label>
                            <select class="form-select" name="status" id="itemStatus">
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                        </div>
                        
                        <div class="col-md-4 mb-3">
                            <label class="form-label">CSS Class</label>
                            <input type="text" class="form-control" name="css_class" id="itemCssClass" 
                                   placeholder="custom-class">
                        </div>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> Save Item
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

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

<script>
// Initialize Sortable for drag-and-drop
<?php if (!empty($menuItems)): ?>
const el = document.getElementById('menuItemsList');
const sortable = Sortable.create(el, {
    animation: 150,
    handle: '.fa-grip-vertical',
    onEnd: function (evt) {
        updateOrder();
    }
});

function updateOrder() {
    const items = [];
    document.querySelectorAll('#menuItemsList .list-group-item').forEach(item => {
        items.push(item.dataset.id);
    });
    
    fetch('', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'action=update_order&items=' + JSON.stringify(items) + '&csrf_token=<?php echo $_SESSION['csrf_token']; ?>'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            console.log('Order updated successfully');
        }
    });
}
<?php endif; ?>

function editItem(item) {
    document.getElementById('itemModalTitle').textContent = 'Edit Menu Item';
    document.getElementById('itemId').value = item.id;
    document.getElementById('itemTitle').value = item.title;
    document.getElementById('itemUrl').value = item.url || '';
    document.getElementById('itemLinkType').value = item.link_type;
    document.getElementById('itemTarget').value = item.target;
    document.getElementById('itemIcon').value = item.icon || '';
    document.getElementById('itemCssClass').value = item.css_class || '';
    document.getElementById('itemVisibility').value = item.visibility;
    document.getElementById('itemStatus').value = item.status;
    document.getElementById('itemParentId').value = item.parent_id || '';
    
    toggleLinkFields();
    new bootstrap.Modal(document.getElementById('itemModal')).show();
}

function toggleLinkFields() {
    const linkType = document.getElementById('itemLinkType').value;
    const urlField = document.getElementById('urlField');
    const pageField = document.getElementById('pageField');
    
    if (linkType === 'page') {
        urlField.classList.add('d-none');
        pageField.classList.remove('d-none');
    } else {
        urlField.classList.remove('d-none');
        pageField.classList.add('d-none');
    }
}

// Update URL when page is selected
document.getElementById('itemPageId')?.addEventListener('change', function() {
    const selectedOption = this.options[this.selectedIndex];
    if (selectedOption.value) {
        const slug = selectedOption.dataset.slug;
        document.getElementById('itemUrl').value = '/public/' + slug + '.php';
    }
});

// Reset form when modal is closed
document.getElementById('itemModal').addEventListener('hidden.bs.modal', function () {
    document.getElementById('itemModalTitle').textContent = 'Add Menu Item';
    document.getElementById('itemId').value = '';
    document.querySelector('#itemModal form').reset();
    toggleLinkFields();
});
</script>

<?php include '../templates/admin-footer.php'; ?>
