<?php
/**
 * Enterprise HRM ERP System - Role Editor Detail
 * Edit role details and 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 edit roles. Your role: ' . ($roleCode ?: 'Unknown'), 'error');
}

$pageTitle = 'Role Editor';
$currentModule = 'settings';

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

if ($roleId <= 0) {
    redirect(BASE_URL . '/admin/roles_edit.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_edit.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_edit.php', 'Error loading role data.', 'error');
}

$errors = [];
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'role_name' => sanitize($_POST['role_name'] ?? ''),
        'role_description' => sanitize($_POST['role_description'] ?? ''),
        'permissions' => $_POST['permissions'] ?? [],
    ];
    
    // Validation
    if (empty($formData['role_name'])) {
        $errors[] = 'Role name is required.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            $db->beginTransaction();
            
            // Update role (allow editing role name even for system roles as requested)
            $stmt = $db->prepare("
                UPDATE roles SET
                    role_name = ?,
                    role_description = ?,
                    updated_at = NOW()
                WHERE role_id = ?
            ");
            $stmt->execute([
                $formData['role_name'],
                $formData['role_description'],
                $roleId
            ]);
            
            // Update permissions (allowed for all roles)
            // Delete existing permissions
            $stmt = $db->prepare("DELETE FROM role_permissions WHERE role_id = ?");
            $stmt->execute([$roleId]);
            
            // Insert new permissions
            if (!empty($formData['permissions'])) {
                $stmt = $db->prepare("INSERT INTO role_permissions (role_id, permission_id) VALUES (?, ?)");
                foreach ($formData['permissions'] 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 role: " . $e->getMessage());
            $errors[] = 'An error occurred while updating role.';
        }
    }
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Role Editor: <?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_edit.php" class="btn btn-secondary">Back to Role Editor</a>
            <a href="<?php echo BASE_URL; ?>/admin/roles.php" class="btn btn-secondary">Role Management</a>
        </div>
    </div>
    
    <?php if ($success): ?>
    <div class="alert alert-success" style="margin-top: 20px;">
        Role 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; ?>
    
    <form method="POST" style="margin-top: 20px;">
        <!-- Role Details -->
        <div style="margin-bottom: 30px;">
            <h3 style="margin-bottom: 15px;">Role Details</h3>
            <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
                <div class="form-group">
                    <label class="form-label">Role Code</label>
                    <input type="text" class="form-control" value="<?php echo htmlspecialchars($role['role_code']); ?>" disabled>
                    <small style="color: var(--text-secondary);">Role code cannot be changed</small>
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="role_name">Role Name *</label>
                    <input type="text" id="role_name" name="role_name" class="form-control" required
                           value="<?php echo htmlspecialchars($role['role_name']); ?>">
                </div>
                
                <div class="form-group" style="grid-column: 1 / -1;">
                    <label class="form-label" for="role_description">Description</label>
                    <textarea id="role_description" name="role_description" class="form-control" rows="2"><?php echo htmlspecialchars($role['role_description'] ?? ''); ?></textarea>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Type</label>
                    <input type="text" class="form-control" 
                           value="<?php echo $role['is_system_role'] ? 'System Role' : 'Custom Role'; ?>" disabled>
                </div>
            </div>
        </div>
        
        <!-- Permissions -->
        <div style="margin-top: 30px;">
            <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>
            
            <div style="margin-top: 15px;">
                <button type="button" onclick="selectAllPermissions()" class="btn btn-sm btn-secondary">Select All</button>
                <button type="button" onclick="deselectAllPermissions()" class="btn btn-sm btn-secondary">Deselect All</button>
            </div>
        </div>
        
        <div style="margin-top: 30px; text-align: right; padding-top: 20px; border-top: 1px solid var(--border-color);">
            <a href="<?php echo BASE_URL; ?>/admin/roles_edit.php" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Update Role</button>
        </div>
    </form>
</div>

<script>
function selectAllPermissions() {
    document.querySelectorAll('input[name="permissions[]"]').forEach(cb => cb.checked = true);
}

function deselectAllPermissions() {
    document.querySelectorAll('input[name="permissions[]"]').forEach(cb => cb.checked = false);
}
</script>

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

