<?php
include ('../config.php');
header('Content-Type: application/json');

// Ensure database connection
if (!$db) {
    echo json_encode(["error" => "Database connection failed"]);
    exit;
}

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

// Fetch latest role from the database using user ID
$user_id = $_SESSION['user_id'];
$sql = "SELECT role FROM users WHERE id = ?";   // userid sai role utha liya
$stmt = $db->prepare($sql);

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

$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user_data = $result->fetch_assoc();

if (!$user_data) {
    echo json_encode(["error" => "User not found"]);
    exit;
}

// Extract role from database
$user_roles = explode(',', $user_data['role']);

// Update session role (optional)
$_SESSION['role'] = $user_data['role'];

if (in_array('admin', $user_roles)) {
    $sql = "SELECT page, page_name, icon FROM role_based_access WHERE section = 'navbar' ORDER BY nav_sequence ASC"; 
    $stmt = $db->prepare($sql);

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

    $stmt->execute();
    $result = $stmt->get_result();

    $pages = [];
    while ($row = $result->fetch_assoc()) {
        $pages[] = [
            "page" => $row['page'],
            "page_name" => $row['page_name'],
            "icon" => $row['icon'] ?? '' // Ensure icon is present, 
        ];
    }

    echo json_encode(["role" => "admin", "pages" => $pages], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
    exit;
}

// For non-admin roles, fetch only assigned pages
$placeholders = implode(',', array_fill(0, count($user_roles), '?')); // Create placeholders for SQL
$sql = "SELECT page, page_name, icon FROM role_based_access WHERE role IN ($placeholders) and section = 'navbar' ORDER BY nav_sequence ASC";
$stmt = $db->prepare($sql);
if (!$stmt) {
    echo json_encode(["error" => "SQL prepare failed: " . $db->error]);
    exit;
}

$stmt->bind_param(str_repeat("s", count($user_roles)), ...$user_roles);
$stmt->execute();
$result = $stmt->get_result();

$pages = [];
while ($row = $result->fetch_assoc()) {
    $pages[] = [
        "page" => $row['page'],
        "page_name" => $row['page_name'], 
        "icon" => $row['icon'] ?? ''
    ];
}

// If no pages found, return an appropriate message
if (empty($pages)) {
    echo json_encode(["error" => "No pages found for roles: " . implode(',', $user_roles)]);
    exit;
}
// Return result for non-admin roles
echo json_encode(["role" => $user_roles, "pages" => $pages], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
?>
