<?php
session_start();
include('../config.php'); 

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

if (!$db) {
    echo json_encode(['error' => 'Database Connection failed']);
    exit;
}

if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
    echo json_encode(["error" => "User is not logged in"]);
    exit;
}

// ✅ Get the current page from AJAX request
$currentPage = isset($_GET['page']) ? trim($_GET['page']) : '';

if (empty($currentPage)) {
    echo json_encode(["error" => "Current page not provided"]);
    exit;
}

// ✅ Match `currentPage` against `sidebar` column
$sql = "SELECT id, sidebar, page_name, page_link, parent_id, icons FROM role_based_sidebar_access WHERE sidebar = ?";
$stmt = $db->prepare($sql);

if (!$stmt) {
    echo json_encode(["error" => "SQL prepare failed: " . $db->error]);
    exit;
}

$stmt->bind_param("s", $currentPage);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo json_encode(["error" => "No sidebar items found for: " . $currentPage]);
    exit;
}

$sidebar_items = [];
$menu_structure = [];

// ✅ Fetch all sidebar items matching the `sidebar` column
while ($row = $result->fetch_assoc()) {
    $row['children'] = [];
    $sidebar_items[$row['id']] = $row;
}

// ✅ Build hierarchical menu based on `parent_id`
foreach ($sidebar_items as &$item) {
    if ($item['parent_id'] != 0 && isset($sidebar_items[$item['parent_id']])) {
        $sidebar_items[$item['parent_id']]['children'][] = &$item;
    } else {
        $menu_structure[] = &$item;
    }
}

// ✅ Return JSON response
echo json_encode(["sidebar" => $menu_structure], JSON_PRETTY_PRINT);
?>
