{% extends 'base.html' %}
{% load static %}
{% load permission_filters %}

{% block title %}Staff Permissions - {{ user.get_full_name }}{% endblock %}

{% block content %}
<div class="space-y-6">
    <!-- Header -->
    <div class="bg-white shadow rounded-lg">
        <div class="px-4 py-5 sm:p-6">
            <div class="flex justify-between items-center">
                <div>
                    <h1 class="text-2xl font-bold text-gray-900">
                        <span>🛡️</span>
                        Staff Permissions
                    </h1>
                    <p class="mt-2 text-sm text-gray-600">
                        Manage detailed permissions for {{ user.get_full_name }}
                    </p>
                </div>
                <div class="flex space-x-3">
                    <a href="{% url 'users:admin_list' %}" 
                       class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md shadow-sm text-gray-700 bg-white hover:bg-gray-50">
                        <span>←</span>
                        Back to Staff List
                    </a>
                    <button onclick="copyPermissionsModal()" 
                            class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md shadow-sm text-gray-700 bg-white hover:bg-gray-50">
                        <span>📋</span>
                        Copy Permissions
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- User Info Card -->
    <div class="bg-white shadow rounded-lg">
        <div class="px-4 py-5 sm:p-6">
            <div class="flex items-center space-x-6">
                <div class="flex-shrink-0 h-20 w-20">
                    {% if user.profile_image %}
                        <img class="h-20 w-20 rounded-full object-cover" src="{{ user.profile_image.url }}" alt="">
                    {% elif user.selfie %}
                        <img class="h-20 w-20 rounded-full object-cover" src="{{ user.selfie.url }}" alt="">
                    {% else %}
                        <div class="h-20 w-20 rounded-full bg-gray-300 flex items-center justify-center">
                            <span class="text-2xl font-medium text-gray-600">{{ user.get_initials }}</span>
                        </div>
                    {% endif %}
                </div>
                <div class="flex-1">
                    <h3 class="text-xl font-medium text-gray-900">{{ user.get_full_name }}</h3>
                    <p class="text-sm text-gray-500">{{ user.email }}</p>
                    <p class="text-sm text-gray-500">{{ user.phone_number }}</p>
                    <div class="mt-2 flex items-center space-x-4">
                        {% if user.role == 'admin' %}
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                <i class="fas fa-crown mr-1"></i>Administrator
                            </span>
                        {% elif user.role == 'team_leader' %}
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                <span>👔</span>Team Leader
                            </span>
                        {% elif user.role == 'loan_officer' %}
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                <i class="fas fa-handshake mr-1"></i>Loan Officer
                            </span>
                        {% elif user.role == 'secretary' %}
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-purple-100 text-purple-800">
                                <i class="fas fa-user-secret mr-1"></i>Secretary
                            </span>
                        {% endif %}
                        
                        {% if user.status == 'active' %}
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                <span>✓</span>Active
                            </span>
                        {% else %}
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                <span>✕</span>{{ user.status|title }}
                            </span>
                        {% endif %}
                    </div>
                </div>
                <div class="flex-shrink-0">
                    <div class="flex space-x-2">
                        <a href="{% url 'users:apply_default_permissions' user.id %}" 
                           onclick="return confirm('This will remove all custom permissions and apply role defaults. Continue?')"
                           class="inline-flex items-center px-3 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                            <span>↶</span>
                            Reset to Defaults
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    {% if messages %}
        {% for message in messages %}
        <div class="bg-{% if message.tags == 'error' %}red{% else %}green{% endif %}-50 border border-{% if message.tags == 'error' %}red{% else %}green{% endif %}-200 rounded-md p-4">
            <div class="flex">
                <div class="flex-shrink-0">
                    <i class="fas fa-{% if message.tags == 'error' %}exclamation-triangle{% else %}check-circle{% endif %} text-{% if message.tags == 'error' %}red{% else %}green{% endif %}-400"></i>
                </div>
                <div class="ml-3">
                    <p class="text-sm text-{% if message.tags == 'error' %}red{% else %}green{% endif %}-700">{{ message }}</p>
                </div>
            </div>
        </div>
        {% endfor %}
    {% endif %}

    <!-- Permissions Form -->
    <form method="post" class="space-y-6">
        {% csrf_token %}
        
        <!-- Permission Legend -->
        <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
            <h4 class="text-sm font-medium text-blue-900 mb-2">Permission Legend</h4>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
                <div class="flex items-center">
                    <div class="w-4 h-4 bg-green-500 rounded mr-2"></div>
                    <span class="text-blue-800">Role Default (Allowed)</span>
                </div>
                <div class="flex items-center">
                    <div class="w-4 h-4 bg-red-500 rounded mr-2"></div>
                    <span class="text-blue-800">Role Default (Denied)</span>
                </div>
                <div class="flex items-center">
                    <div class="w-4 h-4 bg-yellow-500 rounded mr-2"></div>
                    <span class="text-blue-800">Custom Override</span>
                </div>
            </div>
        </div>

        <div class="bg-white shadow rounded-lg">
            <div class="px-4 py-5 sm:p-6">
                <div class="flex justify-between items-center mb-6">
                    <h3 class="text-lg font-medium text-gray-900">
                        <span>⚙️</span>
                        Detailed Permissions
                    </h3>
                    <div class="flex space-x-2">
                        <button type="button" onclick="expandAllModules()" 
                                class="text-sm text-primary hover:text-primary-dark">
                            Expand All
                        </button>
                        <span class="text-gray-300">|</span>
                        <button type="button" onclick="collapseAllModules()" 
                                class="text-sm text-primary hover:text-primary-dark">
                            Collapse All
                        </button>
                    </div>
                </div>

                <div class="space-y-6">
                    <!-- Main Navigation Pages -->
                    <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                        <h3 class="text-lg font-medium text-blue-900 mb-4">
                            <i class="fas fa-sitemap mr-2"></i>Main Navigation Pages
                        </h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {% for module_choice in modules %}
                            {% if module_choice.0 in 'dashboard,clients,loans,repayments,portfolio,reports_statements,documents,customer_documents,payment_receipts,notifications,settings'|split:',' %}
                    {% with module=module_choice.0 module_name=module_choice.1 %}
                            <div class="bg-white border border-gray-200 rounded-lg p-4">
                                <div class="flex items-center justify-between mb-3">
                                    <h4 class="text-sm font-medium text-gray-900">
                                    <i class="fas fa-{{ module|get_module_icon }} text-primary mr-2"></i>
                                    {{ module_name }}
                                </h4>
                                    <button type="button" onclick="toggleModule('{{ module }}')" 
                                            class="text-gray-400 hover:text-gray-600">
                                        <i id="icon-{{ module }}" class="fas fa-chevron-down"></i>
                            </button>
                        </div>
                        
                                <div id="module-{{ module }}" class="space-y-2">
                                {% for action_choice in actions %}
                                {% with action=action_choice.0 action_name=action_choice.1 %}
                                {% with effective_perm=effective_permissions|get_item:module|get_item:action %}
                                    <div class="flex items-center justify-between p-2 border border-gray-100 rounded">
                                        <div class="flex items-center space-x-2">
                                                <input type="checkbox" 
                                                       name="custom_{{ module }}_{{ action }}" 
                                                       id="custom_{{ module }}_{{ action }}"
                                                       {% if effective_perm.source == 'custom' %}checked{% endif %}
                                                       onchange="toggleCustomPermission('{{ module }}', '{{ action }}')"
                                                   class="rounded border-gray-300 text-yellow-500 focus:ring-yellow-500 text-xs">
                                            <input type="checkbox" 
                                                   name="perm_{{ module }}_{{ action }}" 
                                                   id="perm_{{ module }}_{{ action }}"
                                                   {% if effective_perm.allowed %}checked{% endif %}
                                                   {% if effective_perm.source != 'custom' %}disabled{% endif %}
                                                   class="rounded border-gray-300 text-primary focus:ring-primary text-xs">
                                            <span class="text-xs text-gray-700">{{ action_name }}</span>
                                        </div>
                                        <div class="flex items-center space-x-1">
                                            {% if effective_perm.source == 'custom' %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                                                    <i class="fas fa-user-cog mr-1"></i>C
                                                </span>
                                            {% elif effective_perm.source == 'role' %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                                    <i class="fas fa-users-cog mr-1"></i>R
                                                </span>
                                            {% else %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                                                    <i class="fas fa-ban mr-1"></i>S
                                                </span>
                                            {% endif %}
                                            
                                            {% if effective_perm.allowed %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                                    <span>✓</span>✓
                                                </span>
                                            {% else %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                                    <span>✕</span>✗
                                                </span>
                                            {% endif %}
                                        </div>
                                    </div>
                                    {% endwith %}
                                    {% endwith %}
                                    {% endfor %}
                                </div>
                            </div>
                            {% endwith %}
                            {% endif %}
                            {% endfor %}
                        </div>
                    </div>

                    <!-- Dashboard Specific Permissions -->
                    <div class="bg-indigo-50 border border-indigo-200 rounded-lg p-4">
                        <h3 class="text-lg font-medium text-indigo-900 mb-4">
                            <i class="fas fa-tachometer-alt mr-2"></i>Dashboard Specific Permissions
                        </h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            {% for module_choice in modules %}
                            {% if 'dashboard_' in module_choice.0 %}
                            {% with module=module_choice.0 module_name=module_choice.1 %}
                            <div class="bg-white border border-gray-200 rounded-lg p-4">
                                <div class="flex items-center justify-between mb-3">
                                    <h4 class="text-sm font-medium text-gray-900">
                                        <i class="fas fa-{{ module|get_module_icon }} text-indigo-600 mr-2"></i>
                                        {{ module_name }}
                                    </h4>
                                    <button type="button" onclick="toggleModule('{{ module }}')" 
                                            class="text-gray-400 hover:text-gray-600">
                                        <i id="icon-{{ module }}" class="fas fa-chevron-down"></i>
                                    </button>
                                </div>
                                
                                <div id="module-{{ module }}" class="space-y-2">
                                    {% for action_choice in actions %}
                                    {% with action=action_choice.0 action_name=action_choice.1 %}
                                    {% with effective_perm=effective_permissions|get_item:module|get_item:action %}
                                    <div class="flex items-center justify-between p-2 border border-gray-100 rounded">
                                        <div class="flex items-center space-x-2">
                                            <input type="checkbox" 
                                                   name="custom_{{ module }}_{{ action }}" 
                                                   id="custom_{{ module }}_{{ action }}"
                                                   {% if effective_perm.source == 'custom' %}checked{% endif %}
                                                   onchange="toggleCustomPermission('{{ module }}', '{{ action }}')"
                                                   class="rounded border-gray-300 text-yellow-500 focus:ring-yellow-500 text-xs">
                                            <input type="checkbox" 
                                                   name="perm_{{ module }}_{{ action }}" 
                                                   id="perm_{{ module }}_{{ action }}"
                                                   {% if effective_perm.allowed %}checked{% endif %}
                                                   {% if effective_perm.source != 'custom' %}disabled{% endif %}
                                                   class="rounded border-gray-300 text-primary focus:ring-primary text-xs">
                                            <span class="text-xs text-gray-700">{{ action_name }}</span>
                                        </div>
                                        <div class="flex items-center space-x-1">
                                            {% if effective_perm.source == 'custom' %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                                                    <i class="fas fa-user-cog mr-1"></i>C
                                                </span>
                                            {% elif effective_perm.source == 'role' %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                                    <i class="fas fa-users-cog mr-1"></i>R
                                                </span>
                                            {% else %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                                                    <i class="fas fa-ban mr-1"></i>S
                                                </span>
                                            {% endif %}
                                            
                                            {% if effective_perm.allowed %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                                    <span>✓</span>✓
                                                </span>
                                            {% else %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                                    <span>✕</span>✗
                                                </span>
                                            {% endif %}
                                        </div>
                                    </div>
                                    {% endwith %}
                                    {% endwith %}
                                    {% endfor %}
                                </div>
                            </div>
                            {% endwith %}
                            {% endif %}
                            {% endfor %}
                        </div>
                    </div>

                    <!-- Clients Page Specific Permissions -->
                    <div class="bg-green-50 border border-green-200 rounded-lg p-4">
                        <h3 class="text-lg font-medium text-green-900 mb-4">
                            <i class="fas fa-user-friends mr-2"></i>Clients Page Specific Permissions
                        </h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            {% for module_choice in modules %}
                            {% if 'clients_' in module_choice.0 %}
                            {% with module=module_choice.0 module_name=module_choice.1 %}
                            <div class="bg-white border border-gray-200 rounded-lg p-4">
                                <div class="flex items-center justify-between mb-3">
                                    <h4 class="text-sm font-medium text-gray-900">
                                        <i class="fas fa-{{ module|get_module_icon }} text-green-600 mr-2"></i>
                                        {{ module_name }}
                                    </h4>
                                    <button type="button" onclick="toggleModule('{{ module }}')" 
                                            class="text-gray-400 hover:text-gray-600">
                                        <i id="icon-{{ module }}" class="fas fa-chevron-down"></i>
                                    </button>
                                </div>
                                
                                <div id="module-{{ module }}" class="space-y-2">
                                    {% for action_choice in actions %}
                                    {% with action=action_choice.0 action_name=action_choice.1 %}
                                    {% with effective_perm=effective_permissions|get_item:module|get_item:action %}
                                    <div class="flex items-center justify-between p-2 border border-gray-100 rounded">
                                        <div class="flex items-center space-x-2">
                                            <input type="checkbox" 
                                                   name="custom_{{ module }}_{{ action }}" 
                                                   id="custom_{{ module }}_{{ action }}"
                                                   {% if effective_perm.source == 'custom' %}checked{% endif %}
                                                   onchange="toggleCustomPermission('{{ module }}', '{{ action }}')"
                                                   class="rounded border-gray-300 text-yellow-500 focus:ring-yellow-500 text-xs">
                                            <input type="checkbox" 
                                                   name="perm_{{ module }}_{{ action }}" 
                                                   id="perm_{{ module }}_{{ action }}"
                                                   {% if effective_perm.allowed %}checked{% endif %}
                                                   {% if effective_perm.source != 'custom' %}disabled{% endif %}
                                                   class="rounded border-gray-300 text-primary focus:ring-primary text-xs">
                                            <span class="text-xs text-gray-700">{{ action_name }}</span>
                                        </div>
                                        <div class="flex items-center space-x-1">
                                            {% if effective_perm.source == 'custom' %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                                                    <i class="fas fa-user-cog mr-1"></i>C
                                                </span>
                                            {% elif effective_perm.source == 'role' %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                                    <i class="fas fa-users-cog mr-1"></i>R
                                                </span>
                                            {% else %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                                                    <i class="fas fa-ban mr-1"></i>S
                                                </span>
                                            {% endif %}
                                            
                                            {% if effective_perm.allowed %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                                    <span>✓</span>✓
                                                </span>
                                            {% else %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                                    <span>✕</span>✗
                                                </span>
                                            {% endif %}
                                        </div>
                                    </div>
                                    {% endwith %}
                                    {% endwith %}
                                    {% endfor %}
                                </div>
                            </div>
                            {% endwith %}
                            {% endif %}
                            {% endfor %}
                        </div>
                    </div>

                    <!-- Loans Page Specific Permissions -->
                    <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                        <h3 class="text-lg font-medium text-yellow-900 mb-4">
                            <span>💵</span>Loans Page Specific Permissions
                        </h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            {% for module_choice in modules %}
                            {% if 'loans_' in module_choice.0 %}
                            {% with module=module_choice.0 module_name=module_choice.1 %}
                            <div class="bg-white border border-gray-200 rounded-lg p-4">
                                <div class="flex items-center justify-between mb-3">
                                    <h4 class="text-sm font-medium text-gray-900">
                                        <i class="fas fa-{{ module|get_module_icon }} text-yellow-600 mr-2"></i>
                                        {{ module_name }}
                                    </h4>
                                    <button type="button" onclick="toggleModule('{{ module }}')" 
                                            class="text-gray-400 hover:text-gray-600">
                                        <i id="icon-{{ module }}" class="fas fa-chevron-down"></i>
                                    </button>
                                </div>
                                
                                <div id="module-{{ module }}" class="space-y-2">
                                    {% for action_choice in actions %}
                                    {% with action=action_choice.0 action_name=action_choice.1 %}
                                    {% with effective_perm=effective_permissions|get_item:module|get_item:action %}
                                    <div class="flex items-center justify-between p-2 border border-gray-100 rounded">
                                        <div class="flex items-center space-x-2">
                                            <input type="checkbox" 
                                                   name="custom_{{ module }}_{{ action }}" 
                                                   id="custom_{{ module }}_{{ action }}"
                                                   {% if effective_perm.source == 'custom' %}checked{% endif %}
                                                   onchange="toggleCustomPermission('{{ module }}', '{{ action }}')"
                                                   class="rounded border-gray-300 text-yellow-500 focus:ring-yellow-500 text-xs">
                                            <input type="checkbox" 
                                                   name="perm_{{ module }}_{{ action }}" 
                                                   id="perm_{{ module }}_{{ action }}"
                                                   {% if effective_perm.allowed %}checked{% endif %}
                                                   {% if effective_perm.source != 'custom' %}disabled{% endif %}
                                                   class="rounded border-gray-300 text-primary focus:ring-primary text-xs">
                                            <span class="text-xs text-gray-700">{{ action_name }}</span>
                                        </div>
                                        <div class="flex items-center space-x-1">
                                            {% if effective_perm.source == 'custom' %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                                                    <i class="fas fa-user-cog mr-1"></i>C
                                                </span>
                                            {% elif effective_perm.source == 'role' %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                                    <i class="fas fa-users-cog mr-1"></i>R
                                                </span>
                                            {% else %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                                                    <i class="fas fa-ban mr-1"></i>S
                                                </span>
                                            {% endif %}
                                            
                                            {% if effective_perm.allowed %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                                    <span>✓</span>✓
                                                </span>
                                            {% else %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                                    <span>✕</span>✗
                                                </span>
                                            {% endif %}
                                        </div>
                                    </div>
                                    {% endwith %}
                                    {% endwith %}
                                    {% endfor %}
                                </div>
                            </div>
                            {% endwith %}
                            {% endif %}
                            {% endfor %}
                        </div>
                    </div>

                    <!-- Reports & Statements Page Specific Permissions -->
                    <div class="bg-purple-50 border border-purple-200 rounded-lg p-4">
                        <h3 class="text-lg font-medium text-purple-900 mb-4">
                            <span>📊</span>Reports & Statements Page Specific Permissions
                        </h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            {% for module_choice in modules %}
                            {% if 'reports_' in module_choice.0 or 'statements_' in module_choice.0 %}
                            {% with module=module_choice.0 module_name=module_choice.1 %}
                            <div class="bg-white border border-gray-200 rounded-lg p-4">
                                <div class="flex items-center justify-between mb-3">
                                    <h4 class="text-sm font-medium text-gray-900">
                                        <i class="fas fa-{{ module|get_module_icon }} text-purple-600 mr-2"></i>
                                        {{ module_name }}
                                    </h4>
                                    <button type="button" onclick="toggleModule('{{ module }}')" 
                                            class="text-gray-400 hover:text-gray-600">
                                        <i id="icon-{{ module }}" class="fas fa-chevron-down"></i>
                                    </button>
                                </div>
                                
                                <div id="module-{{ module }}" class="space-y-2">
                                    {% for action_choice in actions %}
                                    {% with action=action_choice.0 action_name=action_choice.1 %}
                                    {% with effective_perm=effective_permissions|get_item:module|get_item:action %}
                                    <div class="flex items-center justify-between p-2 border border-gray-100 rounded">
                                        <div class="flex items-center space-x-2">
                                            <input type="checkbox" 
                                                   name="custom_{{ module }}_{{ action }}" 
                                                   id="custom_{{ module }}_{{ action }}"
                                                   {% if effective_perm.source == 'custom' %}checked{% endif %}
                                                   onchange="toggleCustomPermission('{{ module }}', '{{ action }}')"
                                                   class="rounded border-gray-300 text-yellow-500 focus:ring-yellow-500 text-xs">
                                            <input type="checkbox" 
                                                   name="perm_{{ module }}_{{ action }}" 
                                                   id="perm_{{ module }}_{{ action }}"
                                                   {% if effective_perm.allowed %}checked{% endif %}
                                                   {% if effective_perm.source != 'custom' %}disabled{% endif %}
                                                   class="rounded border-gray-300 text-primary focus:ring-primary text-xs">
                                            <span class="text-xs text-gray-700">{{ action_name }}</span>
                                        </div>
                                        <div class="flex items-center space-x-1">
                                            {% if effective_perm.source == 'custom' %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                                                    <i class="fas fa-user-cog mr-1"></i>C
                                                </span>
                                            {% elif effective_perm.source == 'role' %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                                    <i class="fas fa-users-cog mr-1"></i>R
                                                </span>
                                            {% else %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                                                    <i class="fas fa-ban mr-1"></i>S
                                                </span>
                                            {% endif %}
                                            
                                            {% if effective_perm.allowed %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                                    <span>✓</span>✓
                                                </span>
                                            {% else %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                                    <span>✕</span>✗
                                                </span>
                                            {% endif %}
                                        </div>
                                    </div>
                                    {% endwith %}
                                    {% endwith %}
                                    {% endfor %}
                                </div>
                            </div>
                            {% endwith %}
                            {% endif %}
                            {% endfor %}
                        </div>
                    </div>

                    <!-- Repayments Page Specific Permissions -->
                    <div class="bg-orange-50 border border-orange-200 rounded-lg p-4">
                        <h3 class="text-lg font-medium text-orange-900 mb-4">
                            <span>💰</span>Repayments Page Specific Permissions
                        </h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            {% for module_choice in modules %}
                            {% if 'repayments_' in module_choice.0 %}
                            {% with module=module_choice.0 module_name=module_choice.1 %}
                            <div class="bg-white border border-gray-200 rounded-lg p-4">
                                <div class="flex items-center justify-between mb-3">
                                    <h4 class="text-sm font-medium text-gray-900">
                                        <i class="fas fa-{{ module|get_module_icon }} text-orange-600 mr-2"></i>
                                        {{ module_name }}
                                    </h4>
                                    <button type="button" onclick="toggleModule('{{ module }}')" 
                                            class="text-gray-400 hover:text-gray-600">
                                        <i id="icon-{{ module }}" class="fas fa-chevron-down"></i>
                                    </button>
                                </div>
                                
                                <div id="module-{{ module }}" class="space-y-2">
                                    {% for action_choice in actions %}
                                    {% with action=action_choice.0 action_name=action_choice.1 %}
                                    {% with effective_perm=effective_permissions|get_item:module|get_item:action %}
                                    <div class="flex items-center justify-between p-2 border border-gray-100 rounded">
                                        <div class="flex items-center space-x-2">
                                            <input type="checkbox" 
                                                   name="custom_{{ module }}_{{ action }}" 
                                                   id="custom_{{ module }}_{{ action }}"
                                                   {% if effective_perm.source == 'custom' %}checked{% endif %}
                                                   onchange="toggleCustomPermission('{{ module }}', '{{ action }}')"
                                                   class="rounded border-gray-300 text-yellow-500 focus:ring-yellow-500 text-xs">
                                            <input type="checkbox" 
                                                   name="perm_{{ module }}_{{ action }}" 
                                                   id="perm_{{ module }}_{{ action }}"
                                                   {% if effective_perm.allowed %}checked{% endif %}
                                                   {% if effective_perm.source != 'custom' %}disabled{% endif %}
                                                   class="rounded border-gray-300 text-primary focus:ring-primary text-xs">
                                            <span class="text-xs text-gray-700">{{ action_name }}</span>
                                        </div>
                                        <div class="flex items-center space-x-1">
                                            {% if effective_perm.source == 'custom' %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                                                    <i class="fas fa-user-cog mr-1"></i>C
                                                </span>
                                            {% elif effective_perm.source == 'role' %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                                    <i class="fas fa-users-cog mr-1"></i>R
                                                </span>
                                            {% else %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                                                    <i class="fas fa-ban mr-1"></i>S
                                                </span>
                                            {% endif %}
                                            
                                            {% if effective_perm.allowed %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                                    <span>✓</span>✓
                                                </span>
                                            {% else %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                                    <span>✕</span>✗
                                                </span>
                                            {% endif %}
                                        </div>
                                    </div>
                                    {% endwith %}
                                    {% endwith %}
                                    {% endfor %}
                                </div>
                            </div>
                            {% endwith %}
                            {% endif %}
                            {% endfor %}
                        </div>
                    </div>

                    <!-- Portfolio Page Specific Permissions -->
                    <div class="bg-indigo-50 border border-indigo-200 rounded-lg p-4">
                        <h3 class="text-lg font-medium text-indigo-900 mb-4">
                            <i class="fas fa-briefcase mr-2"></i>Portfolio Page Specific Permissions
                        </h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            {% for module_choice in modules %}
                            {% if 'portfolio_' in module_choice.0 %}
                            {% with module=module_choice.0 module_name=module_choice.1 %}
                            <div class="bg-white border border-gray-200 rounded-lg p-4">
                                <div class="flex items-center justify-between mb-3">
                                    <h4 class="text-sm font-medium text-gray-900">
                                        <i class="fas fa-{{ module|get_module_icon }} text-indigo-600 mr-2"></i>
                                        {{ module_name }}
                                    </h4>
                                    <button type="button" onclick="toggleModule('{{ module }}')" 
                                            class="text-gray-400 hover:text-gray-600">
                                        <i id="icon-{{ module }}" class="fas fa-chevron-down"></i>
                                    </button>
                                </div>
                                
                                <div id="module-{{ module }}" class="space-y-2">
                                    {% for action_choice in actions %}
                                    {% with action=action_choice.0 action_name=action_choice.1 %}
                                    {% with effective_perm=effective_permissions|get_item:module|get_item:action %}
                                    <div class="flex items-center justify-between p-2 border border-gray-100 rounded">
                                        <div class="flex items-center space-x-2">
                                            <input type="checkbox" 
                                                   name="custom_{{ module }}_{{ action }}" 
                                                   id="custom_{{ module }}_{{ action }}"
                                                   {% if effective_perm.source == 'custom' %}checked{% endif %}
                                                   onchange="toggleCustomPermission('{{ module }}', '{{ action }}')"
                                                   class="rounded border-gray-300 text-yellow-500 focus:ring-yellow-500 text-xs">
                                            <input type="checkbox" 
                                                   name="perm_{{ module }}_{{ action }}" 
                                                   id="perm_{{ module }}_{{ action }}"
                                                   {% if effective_perm.allowed %}checked{% endif %}
                                                   {% if effective_perm.source != 'custom' %}disabled{% endif %}
                                                   class="rounded border-gray-300 text-primary focus:ring-primary text-xs">
                                            <span class="text-xs text-gray-700">{{ action_name }}</span>
                                        </div>
                                        <div class="flex items-center space-x-1">
                                            {% if effective_perm.source == 'custom' %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                                                    <i class="fas fa-user-cog mr-1"></i>C
                                                </span>
                                            {% elif effective_perm.source == 'role' %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                                    <i class="fas fa-users-cog mr-1"></i>R
                                                </span>
                                            {% else %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                                                    <i class="fas fa-ban mr-1"></i>S
                                                </span>
                                            {% endif %}
                                            
                                            {% if effective_perm.allowed %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                                    <span>✓</span>✓
                                                </span>
                                            {% else %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                                    <span>✕</span>✗
                                                </span>
                                            {% endif %}
                                        </div>
                                    </div>
                                    {% endwith %}
                                    {% endwith %}
                                    {% endfor %}
                                </div>
                            </div>
                            {% endwith %}
                            {% endif %}
                            {% endfor %}
                        </div>
                    </div>

                    <!-- Documents & Receipts Page Specific Permissions -->
                    <div class="bg-teal-50 border border-teal-200 rounded-lg p-4">
                        <h3 class="text-lg font-medium text-teal-900 mb-4">
                            <span>📄</span>Documents & Receipts Page Specific Permissions
                        </h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            {% for module_choice in modules %}
                            {% if 'documents_' in module_choice.0 or 'customer_docs_' in module_choice.0 or 'receipts_' in module_choice.0 %}
                            {% with module=module_choice.0 module_name=module_choice.1 %}
                            <div class="bg-white border border-gray-200 rounded-lg p-4">
                                <div class="flex items-center justify-between mb-3">
                                    <h4 class="text-sm font-medium text-gray-900">
                                        <i class="fas fa-{{ module|get_module_icon }} text-teal-600 mr-2"></i>
                                        {{ module_name }}
                                    </h4>
                                    <button type="button" onclick="toggleModule('{{ module }}')" 
                                            class="text-gray-400 hover:text-gray-600">
                                        <i id="icon-{{ module }}" class="fas fa-chevron-down"></i>
                                    </button>
                                </div>
                                
                                <div id="module-{{ module }}" class="space-y-2">
                                    {% for action_choice in actions %}
                                    {% with action=action_choice.0 action_name=action_choice.1 %}
                                    {% with effective_perm=effective_permissions|get_item:module|get_item:action %}
                                    <div class="flex items-center justify-between p-2 border border-gray-100 rounded">
                                        <div class="flex items-center space-x-2">
                                            <input type="checkbox" 
                                                   name="custom_{{ module }}_{{ action }}" 
                                                   id="custom_{{ module }}_{{ action }}"
                                                   {% if effective_perm.source == 'custom' %}checked{% endif %}
                                                   onchange="toggleCustomPermission('{{ module }}', '{{ action }}')"
                                                   class="rounded border-gray-300 text-yellow-500 focus:ring-yellow-500 text-xs">
                                            <input type="checkbox" 
                                                   name="perm_{{ module }}_{{ action }}" 
                                                   id="perm_{{ module }}_{{ action }}"
                                                   {% if effective_perm.allowed %}checked{% endif %}
                                                   {% if effective_perm.source != 'custom' %}disabled{% endif %}
                                                   class="rounded border-gray-300 text-primary focus:ring-primary text-xs">
                                            <span class="text-xs text-gray-700">{{ action_name }}</span>
                                        </div>
                                        <div class="flex items-center space-x-1">
                                            {% if effective_perm.source == 'custom' %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                                                    <i class="fas fa-user-cog mr-1"></i>C
                                                </span>
                                            {% elif effective_perm.source == 'role' %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                                    <i class="fas fa-users-cog mr-1"></i>R
                                                </span>
                                            {% else %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                                                    <i class="fas fa-ban mr-1"></i>S
                                                </span>
                                            {% endif %}
                                            
                                            {% if effective_perm.allowed %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                                    <span>✓</span>✓
                                                </span>
                                            {% else %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                                    <span>✕</span>✗
                                                </span>
                                            {% endif %}
                                        </div>
                                    </div>
                                    {% endwith %}
                                    {% endwith %}
                                    {% endfor %}
                                </div>
                            </div>
                            {% endwith %}
                            {% endif %}
                            {% endfor %}
                        </div>
                    </div>

                    <!-- Notifications & Settings Page Specific Permissions -->
                    <div class="bg-red-50 border border-red-200 rounded-lg p-4">
                        <h3 class="text-lg font-medium text-red-900 mb-4">
                            <span>⚙️</span>Notifications & Settings Page Specific Permissions
                        </h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            {% for module_choice in modules %}
                            {% if 'notifications_' in module_choice.0 or 'settings_' in module_choice.0 %}
                            {% with module=module_choice.0 module_name=module_choice.1 %}
                            <div class="bg-white border border-gray-200 rounded-lg p-4">
                                <div class="flex items-center justify-between mb-3">
                                    <h4 class="text-sm font-medium text-gray-900">
                                        <i class="fas fa-{{ module|get_module_icon }} text-red-600 mr-2"></i>
                                        {{ module_name }}
                                    </h4>
                                    <button type="button" onclick="toggleModule('{{ module }}')" 
                                            class="text-gray-400 hover:text-gray-600">
                                        <i id="icon-{{ module }}" class="fas fa-chevron-down"></i>
                                    </button>
                                </div>
                                
                                <div id="module-{{ module }}" class="space-y-2">
                                    {% for action_choice in actions %}
                                    {% with action=action_choice.0 action_name=action_choice.1 %}
                                    {% with effective_perm=effective_permissions|get_item:module|get_item:action %}
                                    <div class="flex items-center justify-between p-2 border border-gray-100 rounded">
                                        <div class="flex items-center space-x-2">
                                            <input type="checkbox" 
                                                   name="custom_{{ module }}_{{ action }}" 
                                                   id="custom_{{ module }}_{{ action }}"
                                                   {% if effective_perm.source == 'custom' %}checked{% endif %}
                                                   onchange="toggleCustomPermission('{{ module }}', '{{ action }}')"
                                                   class="rounded border-gray-300 text-yellow-500 focus:ring-yellow-500 text-xs">
                                            <input type="checkbox" 
                                                   name="perm_{{ module }}_{{ action }}" 
                                                   id="perm_{{ module }}_{{ action }}"
                                                   {% if effective_perm.allowed %}checked{% endif %}
                                                   {% if effective_perm.source != 'custom' %}disabled{% endif %}
                                                   class="rounded border-gray-300 text-primary focus:ring-primary text-xs">
                                            <span class="text-xs text-gray-700">{{ action_name }}</span>
                                        </div>
                                        <div class="flex items-center space-x-1">
                                            {% if effective_perm.source == 'custom' %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                                                    <i class="fas fa-user-cog mr-1"></i>C
                                                </span>
                                            {% elif effective_perm.source == 'role' %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                                    <i class="fas fa-users-cog mr-1"></i>R
                                                </span>
                                            {% else %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                                                    <i class="fas fa-ban mr-1"></i>S
                                                </span>
                                            {% endif %}
                                            
                                            {% if effective_perm.allowed %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                                    <span>✓</span>✓
                                                </span>
                                            {% else %}
                                                <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                                    <span>✕</span>✗
                                                </span>
                                            {% endif %}
                                        </div>
                                    </div>
                                    {% endwith %}
                                    {% endwith %}
                                    {% endfor %}
                                </div>
                            </div>
                            {% endwith %}
                            {% endif %}
                            {% endfor %}
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Submit Buttons -->
        <div class="flex justify-end space-x-3">
            <a href="{% url 'users:admin_list' %}" 
               class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
                Cancel
            </a>
            <button type="submit" 
                    class="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary hover:bg-primary-dark focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                <span>💾</span>
                Save Permissions
            </button>
        </div>
    </form>
</div>

<!-- Copy Permissions Modal -->
<div id="copyPermissionsModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden">
    <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
        <div class="mt-3">
            <h3 class="text-lg font-medium text-gray-900 mb-4">Copy Permissions From</h3>
            <select id="copyFromUser" class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary">
                <option value="">Select a staff member...</option>
                <!-- This would be populated via AJAX or server-side -->
            </select>
            <div class="mt-4 flex justify-end space-x-3">
                <button onclick="closeCopyModal()" 
                        class="px-4 py-2 bg-gray-300 text-gray-800 text-sm font-medium rounded-md hover:bg-gray-400">
                    Cancel
                </button>
                <button onclick="copyPermissions()" 
                        class="px-4 py-2 bg-primary text-white text-sm font-medium rounded-md hover:bg-primary-dark">
                    Copy Permissions
                </button>
            </div>
        </div>
    </div>
</div>

<script>
// Module toggle functionality
function toggleModule(module) {
    const content = document.getElementById(`module-${module}`);
    const icon = document.getElementById(`icon-${module}`);
    
    if (content.style.display === 'none') {
        content.style.display = 'block';
        icon.classList.remove('fa-chevron-right');
        icon.classList.add('fa-chevron-down');
    } else {
        content.style.display = 'none';
        icon.classList.remove('fa-chevron-down');
        icon.classList.add('fa-chevron-right');
    }
}

function expandAllModules() {
    document.querySelectorAll('[id^="module-"]').forEach(module => {
        module.style.display = 'block';
    });
    document.querySelectorAll('[id^="icon-"]').forEach(icon => {
        icon.classList.remove('fa-chevron-right');
        icon.classList.add('fa-chevron-down');
    });
}

function collapseAllModules() {
    document.querySelectorAll('[id^="module-"]').forEach(module => {
        module.style.display = 'none';
    });
    document.querySelectorAll('[id^="icon-"]').forEach(icon => {
        icon.classList.remove('fa-chevron-down');
        icon.classList.add('fa-chevron-right');
    });
}

// Custom permission toggle
function toggleCustomPermission(module, action) {
    const customCheckbox = document.getElementById(`custom_${module}_${action}`);
    const permCheckbox = document.getElementById(`perm_${module}_${action}`);
    
    if (customCheckbox.checked) {
        permCheckbox.disabled = false;
        permCheckbox.parentElement.parentElement.classList.add('bg-yellow-50');
    } else {
        permCheckbox.disabled = true;
        permCheckbox.parentElement.parentElement.classList.remove('bg-yellow-50');
        // Reset to default value
        // You might want to store the default value and restore it here
    }
}

// Copy permissions functionality
function copyPermissionsModal() {
    // Load staff members via AJAX
    fetch('/users/staff-list-ajax/')
        .then(response => response.json())
        .then(data => {
            const select = document.getElementById('copyFromUser');
            select.innerHTML = '<option value="">Select a staff member...</option>';
            data.staff.forEach(staff => {
                if (staff.id !== '{{ user.id }}') {
                    select.innerHTML += `<option value="${staff.id}">${staff.name} (${staff.role})</option>`;
                }
            });
        });
    
    document.getElementById('copyPermissionsModal').classList.remove('hidden');
}

function closeCopyModal() {
    document.getElementById('copyPermissionsModal').classList.add('hidden');
}

function copyPermissions() {
    const fromUserId = document.getElementById('copyFromUser').value;
    if (!fromUserId) {
        alert('Please select a staff member to copy permissions from.');
        return;
    }
    
    if (confirm('This will replace all current permissions with those from the selected staff member. Continue?')) {
        window.location.href = `/users/copy-permissions/${fromUserId}/{{ user.id }}/`;
    }
}

// Initialize collapsed state for modules
document.addEventListener('DOMContentLoaded', function() {
    // Start with all modules collapsed except the first one
    const modules = document.querySelectorAll('[id^="module-"]');
    modules.forEach((module, index) => {
        if (index > 0) {
            module.style.display = 'none';
            const moduleId = module.id.replace('module-', '');
            const icon = document.getElementById(`icon-${moduleId}`);
            if (icon) {
                icon.classList.remove('fa-chevron-down');
                icon.classList.add('fa-chevron-right');
            }
        }
    });
    
    // Initialize custom permission states
    document.querySelectorAll('[id^="custom_"]').forEach(checkbox => {
        const parts = checkbox.id.split('_');
        const module = parts[1];
        const action = parts[2];
        toggleCustomPermission(module, action);
    });
});

// Template filter functions (implement these in Django)
function getModuleIcon(module) {
    const icons = {
        'dashboard': 'tachometer-alt',
        'users': 'users',
        'clients': 'user-friends',
        'loans': 'money-bill-wave',
        'applications': 'file-contract',
        'repayments': 'hand-holding-usd',
        'reports': 'chart-bar',
        'documents': 'file-alt',
        'settings': 'cogs',
        'notifications': 'bell',
        'audit': 'clipboard-list',
        'kyc': 'id-card',
        'payments': 'credit-card',
        'communications': 'envelope',
        'portfolio': 'briefcase',
        'receipts': 'receipt',
        'statements': 'file-invoice',
        'media': 'images',
        'backup': 'database',
        'system': 'server'
    };
    return icons[module] || 'cog';
}
</script>
{% endblock %}