from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.db import transaction
from .models import CustomUser, RolePermission, UserPermission, DefaultRolePermission
from .decorators import admin_required
import json


# Mapping from simplified permission names to actual module codes in RolePermission
MODULE_NAME_TO_CODE = {
    'Dashboard': 'dashboard',
    'Clients': 'clients',
    'Loans': 'loans',
    'Repayments': 'repayments',
    'Portfolio': 'portfolio',
    'Reports & Statements': 'reports_statements',
    'Documents': 'documents',
    'Customer Documents': 'customer_documents',
    'Payment Receipts': 'payment_receipts',
    'Notifications': 'notifications',
    'Settings': 'settings',
    'Branch Settings': 'branch_settings',
    'System Settings': 'system_settings',
}

def get_module_code(module_name):
    """Convert simplified permission module name to actual module code"""
    return MODULE_NAME_TO_CODE.get(module_name, module_name.lower().replace(' ', '_').replace('&', '').replace('-', '_'))

# Define the simplified permission structure based on your requirements
SIMPLIFIED_PERMISSIONS = {
        'Dashboard': {
            'access': 'Access Dashboard',
            'create': 'Create Dashboard Items',
            'edit': 'Edit Dashboard Items',
            'delete': 'Delete Dashboard Items',
            'approve': 'Approve Dashboard Actions',
            'reject': 'Reject Dashboard Actions',
            'verify': 'Verify Dashboard Data',
            'validate': 'Validate Dashboard Information',
            'export': 'Export Dashboard Data',
            'import': 'Import Dashboard Data',
            'download': 'Download Dashboard Files',
            'upload': 'Upload Dashboard Files',
            'print': 'Print Dashboard Reports',
            'process': 'Process Dashboard Actions',
            'calculate': 'Calculate Dashboard Metrics',
            'generate': 'Generate Dashboard Reports',
            'record': 'Record Dashboard Activities',
            'reconcile': 'Reconcile Dashboard Data',
            'assign': 'Assign Dashboard Tasks',
            'reassign': 'Reassign Dashboard Tasks',
            'manage': 'Manage Dashboard Settings',
            'configure': 'Configure Dashboard',
            'send': 'Send Dashboard Notifications',
            'email': 'Email Dashboard Reports',
            'notify': 'Send Dashboard Notifications',
            'share': 'Share Dashboard Data',
            'activate': 'Activate Dashboard Features',
            'deactivate': 'Deactivate Dashboard Features',
            'suspend': 'Suspend Dashboard Access',
            'close': 'Close Dashboard Items',
            'monitor': 'Monitor Dashboard Activity',
            'audit': 'Audit Dashboard Actions',
            'backup': 'Backup Dashboard Data',
            'restore': 'Restore Dashboard Data'
        },
        'Clients': {
            'access': 'Access Clients',
            'create': 'Create New Clients',
            'edit': 'Edit Client Information',
            'delete': 'Delete Clients',
            'approve': 'Approve Client Applications',
            'reject': 'Reject Client Applications',
            'verify': 'Verify Client Information',
            'validate': 'Validate Client Data',
            'export': 'Export Client Data',
            'import': 'Import Client Data',
            'download': 'Download Client Files',
            'upload': 'Upload Client Documents',
            'print': 'Print Client Reports',
            'process': 'Process Client Applications',
            'calculate': 'Calculate Client Metrics',
            'generate': 'Generate Client Reports',
            'record': 'Record Client Activities',
            'reconcile': 'Reconcile Client Data',
            'assign': 'Assign Clients to Officers',
            'reassign': 'Reassign Clients',
            'manage': 'Manage Client Accounts',
            'configure': 'Configure Client Settings',
            'send': 'Send Client Communications',
            'email': 'Email Clients',
            'notify': 'Send Client Notifications',
            'share': 'Share Client Information',
            'activate': 'Activate Client Accounts',
            'deactivate': 'Deactivate Client Accounts',
            'suspend': 'Suspend Client Accounts',
            'close': 'Close Client Accounts',
            'monitor': 'Monitor Client Activity',
            'audit': 'Audit Client Actions',
            'backup': 'Backup Client Data',
            'restore': 'Restore Client Data'
        },
        'Loans': {
            'access': 'Access Loans',
            'create': 'Create Loan Applications',
            'edit': 'Edit Loan Information',
            'delete': 'Delete Loans',
            'approve': 'Approve Loan Applications',
            'reject': 'Reject Loan Applications',
            'verify': 'Verify Loan Information',
            'validate': 'Validate Loan Data',
            'export': 'Export Loan Data',
            'import': 'Import Loan Data',
            'download': 'Download Loan Documents',
            'upload': 'Upload Loan Documents',
            'print': 'Print Loan Reports',
            'process': 'Process Loan Applications',
            'calculate': 'Calculate Loan Interest',
            'generate': 'Generate Loan Reports',
            'record': 'Record Loan Activities',
            'reconcile': 'Reconcile Loan Data',
            'assign': 'Assign Loans to Officers',
            'reassign': 'Reassign Loans',
            'manage': 'Manage Loan Portfolio',
            'configure': 'Configure Loan Settings',
            'send': 'Send Loan Communications',
            'email': 'Email Loan Information',
            'notify': 'Send Loan Notifications',
            'share': 'Share Loan Information',
            'activate': 'Activate Loans',
            'deactivate': 'Deactivate Loans',
            'suspend': 'Suspend Loans',
            'close': 'Close Loans',
            'monitor': 'Monitor Loan Performance',
            'audit': 'Audit Loan Actions',
            'backup': 'Backup Loan Data',
            'restore': 'Restore Loan Data'
        },
        'Repayments': {
            'access': 'Access Repayments',
            'create': 'Create Repayment Records',
            'edit': 'Edit Repayment Information',
            'delete': 'Delete Repayments',
            'approve': 'Approve Repayments',
            'reject': 'Reject Repayments',
            'verify': 'Verify Repayment Information',
            'validate': 'Validate Repayment Data',
            'export': 'Export Repayment Data',
            'import': 'Import Repayment Data',
            'download': 'Download Repayment Reports',
            'upload': 'Upload Repayment Files',
            'print': 'Print Repayment Reports',
            'process': 'Process Repayments',
            'calculate': 'Calculate Repayment Amounts',
            'generate': 'Generate Repayment Reports',
            'record': 'Record Repayment Activities',
            'reconcile': 'Reconcile Repayments',
            'assign': 'Assign Repayment Tasks',
            'reassign': 'Reassign Repayment Tasks',
            'manage': 'Manage Repayment System',
            'configure': 'Configure Repayment Settings',
            'send': 'Send Repayment Communications',
            'email': 'Email Repayment Information',
            'notify': 'Send Repayment Notifications',
            'share': 'Share Repayment Information',
            'activate': 'Activate Repayment Features',
            'deactivate': 'Deactivate Repayment Features',
            'suspend': 'Suspend Repayment Processing',
            'close': 'Close Repayment Records',
            'monitor': 'Monitor Repayment Activity',
            'audit': 'Audit Repayment Actions',
            'backup': 'Backup Repayment Data',
            'restore': 'Restore Repayment Data'
        },
        'Portfolio': {
            'access': 'Access Portfolio',
            'create': 'Create Portfolio Items',
            'edit': 'Edit Portfolio Information',
            'delete': 'Delete Portfolio Items',
            'approve': 'Approve Portfolio Actions',
            'reject': 'Reject Portfolio Actions',
            'verify': 'Verify Portfolio Information',
            'validate': 'Validate Portfolio Data',
            'export': 'Export Portfolio Data',
            'import': 'Import Portfolio Data',
            'download': 'Download Portfolio Reports',
            'upload': 'Upload Portfolio Files',
            'print': 'Print Portfolio Reports',
            'process': 'Process Portfolio Actions',
            'calculate': 'Calculate Portfolio Metrics',
            'generate': 'Generate Portfolio Reports',
            'record': 'Record Portfolio Activities',
            'reconcile': 'Reconcile Portfolio Data',
            'assign': 'Assign Portfolio Items',
            'reassign': 'Reassign Portfolio Items',
            'manage': 'Manage Portfolio',
            'configure': 'Configure Portfolio Settings',
            'send': 'Send Portfolio Communications',
            'email': 'Email Portfolio Information',
            'notify': 'Send Portfolio Notifications',
            'share': 'Share Portfolio Information',
            'activate': 'Activate Portfolio Features',
            'deactivate': 'Deactivate Portfolio Features',
            'suspend': 'Suspend Portfolio Access',
            'close': 'Close Portfolio Items',
            'monitor': 'Monitor Portfolio Performance',
            'audit': 'Audit Portfolio Actions',
            'backup': 'Backup Portfolio Data',
            'restore': 'Restore Portfolio Data'
        },
        'Reports & Statements': {
            'access': 'Access Reports & Statements',
            'create': 'Create Reports',
            'edit': 'Edit Reports',
            'delete': 'Delete Reports',
            'approve': 'Approve Reports',
            'reject': 'Reject Reports',
            'verify': 'Verify Report Data',
            'validate': 'Validate Report Information',
            'export': 'Export Reports',
            'import': 'Import Report Data',
            'download': 'Download Reports',
            'upload': 'Upload Report Files',
            'print': 'Print Reports',
            'process': 'Process Report Requests',
            'calculate': 'Calculate Report Metrics',
            'generate': 'Generate Reports',
            'record': 'Record Report Activities',
            'reconcile': 'Reconcile Report Data',
            'assign': 'Assign Report Tasks',
            'reassign': 'Reassign Report Tasks',
            'manage': 'Manage Reporting System',
            'configure': 'Configure Report Settings',
            'send': 'Send Reports',
            'email': 'Email Reports',
            'notify': 'Send Report Notifications',
            'share': 'Share Reports',
            'activate': 'Activate Report Features',
            'deactivate': 'Deactivate Report Features',
            'suspend': 'Suspend Report Access',
            'close': 'Close Report Items',
            'monitor': 'Monitor Report Usage',
            'audit': 'Audit Report Actions',
            'backup': 'Backup Report Data',
            'restore': 'Restore Report Data'
        },
        'Documents': {
            'access': 'Access Documents',
            'create': 'Create Documents',
            'edit': 'Edit Documents',
            'delete': 'Delete Documents',
            'approve': 'Approve Documents',
            'reject': 'Reject Documents',
            'verify': 'Verify Documents',
            'validate': 'Validate Document Information',
            'export': 'Export Documents',
            'import': 'Import Documents',
            'download': 'Download Documents',
            'upload': 'Upload Documents',
            'print': 'Print Documents',
            'process': 'Process Document Requests',
            'calculate': 'Calculate Document Metrics',
            'generate': 'Generate Documents',
            'record': 'Record Document Activities',
            'reconcile': 'Reconcile Document Data',
            'assign': 'Assign Document Tasks',
            'reassign': 'Reassign Document Tasks',
            'manage': 'Manage Document System',
            'configure': 'Configure Document Settings',
            'send': 'Send Documents',
            'email': 'Email Documents',
            'notify': 'Send Document Notifications',
            'share': 'Share Documents',
            'activate': 'Activate Document Features',
            'deactivate': 'Deactivate Document Features',
            'suspend': 'Suspend Document Access',
            'close': 'Close Document Items',
            'monitor': 'Monitor Document Usage',
            'audit': 'Audit Document Actions',
            'backup': 'Backup Documents',
            'restore': 'Restore Documents'
        },
        'Customer Documents': {
            'access': 'Access Customer Documents',
            'create': 'Create Customer Documents',
            'edit': 'Edit Customer Documents',
            'delete': 'Delete Customer Documents',
            'approve': 'Approve Customer Documents',
            'reject': 'Reject Customer Documents',
            'verify': 'Verify Customer Documents',
            'validate': 'Validate Customer Document Information',
            'export': 'Export Customer Documents',
            'import': 'Import Customer Documents',
            'download': 'Download Customer Documents',
            'upload': 'Upload Customer Documents',
            'print': 'Print Customer Documents',
            'process': 'Process Customer Document Requests',
            'calculate': 'Calculate Customer Document Metrics',
            'generate': 'Generate Customer Documents',
            'record': 'Record Customer Document Activities',
            'reconcile': 'Reconcile Customer Document Data',
            'assign': 'Assign Customer Document Tasks',
            'reassign': 'Reassign Customer Document Tasks',
            'manage': 'Manage Customer Document System',
            'configure': 'Configure Customer Document Settings',
            'send': 'Send Customer Documents',
            'email': 'Email Customer Documents',
            'notify': 'Send Customer Document Notifications',
            'share': 'Share Customer Documents',
            'activate': 'Activate Customer Document Features',
            'deactivate': 'Deactivate Customer Document Features',
            'suspend': 'Suspend Customer Document Access',
            'close': 'Close Customer Document Items',
            'monitor': 'Monitor Customer Document Usage',
            'audit': 'Audit Customer Document Actions',
            'backup': 'Backup Customer Documents',
            'restore': 'Restore Customer Documents'
        },
        'Payment Receipts': {
            'access': 'Access Payment Receipts',
            'create': 'Create Payment Receipts',
            'edit': 'Edit Payment Receipts',
            'delete': 'Delete Payment Receipts',
            'approve': 'Approve Payment Receipts',
            'reject': 'Reject Payment Receipts',
            'verify': 'Verify Payment Receipts',
            'validate': 'Validate Payment Receipt Information',
            'export': 'Export Payment Receipts',
            'import': 'Import Payment Receipts',
            'download': 'Download Payment Receipts',
            'upload': 'Upload Payment Receipt Files',
            'print': 'Print Payment Receipts',
            'process': 'Process Payment Receipt Requests',
            'calculate': 'Calculate Payment Receipt Amounts',
            'generate': 'Generate Payment Receipts',
            'record': 'Record Payment Receipt Activities',
            'reconcile': 'Reconcile Payment Receipts',
            'assign': 'Assign Payment Receipt Tasks',
            'reassign': 'Reassign Payment Receipt Tasks',
            'manage': 'Manage Payment Receipt System',
            'configure': 'Configure Payment Receipt Settings',
            'send': 'Send Payment Receipts',
            'email': 'Email Payment Receipts',
            'notify': 'Send Payment Receipt Notifications',
            'share': 'Share Payment Receipts',
            'activate': 'Activate Payment Receipt Features',
            'deactivate': 'Deactivate Payment Receipt Features',
            'suspend': 'Suspend Payment Receipt Access',
            'close': 'Close Payment Receipt Items',
            'monitor': 'Monitor Payment Receipt Usage',
            'audit': 'Audit Payment Receipt Actions',
            'backup': 'Backup Payment Receipts',
            'restore': 'Restore Payment Receipts'
        },
        'Notifications': {
            'access': 'Access Notifications',
            'create': 'Create Notifications',
            'edit': 'Edit Notifications',
            'delete': 'Delete Notifications',
            'approve': 'Approve Notifications',
            'reject': 'Reject Notifications',
            'verify': 'Verify Notification Information',
            'validate': 'Validate Notification Data',
            'export': 'Export Notifications',
            'import': 'Import Notifications',
            'download': 'Download Notification Reports',
            'upload': 'Upload Notification Files',
            'print': 'Print Notification Reports',
            'process': 'Process Notification Requests',
            'calculate': 'Calculate Notification Metrics',
            'generate': 'Generate Notifications',
            'record': 'Record Notification Activities',
            'reconcile': 'Reconcile Notification Data',
            'assign': 'Assign Notification Tasks',
            'reassign': 'Reassign Notification Tasks',
            'manage': 'Manage Notification System',
            'configure': 'Configure Notification Settings',
            'send': 'Send Notifications',
            'email': 'Email Notifications',
            'notify': 'Send System Notifications',
            'share': 'Share Notification Information',
            'activate': 'Activate Notification Features',
            'deactivate': 'Deactivate Notification Features',
            'suspend': 'Suspend Notification Access',
            'close': 'Close Notification Items',
            'monitor': 'Monitor Notification Activity',
            'audit': 'Audit Notification Actions',
            'backup': 'Backup Notification Data',
            'restore': 'Restore Notification Data'
        },
        'Settings': {
            'access': 'Access Settings',
            'create': 'Create Settings',
            'edit': 'Edit Settings',
            'delete': 'Delete Settings',
            'approve': 'Approve Setting Changes',
            'reject': 'Reject Setting Changes',
            'verify': 'Verify Setting Information',
            'validate': 'Validate Setting Data',
            'export': 'Export Settings',
            'import': 'Import Settings',
            'download': 'Download Setting Files',
            'upload': 'Upload Setting Files',
            'print': 'Print Setting Reports',
            'process': 'Process Setting Requests',
            'calculate': 'Calculate Setting Metrics',
            'generate': 'Generate Setting Reports',
            'record': 'Record Setting Activities',
            'reconcile': 'Reconcile Setting Data',
            'assign': 'Assign Setting Tasks',
            'reassign': 'Reassign Setting Tasks',
            'manage': 'Manage System Settings',
            'configure': 'Configure System Settings',
            'send': 'Send Setting Communications',
            'email': 'Email Setting Information',
            'notify': 'Send Setting Notifications',
            'share': 'Share Setting Information',
            'activate': 'Activate Setting Features',
            'deactivate': 'Deactivate Setting Features',
            'suspend': 'Suspend Setting Access',
            'close': 'Close Setting Items',
            'monitor': 'Monitor Setting Usage',
            'audit': 'Audit Setting Actions',
            'backup': 'Backup Settings',
            'restore': 'Restore Settings'
        },
        'Branch Settings': {
            'access': 'Access Branch Settings',
            'create': 'Create Branch Settings',
            'edit': 'Edit Branch Settings',
            'delete': 'Delete Branch Settings',
            'approve': 'Approve Branch Setting Changes',
            'reject': 'Reject Branch Setting Changes',
            'verify': 'Verify Branch Setting Information',
            'validate': 'Validate Branch Setting Data',
            'export': 'Export Branch Settings',
            'import': 'Import Branch Settings',
            'download': 'Download Branch Setting Files',
            'upload': 'Upload Branch Setting Files',
            'print': 'Print Branch Setting Reports',
            'process': 'Process Branch Setting Requests',
            'calculate': 'Calculate Branch Setting Metrics',
            'generate': 'Generate Branch Setting Reports',
            'record': 'Record Branch Setting Activities',
            'reconcile': 'Reconcile Branch Setting Data',
            'assign': 'Assign Branch Setting Tasks',
            'reassign': 'Reassign Branch Setting Tasks',
            'manage': 'Manage Branch Settings',
            'configure': 'Configure Branch Settings',
            'send': 'Send Branch Setting Communications',
            'email': 'Email Branch Setting Information',
            'notify': 'Send Branch Setting Notifications',
            'share': 'Share Branch Setting Information',
            'activate': 'Activate Branch Setting Features',
            'deactivate': 'Deactivate Branch Setting Features',
            'suspend': 'Suspend Branch Setting Access',
            'close': 'Close Branch Setting Items',
            'monitor': 'Monitor Branch Setting Usage',
            'audit': 'Audit Branch Setting Actions',
            'backup': 'Backup Branch Settings',
            'restore': 'Restore Branch Settings'
        },
        'System Settings': {
            'access': 'Access System Settings',
            'create': 'Create System Settings',
            'edit': 'Edit System Settings',
            'delete': 'Delete System Settings',
            'approve': 'Approve System Setting Changes',
            'reject': 'Reject System Setting Changes',
            'verify': 'Verify System Setting Information',
            'validate': 'Validate System Setting Data',
            'export': 'Export System Settings',
            'import': 'Import System Settings',
            'download': 'Download System Setting Files',
            'upload': 'Upload System Setting Files',
            'print': 'Print System Setting Reports',
            'process': 'Process System Setting Requests',
            'calculate': 'Calculate System Setting Metrics',
            'generate': 'Generate System Setting Reports',
            'record': 'Record System Setting Activities',
            'reconcile': 'Reconcile System Setting Data',
            'assign': 'Assign System Setting Tasks',
            'reassign': 'Reassign System Setting Tasks',
            'manage': 'Manage System Settings',
            'configure': 'Configure System Settings',
            'send': 'Send System Setting Communications',
            'email': 'Email System Setting Information',
            'notify': 'Send System Setting Notifications',
            'share': 'Share System Setting Information',
            'activate': 'Activate System Setting Features',
            'deactivate': 'Deactivate System Setting Features',
            'suspend': 'Suspend System Setting Access',
            'close': 'Close System Setting Items',
            'monitor': 'Monitor System Setting Usage',
            'audit': 'Audit System Setting Actions',
            'backup': 'Backup System Settings',
            'restore': 'Restore System Settings'
        }
    }


