<?php
/**
 * CMS - Menu Management
 * Create and manage navigation menus
 */

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

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

$db = getDB();

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

// Handle create/update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    validateCSRF();
    
    try {
        $name = sanitize($_POST['name'] ?? '');
        $slug = sanitize($_POST['slug'] ?? '');
        $location = sanitize($_POST['location'] ?? 'header');
        $description = sanitize($_POST['description'] ?? '');
        $status = sanitize($_POST['status'] ?? 'active');
        
        if (empty($name)) {
            throw new Exception('Menu name is required');
        }
        
        // Generate slug if empty
        if (empty($slug)) {
            $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $name)));
        }
        
        if (isset($_POST['menu_id']) && !empty($_POST['menu_id'])) {
            // Update existing menu
            $menuId = (int)$_POST['menu_id'];
            
            $stmt = $db->prepare("
                UPDATE cms_menus 
                SET name = ?, slug = ?, location = ?, description = ?, status = ?
                WHERE id = ?
            ");
            $stmt->execute([$name, $slug, $location, $description, $status, $menuId]);
            
            $success = 'Menu updated successfully.';
            logAudit($_SESSION['user_id'], 'update', 'cms_menus', $menuId, 'Updated menu');
        } else {
            // Create new menu
            $stmt = $db->prepare("
                INSERT INTO cms_menus (name, slug, location, description, status, created_by)
                VALUES (?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([$name, $slug, $location, $description, $status, $_SESSION['user_id']]);
            
            $menuId = $db->lastInsertId();
            $success = 'Menu created successfully.';
            logAudit($_SESSION['user_id'], 'create', 'cms_menus', $menuId, 'Created menu');
        }
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

// Get all menus
$stmt = $db->prepare("
    SELECT m.*, u.first_name, u.last_name,
           (SELECT COUNT(*) FROM cms_menu_items WHERE menu_id = m.id) as items_count
    FROM cms_menus m
    LEFT JOIN users u ON m.created_by = u.id
    ORDER BY m.location, m.name
");
$stmt->execute();
$menus = $stmt->fetchAll();

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

<div class="container-fluid">
    <div class="row">
        <?php include 'sidebar.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">
                <h1 class="h2"><i class="fas fa-bars"></i> Menu Management</h1>
                <div class="btn-toolbar">
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#menuModal">
                        <i class="fas fa-plus"></i> New Menu
                    </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; ?>

            <!-- Menus Grid -->
            <div class="row g-4">
                <?php if (empty($menus)): ?>
                    <div class="col-12">
                        <div class="card shadow-sm">
                            <div class="card-body text-center py-5">
                                <i class="fas fa-bars fa-3x text-muted mb-3"></i>
                                <h5>No Menus Yet</h5>
                                <p class="text-muted">Create your first navigation menu to get started.</p>
                                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#menuModal">
                                    <i class="fas fa-plus"></i> Create Menu
                                </button>
                            </div>
                        </div>
                    </div>
                <?php else: ?>
                    <?php foreach ($menus as $menu): ?>
                        <div class="col-md-6 col-lg-4">
                            <div class="card shadow-sm h-100">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="mb-0"><?php echo e($menu['name']); ?></h5>
                                    <span class="badge bg-<?php echo $menu['status'] === 'active' ? 'success' : 'secondary'; ?>">
                                        <?php echo ucfirst($menu['status']); ?>
                                    </span>
                                </div>
                                <div class="card-body">
                                    <p class="text-muted small mb-2">
                                        <i class="fas fa-map-marker-alt"></i> Location: <strong><?php echo ucfirst($menu['location']); ?></strong>
                                    </p>
                                    <p class="text-muted small mb-2">
                                        <i class="fas fa-link"></i> Slug: <code><?php echo e($menu['slug']); ?></code>
                                    </p>
                                    <p class="text-muted small mb-3">
                                        <i class="fas fa-list"></i> Items: <strong><?php echo $menu['items_count']; ?></strong>
                                    </p>
                                    <?php if ($menu['description']): ?>
                                        <p class="small"><?php echo e($menu['description']); ?></p>
                                    <?php endif; ?>
                                </div>
                                <div class="card-footer bg-transparent">
                                    <div class="btn-group w-100">
                                        <a href="cms-menu-items.php?menu_id=<?php echo $menu['id']; ?>" 
                                           class="btn btn-sm btn-primary">
                                            <i class="fas fa-edit"></i> Manage Items
                                        </a>
                                        <button type="button" 
                                                class="btn btn-sm btn-outline-secondary"
                                                onclick="editMenu(<?php echo htmlspecialchars(json_encode($menu)); ?>)">
                                            <i class="fas fa-cog"></i> Settings
                                        </button>
                                        <a href="?action=delete&id=<?php echo $menu['id']; ?>&csrf_token=<?php echo $_SESSION['csrf_token']; ?>" 
                                           class="btn btn-sm btn-outline-danger"
                                           onclick="return confirm('Delete this menu and all its items?')">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </main>
    </div>
</div>

<!-- Menu Modal -->
<div class="modal fade" id="menuModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <?php echo csrfField(); ?>
                <input type="hidden" name="menu_id" id="menuId">
                
                <div class="modal-header">
                    <h5 class="modal-title" id="menuModalTitle">Create New Menu</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Menu Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="name" id="menuName" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Slug</label>
                        <input type="text" class="form-control" name="slug" id="menuSlug" 
                               placeholder="auto-generated">
                        <small class="form-text text-muted">Leave empty to auto-generate</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Location</label>
                        <select class="form-select" name="location" id="menuLocation">
                            <option value="header">Header</option>
                            <option value="footer">Footer</option>
                            <option value="sidebar">Sidebar</option>
                            <option value="custom">Custom</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea class="form-control" name="description" id="menuDescription" rows="2"></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select class="form-select" name="status" id="menuStatus">
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </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 Menu
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function editMenu(menu) {
    document.getElementById('menuModalTitle').textContent = 'Edit Menu';
    document.getElementById('menuId').value = menu.id;
    document.getElementById('menuName').value = menu.name;
    document.getElementById('menuSlug').value = menu.slug;
    document.getElementById('menuLocation').value = menu.location;
    document.getElementById('menuDescription').value = menu.description || '';
    document.getElementById('menuStatus').value = menu.status;
    
    new bootstrap.Modal(document.getElementById('menuModal')).show();
}

// Reset form when modal is closed
document.getElementById('menuModal').addEventListener('hidden.bs.modal', function () {
    document.getElementById('menuModalTitle').textContent = 'Create New Menu';
    document.getElementById('menuId').value = '';
    document.querySelector('#menuModal form').reset();
});
</script>

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