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

header('Content-Type: application/json');

// Check authentication and permissions
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] !== 1) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Insufficient permissions. Not Authorized.']);
    exit;
}

try {
    // Validate input
    if (!isset($_GET['id']) || empty($_GET['id'])) {
        throw new Exception('Menu ID is required');
    }

    $menu_id = intval($_GET['id']);
    
    // Fetch menu details
    $sql = "SELECT menu_id, menu_name, menu_url, menu_icon, parent_id, menu_order, is_active 
            FROM menu_items 
            WHERE menu_id = ?";
    
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        throw new Exception("Failed to prepare statement: " . $conn->error);
    }
    
    $stmt->bind_param('i', $menu_id);
    
    if (!$stmt->execute()) {
        throw new Exception("Failed to execute query: " . $stmt->error);
    }
    
    $result = $stmt->get_result();
    $menu = $result->fetch_assoc();
    
    if (!$menu) {
        throw new Exception('Menu item not found');
    }

    echo json_encode([
        'success' => true,
        'menu' => $menu
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
} finally {
    if (isset($stmt)) {
        $stmt->close();
    }
    $conn->close();
}
?>