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

// Set timezone
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Not authenticated']);
    exit();
}

$user_role = $_SESSION['role_name'] ?? 'User';

// Check if user has permission to manage roles
if ($user_role !== 'Administrator') {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Not authorized']);
    exit();
}

// Get role permissions
if (isset($_GET['role_id'])) {
    $role_id = intval($_GET['role_id']);
    
    $sql = "SELECT permission_id FROM role_permissions WHERE role_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $role_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $permissions = [];
    while ($row = $result->fetch_assoc()) {
        $permissions[] = intval($row['permission_id']);
    }
    
    header('Content-Type: application/json');
    echo json_encode($permissions);
} else {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Role ID required']);
}

$conn->close();
?>