@login_required
@admin_required
def simplified_user_permissions(request, user_id):
    """Simplified permission management interface focusing on core pages"""
    
    # IMPORTANT: Store the current admin user BEFORE any operations
    current_admin = request.user
    current_admin_id = current_admin.id
    
    # Log the access attempt for debugging
    import logging
    logger = logging.getLogger(__name__)
    logger.info(f"Simplified permissions access: Admin={current_admin.username} (ID: {current_admin_id}) accessing permissions for user_id={user_id}")
    
    # Security check: Ensure the current user is an admin (double-check)
    if not request.user.is_authenticated:
        messages.error(request, 'You must be logged in to access this page.')
        return redirect('users:login')
    
    if request.user.role != 'admin' and not request.user.is_superuser:
        messages.error(request, 'Only administrators can manage user permissions.')
        return redirect('users:admin_list')
    
    # CRITICAL: Verify we're still logged in as the admin
    if request.user.id != current_admin_id:
        logger.error(f"SECURITY VIOLATION: User switched from {current_admin_id} to {request.user.id}")
        messages.error(request, 'Security violation detected. Please log out and log back in.')
        return redirect('users:admin_list')
    
    # Get the target user (the one whose permissions we're managing)
    user = get_object_or_404(CustomUser, id=user_id)
    
    # CRITICAL: Verify we're STILL logged in as the admin, not the target user
    if request.user.id == user.id:
        logger.error(f"SECURITY VIOLATION: Admin is logged in as target user {user.id}")
        messages.error(request, 'Security violation: Cannot manage your own permissions this way.')
        return redirect('users:admin_list')
    
    # CRITICAL: Double-check we're still the admin
    if request.user.id != current_admin_id:
        logger.error(f"SECURITY VIOLATION: User changed during request from {current_admin_id} to {request.user.id}")
        messages.error(request, 'Security violation detected. Session may have been compromised.')
        return redirect('users:admin_list')
    
    # Important: Do NOT log in as this user - we're just managing their permissions
    # The current logged-in user (request.user) should remain the admin
    
    if request.method == 'POST':
        # Check if this is an AJAX request
        is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' or \
                  request.content_type == 'application/json'
        
        # Log POST data for debugging (only first 20 fields to avoid log spam)
        post_fields = list(request.POST.keys())
        logger.info(f"POST request received: Admin={request.user.id}, User={user.id}, "
                   f"Fields count={len(post_fields)}, "
                   f"Sample fields={post_fields[:20]}")
        
        try:
            permissions_created = 0
            permissions_deleted = 0
            fields_processed = 0
            fields_matched = 0
            
            with transaction.atomic():
                # Clear existing custom permissions for this user
                deleted_count = UserPermission.objects.filter(user=user).delete()[0]
                permissions_deleted = deleted_count
                logger.info(f"Cleared {deleted_count} existing permissions for user {user.id}")
                
                # Process each module and action
                for module_name, actions in SIMPLIFIED_PERMISSIONS.items():
                    # Convert module name to code using the mapping
                    module_code = get_module_code(module_name)
                    
                    for action_code, action_description in actions.items():
                        field_name = f'perm_{module_code}_{action_code}'
                        fields_processed += 1
                        is_allowed = request.POST.get(field_name) == 'on'
                        
                        if field_name in request.POST:
                            fields_matched += 1
                        
                        # Get role default permission
                        try:
                            role_perm = RolePermission.objects.get(
                                role=user.role,
                                module=module_code,
                                action=action_code
                            )
                            role_default = role_perm.is_allowed
                        except RolePermission.DoesNotExist:
                            # Check default role permissions
                            try:
                                default_perm = DefaultRolePermission.objects.get(
                                    role=user.role,
                                    module=module_code,
                                    action=action_code
                                )
                                role_default = default_perm.is_allowed
                            except DefaultRolePermission.DoesNotExist:
                                role_default = False
                        
                        # IMPORTANT: Always create custom permission if checkbox is checked
                        # This ensures the permission persists even if defaults change
                        # We only skip creating if checkbox is unchecked AND it matches the default
                        if is_allowed:
                            # Checkbox is checked - always create custom permission
                            UserPermission.objects.update_or_create(
                                user=user,
                                module=module_code,
                                action=action_code,
                                defaults={
                                    'is_allowed': True,
                                    'granted_by': request.user,
                                    'reason': f'Custom permission for {action_description}'
                                }
                            )
                            permissions_created += 1
                            logger.debug(f"Created/updated permission: {module_code}.{action_code} = True for user {user.id}")
                        elif is_allowed != role_default:
                            # Checkbox is unchecked but differs from default - create explicit denial
                            UserPermission.objects.update_or_create(
                                user=user,
                                module=module_code,
                                action=action_code,
                                defaults={
                                    'is_allowed': False,
                                    'granted_by': request.user,
                                    'reason': f'Custom permission denied for {action_description}'
                                }
                            )
                            permissions_created += 1
                            logger.debug(f"Created/updated permission: {module_code}.{action_code} = False for user {user.id}")
                        # If checkbox is unchecked AND matches default, no custom permission needed
                
                # Log the permission update
                request.user.log_access(
                    action='update_permissions',
                    module='users',
                    object_type='CustomUser',
                    object_id=str(user.id),
                    description=f'Updated simplified permissions for {user.get_full_name()}',
                    request=request
                )
                
                logger.info(f"Successfully updated permissions: Admin={request.user.id} updated User={user.id}, "
                           f"created={permissions_created}, deleted={permissions_deleted}, "
                           f"fields_processed={fields_processed}, fields_matched={fields_matched}")
                
                # Return JSON for AJAX requests, redirect for regular form submissions
                if is_ajax:
                    return JsonResponse({
                        'success': True,
                        'message': f'Permissions updated successfully for {user.get_full_name()}',
                        'permissions_created': permissions_created,
                        'permissions_deleted': permissions_deleted
                    })
                
                messages.success(request, f'Permissions updated successfully for {user.get_full_name()}')
                return redirect('users:admin_list')
                
        except Exception as e:
            error_msg = f'Error updating permissions: {str(e)}'
            logger.error(f"Permission update failed: Admin={request.user.id}, User={user.id}, Error={str(e)}", 
                        exc_info=True)
            
            # Return JSON for AJAX requests, flash message for regular form submissions
            if is_ajax:
                return JsonResponse({
                    'success': False,
                    'error': error_msg
                }, status=500)
            
            messages.error(request, error_msg)
    
    # Get current effective permissions for the user
    current_permissions = {}
    for module_name, actions in SIMPLIFIED_PERMISSIONS.items():
        module_code = get_module_code(module_name)
        current_permissions[module_name] = {}
        
        for action_code, action_description in actions.items():
            # Check if user has a custom permission override
            is_custom = False
            custom_allowed = None
            try:
                user_perm = UserPermission.objects.get(
                    user=user,
                    module=module_code,
                    action=action_code
                )
                is_custom = True
                custom_allowed = user_perm.is_allowed
                logger.debug(f"Found custom permission for {user.id}: {module_code}.{action_code} = {custom_allowed}")
            except UserPermission.DoesNotExist:
                # No custom permission - will use role default
                pass
            
            # Determine effective permission
            if is_custom:
                # Use custom permission value
                has_permission = custom_allowed
            else:
                # Check role default
                has_permission = user.has_permission(module_code, action_code)
            
            current_permissions[module_name][action_code] = {
                'allowed': has_permission,
                'custom': is_custom,
                'description': action_description,
                'action_name': action_description  # For template display
            }
    
    # Calculate permission summary
    total_permissions = 0
    allowed_permissions = 0
    denied_permissions = 0
    custom_overrides = 0
    
    for module_name, actions in current_permissions.items():
        for action_code, perm_info in actions.items():
            total_permissions += 1
            if perm_info.get('allowed', False):
                allowed_permissions += 1
            else:
                denied_permissions += 1
            if perm_info.get('custom', False):
                custom_overrides += 1
    
    permission_summary = {
        'total_permissions': total_permissions,
        'allowed_permissions': allowed_permissions,
        'denied_permissions': denied_permissions,
        'custom_overrides': custom_overrides,
    }
    
    # FINAL SECURITY CHECK: Ensure we're still logged in as the admin
    if request.user.id != current_admin_id:
        logger.error(f"SECURITY VIOLATION: User changed at end of request from {current_admin_id} to {request.user.id}")
        messages.error(request, 'Security violation detected. Please log out and log back in.')
        return redirect('users:admin_list')
    
    if request.user.id == user.id:
        logger.error(f"SECURITY VIOLATION: Admin is logged in as target user {user.id}")
        messages.error(request, 'Security violation: Cannot manage your own permissions this way.')
        return redirect('users:admin_list')
    
    # CRITICAL: Use 'target_user' instead of 'user' to avoid overriding Django's default 'user' (request.user)
    # This prevents the base template from using the target user instead of the logged-in admin
    context = {
        'target_user': user,  # Target user whose permissions we're managing (DO NOT use 'user' as it overrides request.user)
        'user': request.user,  # Explicitly set to admin to ensure base template uses correct user
        'current_admin': request.user,  # The admin managing permissions
        'permissions': current_permissions,
        'simplified_permissions': SIMPLIFIED_PERMISSIONS,
        'permission_summary': permission_summary,
    }
    
    # Log successful access
    logger.info(f"Successfully rendering permissions page: Admin={request.user.username} (ID: {request.user.id}) managing User={user.username} (ID: {user.id})")
    
    return render(request, 'users/simplified_user_permissions.html', context)


