<?php
/**
 * Enterprise HRM ERP System - View/Edit Role Permissions
 */

require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/check_admin_access.php';

// Check if user is Super Admin - with better error handling
startSession();

// Force refresh role_code from database
$roleCode = $_SESSION['role_code'] ?? '';
if (empty($roleCode) && isset($_SESSION['user_id'])) {
    try {
        $db = getDB();
        $stmt = $db->prepare("
            SELECT r.role_code 
            FROM users u
            INNER JOIN roles r ON u.role_id = r.role_id
            WHERE u.user_id = ?
        ");
        $stmt->execute([$_SESSION['user_id']]);
        $userRole = $stmt->fetch();
        if ($userRole && !empty($userRole['role_code'])) {
            $roleCode = $userRole['role_code'];
            $_SESSION['role_code'] = $roleCode;
        }
    } catch (Exception $e) {
        error_log("Error loading role_code: " . $e->getMessage());
    }
}

// Check if Super Admin (case-insensitive)
if (strtolower($roleCode) !== 'super_admin') {
    redirect(BASE_URL . '/dashboard.php', 'Only Super Admin can manage roles. Your role: ' . ($roleCode ?: 'Unknown'), 'error');
}

$pageTitle = 'View/Edit Role';
$currentModule = 'settings';

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

if ($roleId <= 0) {
    redirect(BASE_URL . '/admin/roles.php', 'Invalid role ID.', 'error');
}

// Get role
try {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM roles WHERE role_id = ?");
    $stmt->execute([$roleId]);
    $role = $stmt->fetch();
    
    if (!$role) {
        redirect(BASE_URL . '/admin/roles.php', 'Role not found.', 'error');
    }
    
    // Get role permissions
    $stmt = $db->prepare("
        SELECT permission_id FROM role_permissions WHERE role_id = ?
    ");
    $stmt->execute([$roleId]);
    $rolePermissions = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    // Get all permissions
    $stmt = $db->prepare("
        SELECT permission_id, permission_code, permission_name, permission_module
        FROM permissions
        ORDER BY permission_module, permission_name
    ");
    $stmt->execute();
    $allPermissions = $stmt->fetchAll();
    
    // Group by module
    $permissionsByModule = [];
    foreach ($allPermissions as $perm) {
        $module = $perm['permission_module'];
        if (!isset($permissionsByModule[$module])) {
            $permissionsByModule[$module] = [];
        }
        $permissionsByModule[$module][] = $perm;
    }
    
} catch (Exception $e) {
    error_log("Error loading role: " . $e->getMessage());
    redirect(BASE_URL . '/admin/roles.php', 'Error loading role data.', 'error');
}

$errors = [];
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_permissions'])) {
    $newPermissions = $_POST['permissions'] ?? [];
    
    try {
        $db = getDB();
        $db->beginTransaction();
        
        // Delete existing permissions
        $stmt = $db->prepare("DELETE FROM role_permissions WHERE role_id = ?");
        $stmt->execute([$roleId]);
        
        // Insert new permissions
        if (!empty($newPermissions)) {
            $stmt = $db->prepare("INSERT INTO role_permissions (role_id, permission_id) VALUES (?, ?)");
            foreach ($newPermissions as $permissionId) {
                $stmt->execute([$roleId, (int)$permissionId]);
            }
        }
        
        $db->commit();
        
        $success = true;
        logAudit('UPDATE', 'roles', $roleId);
        
        // Reload permissions
        $stmt = $db->prepare("SELECT permission_id FROM role_permissions WHERE role_id = ?");
        $stmt->execute([$roleId]);
        $rolePermissions = $stmt->fetchAll(PDO::FETCH_COLUMN);
        
    } catch (Exception $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        error_log("Error updating permissions: " . $e->getMessage());
        $errors[] = 'An error occurred while updating permissions. Please try again.';
    }
}

include __DIR__ . '/../includes/header.php';
?>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Role: <?php echo htmlspecialchars($role['role_name']); ?></h2>
        <div style="display: flex; gap: 10px;">
            <a href="<?php echo BASE_URL; ?>/modules/settings/index.php" class="btn btn-secondary">Back to Settings</a>
            <a href="<?php echo BASE_URL; ?>/admin/roles.php" class="btn btn-secondary">Back to Roles</a>
            <a href="<?php echo BASE_URL; ?>/admin/roles_edit_detail.php?id=<?php echo $roleId; ?>" class="btn btn-primary">Edit Role</a>
        </div>
    </div>
    
    <?php if ($success): ?>
    <div class="alert alert-success" style="margin-top: 20px;">
        Permissions updated successfully.
    </div>
    <?php endif; ?>
    
    <?php if (!empty($errors)): ?>
    <div class="alert alert-error" style="margin-top: 20px;">
        <ul style="margin: 0; padding-left: 20px;">
            <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>
    
    <div style="margin-top: 20px;">
        <table class="data-table" style="margin-bottom: 30px;">
            <tr>
                <td><strong>Role Code</strong></td>
                <td><?php echo htmlspecialchars($role['role_code']); ?></td>
            </tr>
            <tr>
                <td><strong>Role Name</strong></td>
                <td><?php echo htmlspecialchars($role['role_name']); ?></td>
            </tr>
            <tr>
                <td><strong>Description</strong></td>
                <td><?php echo htmlspecialchars($role['role_description'] ?? 'N/A'); ?></td>
            </tr>
            <tr>
                <td><strong>Type</strong></td>
                <td>
                    <span class="status-badge status-<?php echo $role['is_system_role'] ? 'active' : 'inactive'; ?>">
                        <?php echo $role['is_system_role'] ? 'System Role' : 'Custom Role'; ?>
                    </span>
                </td>
            </tr>
        </table>
        
        <form method="POST">
            <h3 style="margin-bottom: 15px;">Role Permissions</h3>
            <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
                <?php foreach ($permissionsByModule as $module => $permissions): ?>
                <div style="padding: 15px; background: #f9fafb; border-radius: 8px;">
                    <h4 style="margin-bottom: 10px; text-transform: uppercase; color: var(--primary-color);">
                        <?php echo htmlspecialchars($module); ?>
                    </h4>
                    <?php foreach ($permissions as $perm): ?>
                    <label style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px; cursor: pointer;">
                        <input type="checkbox" name="permissions[]" value="<?php echo $perm['permission_id']; ?>"
                               <?php echo in_array($perm['permission_id'], $rolePermissions) ? 'checked' : ''; ?>>
                        <span><?php echo htmlspecialchars($perm['permission_name']); ?></span>
                    </label>
                    <?php endforeach; ?>
                </div>
                <?php endforeach; ?>
            </div>
            
            <?php if (!$role['is_system_role']): ?>
            <div style="margin-top: 30px; text-align: right; padding-top: 20px; border-top: 1px solid var(--border-color);">
                <button type="submit" name="update_permissions" class="btn btn-primary">Update Permissions</button>
            </div>
            <?php else: ?>
            <div style="margin-top: 20px; padding: 15px; background: #fef3c7; border-radius: 6px;">
                <p style="margin: 0; color: #92400e;">
                    <strong>Note:</strong> System roles cannot be modified. Permissions are managed automatically.
                </p>
            </div>
            <?php endif; ?>
        </form>
    </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>

