<?php
/**
 * Enterprise HRM ERP System - Get Role Permissions (AJAX)
 * Returns permissions for a role in JSON format
 */

require_once __DIR__ . '/../includes/init.php';
requireLogin();

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

$roleId = isset($_GET['role_id']) ? (int)$_GET['role_id'] : 0;

if ($roleId <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid role ID']);
    exit;
}

try {
    $db = getDB();
    
    // Get role permissions
    $stmt = $db->prepare("
        SELECT 
            p.permission_id,
            p.permission_code,
            p.permission_name,
            p.permission_module,
            p.permission_description
        FROM permissions p
        INNER JOIN role_permissions rp ON p.permission_id = rp.permission_id
        WHERE rp.role_id = ?
        ORDER BY p.permission_module, p.permission_name
    ");
    $stmt->execute([$roleId]);
    $permissions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get role info
    $stmt = $db->prepare("SELECT role_id, role_name, role_code, role_description FROM roles WHERE role_id = ?");
    $stmt->execute([$roleId]);
    $role = $stmt->fetch(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'role' => $role,
        'permissions' => $permissions,
        'count' => count($permissions)
    ]);
    
} catch (Exception $e) {
    error_log("Error loading role permissions: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error loading permissions'
    ]);
}