@login_required
@admin_required
@require_http_methods(["POST"])
def bulk_update_simplified_permissions(request):
    """Bulk update permissions for multiple users"""
    try:
        user_ids = request.POST.getlist('user_ids')
        template_user_id = request.POST.get('template_user_id')
        
        if not user_ids or not template_user_id:
            return JsonResponse({'success': False, 'error': 'Missing required parameters'})
        
        template_user = get_object_or_404(CustomUser, id=template_user_id)
        users_to_update = CustomUser.objects.filter(id__in=user_ids)
        
        with transaction.atomic():
            # Get template user's custom permissions
            template_permissions = UserPermission.objects.filter(user=template_user)
            
            for user in users_to_update:
                # Clear existing custom permissions
                UserPermission.objects.filter(user=user).delete()
                
                # Copy template permissions
                for perm in template_permissions:
                    UserPermission.objects.create(
                        user=user,
                        module=perm.module,
                        action=perm.action,
                        is_allowed=perm.is_allowed,
                        granted_by=request.user,
                        reason=f'Copied from {template_user.get_full_name()}'
                    )
        
        return JsonResponse({
            'success': True,
            'message': f'Permissions updated for {len(users_to_update)} users'
        })
        
    except Exception as e:
        return JsonResponse({'success': False, 'error': str(e)})


@login_required
@admin_required
def get_simplified_role_permissions(request, role):
    """Get default permissions for a role in simplified format"""
    try:
        permissions = {}
        
        # Get default permissions for the role
        default_perms = DefaultRolePermission.objects.filter(role=role)
        
        for perm in default_perms:
            if perm.module not in permissions:
                permissions[perm.module] = {}
            permissions[perm.module][perm.action] = perm.is_allowed
        
        return JsonResponse({'success': True, 'permissions': permissions})
        
    except Exception as e:
        return JsonResponse({'success': False, 'error': str(e)})