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

{% block title %}Permission Matrix{% 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>
                    <h3 class="text-lg leading-6 font-medium text-gray-900">
                        <i class="fas fa-table text-primary mr-2"></i>
                        Permission Matrix
                    </h3>
                    <p class="mt-1 max-w-2xl text-sm text-gray-500">
                        Complete overview of all permissions across all roles. {{ total_permissions }} permissions for {{ total_roles }} roles.
                    </p>
                </div>
                <div class="flex space-x-2">
                    <a href="{% url 'users:role_template_configuration' %}"
                        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 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                        <span>←</span>
                        Back to Configuration
                    </a>
                    <button onclick="exportMatrix()" 
                            class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-primary hover:bg-primary-dark">
                        <span>⬇️</span>
                        Export Matrix
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Matrix Controls -->
    <div class="bg-white shadow rounded-lg">
        <div class="px-4 py-5 sm:p-6">
            <div class="flex flex-wrap items-center justify-between gap-4">
                <div class="flex items-center space-x-4">
                    <div>
                        <label for="pageFilter" class="block text-sm font-medium text-gray-700">Filter by Page</label>
                        <select id="pageFilter" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary">
                            <option value="">All Pages</option>
                            {% for page_name in pages_data.keys %}
                            <option value="{{ page_name }}">{{ page_name|title }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div>
                        <label for="categoryFilter" class="block text-sm font-medium text-gray-700">Filter by Category</label>
                        <select id="categoryFilter" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary">
                            <option value="">All Categories</option>
                            <option value="view">View/Access</option>
                            <option value="create">Create/Add</option>
                            <option value="edit">Edit/Modify</option>
                            <option value="delete">Delete/Remove</option>
                            <option value="approve">Approve/Reject</option>
                            <option value="export">Export/Download</option>
                            <option value="manage">Manage/Configure</option>
                            <option value="process">Process/Execute</option>
                        </select>
                    </div>
                    <div>
                        <label for="roleFilter" class="block text-sm font-medium text-gray-700">Filter by Role</label>
                        <select id="roleFilter" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary">
                            <option value="">All Roles</option>
                            {% for role_code, role_name in roles %}
                            <option value="{{ role_code }}">{{ role_name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                </div>
                <div class="flex items-center space-x-2">
                    <button onclick="clearFilters()" 
                            class="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                        <span>✕</span>Clear Filters
                    </button>
                    <button onclick="toggleCompactView()" 
                            class="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                        <i class="fas fa-compress mr-2"></i>Compact View
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Legend -->
    <div class="bg-white shadow rounded-lg">
        <div class="px-4 py-5 sm:p-6">
            <h4 class="text-sm font-medium text-gray-900 mb-3">Legend</h4>
            <div class="flex flex-wrap items-center gap-4 text-sm">
                <div class="flex items-center">
                    <div class="w-4 h-4 bg-green-500 rounded mr-2"></div>
                    <span>Allowed</span>
                </div>
                <div class="flex items-center">
                    <div class="w-4 h-4 bg-red-500 rounded mr-2"></div>
                    <span>Denied</span>
                </div>
                <div class="flex items-center">
                    <div class="w-4 h-4 bg-yellow-500 rounded mr-2"></div>
                    <span>Can Override</span>
                </div>
                <div class="flex items-center">
                    <div class="w-4 h-4 bg-gray-300 rounded mr-2"></div>
                    <span>Fixed (No Override)</span>
                </div>
                <div class="flex items-center">
                    <span>⚠️</span>
                    <span>Critical Permission</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Permission Matrix -->
    <div class="bg-white shadow rounded-lg overflow-hidden">
        <div class="px-4 py-5 sm:p-6">
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200" id="permissionMatrix">
                    <thead class="bg-gray-50">
                        <tr>
                            <th scope="col" class="sticky left-0 z-10 bg-gray-50 px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-r border-gray-200">
                                Permission
                            </th>
                            {% for role_code, role_name in roles %}
                            <th scope="col" class="px-3 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider min-w-24">
                                <div class="flex flex-col items-center">
                                    {% if role_code == 'admin' %}
                                        <i class="fas fa-crown text-red-500 mb-1"></i>
                                    {% elif role_code == 'team_leader' %}
                                        <span>👔</span>
                                    {% elif role_code == 'loan_officer' %}
                                        <i class="fas fa-handshake text-green-500 mb-1"></i>
                                    {% elif role_code == 'secretary' %}
                                        <i class="fas fa-user-secret text-purple-500 mb-1"></i>
                                    {% elif role_code == 'auditor' %}
                                        <span>🔍</span>
                                    {% else %}
                                        <span>👤</span>
                                    {% endif %}
                                    <span class="text-xs">{{ role_name }}</span>
                                </div>
                            </th>
                            {% endfor %}
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        {% for page_name, page_permissions in pages_data.items %}
                        <!-- Page Header Row -->
                        <tr class="bg-gray-100">
                            <td colspan="{{ roles|length|add:1 }}" class="px-6 py-3 text-sm font-medium text-gray-900">
                                <div class="flex items-center">
                                    {% if 'dashboard' in page_name %}
                                    <i class="fas fa-tachometer-alt text-blue-500 mr-2"></i>
                                    {% elif 'client' in page_name %}
                                    <span>👥</span>
                                    {% elif 'loan' in page_name %}
                                    <span>💵</span>
                                    {% elif 'repayment' in page_name or 'payment' in page_name %}
                                    <span>💳</span>
                                    {% elif 'report' in page_name %}
                                    <span>📊</span>
                                    {% else %}
                                    <span>📦</span>
                                    {% endif %}
                                    {{ page_name|title }} Page
                                </div>
                            </td>
                        </tr>
                        
                        {% for perm_data in page_permissions %}
                        <tr class="permission-row hover:bg-gray-50" 
                            data-page="{{ perm_data.permission.page_name }}" 
                            data-category="{{ perm_data.permission.category }}">
                            <td class="sticky left-0 z-10 bg-white px-6 py-4 whitespace-nowrap text-sm border-r border-gray-200">
                                <div class="flex items-center">
                                    <div class="flex-shrink-0">
                                        {% if perm_data.permission.category == 'view' %}
                                        <i class="fas fa-eye text-blue-400"></i>
                                        {% elif perm_data.permission.category == 'create' %}
                                        <span>+</span>
                                        {% elif perm_data.permission.category == 'edit' %}
                                        <span>✏️</span>
                                        {% elif perm_data.permission.category == 'delete' %}
                                        <span>🗑️</span>
                                        {% elif perm_data.permission.category == 'approve' %}
                                        <span>✓</span>
                                        {% elif perm_data.permission.category == 'export' %}
                                        <span>⬇️</span>
                                        {% else %}
                                        <span>⚙️</span>
                                        {% endif %}
                                    </div>
                                    <div class="ml-3">
                                        <div class="text-sm font-medium text-gray-900">
                                            {{ perm_data.permission.action_name }}
                                            {% if perm_data.permission.is_critical %}
                                            <span>⚠️</span>
                                            {% endif %}
                                        </div>
                                        <div class="text-xs text-gray-500">{{ perm_data.permission.description|truncatechars:50 }}</div>
                                    </div>
                                </div>
                            </td>
                            {% for role_code, role_name in roles %}
                            {% with role_perm=perm_data.roles|get_item:role_code %}
                            <td class="px-3 py-4 whitespace-nowrap text-center">
                                <div class="flex items-center justify-center">
                                    {% if role_perm.allowed %}
                                    <div class="w-6 h-6 rounded-full bg-green-500 flex items-center justify-center" 
                                         title="Allowed{% if not role_perm.can_override %} (Fixed){% endif %}">
                                        <span>✓</span>
                                    </div>
                                    {% else %}
                                    <div class="w-6 h-6 rounded-full bg-red-500 flex items-center justify-center" 
                                         title="Denied{% if not role_perm.can_override %} (Fixed){% endif %}">
                                        <span>✕</span>
                                    </div>
                                    {% endif %}
                                    {% if not role_perm.can_override %}
                                    <span>🔒</span>
                                    {% endif %}
                                </div>
                            </td>
                            {% endwith %}
                            {% endfor %}
                        </tr>
                        {% endfor %}
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Initialize filters
    setupFilters();
});

function setupFilters() {
    const pageFilter = document.getElementById('pageFilter');
    const categoryFilter = document.getElementById('categoryFilter');
    const roleFilter = document.getElementById('roleFilter');
    
    [pageFilter, categoryFilter, roleFilter].forEach(filter => {
        filter.addEventListener('change', applyFilters);
    });
}

function applyFilters() {
    const pageFilter = document.getElementById('pageFilter').value;
    const categoryFilter = document.getElementById('categoryFilter').value;
    const roleFilter = document.getElementById('roleFilter').value;
    
    const rows = document.querySelectorAll('.permission-row');
    
    rows.forEach(row => {
        let show = true;
        
        if (pageFilter && row.dataset.page !== pageFilter) {
            show = false;
        }
        
        if (categoryFilter && row.dataset.category !== categoryFilter) {
            show = false;
        }
        
        if (show) {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    });
    
    // Handle page headers
    const pageHeaders = document.querySelectorAll('tr.bg-gray-100');
    pageHeaders.forEach(header => {
        const nextRows = [];
        let nextSibling = header.nextElementSibling;
        
        while (nextSibling && !nextSibling.classList.contains('bg-gray-100')) {
            if (nextSibling.classList.contains('permission-row')) {
                nextRows.push(nextSibling);
            }
            nextSibling = nextSibling.nextElementSibling;
        }
        
        const hasVisibleRows = nextRows.some(row => row.style.display !== 'none');
        header.style.display = hasVisibleRows ? '' : 'none';
    });
}

function clearFilters() {
    document.getElementById('pageFilter').value = '';
    document.getElementById('categoryFilter').value = '';
    document.getElementById('roleFilter').value = '';
    applyFilters();
}

function toggleCompactView() {
    const table = document.getElementById('permissionMatrix');
    const button = event.target;
    
    if (table.classList.contains('compact-view')) {
        table.classList.remove('compact-view');
        button.innerHTML = '<i class="fas fa-compress mr-2"></i>Compact View';
    } else {
        table.classList.add('compact-view');
        button.innerHTML = '<i class="fas fa-expand mr-2"></i>Expanded View';
    }
}

function exportMatrix() {
    // Create CSV content
    let csvContent = "Permission,Page,Category,Description";
    
    // Add role headers
    {% for role_code, role_name in roles %}
    csvContent += ",{{ role_name }}";
    {% endfor %}
    csvContent += "\n";
    
    // Add permission data
    const rows = document.querySelectorAll('.permission-row');
    rows.forEach(row => {
        if (row.style.display !== 'none') {
            const cells = row.querySelectorAll('td');
            const permissionName = cells[0].querySelector('.text-sm.font-medium').textContent.trim();
            const description = cells[0].querySelector('.text-xs.text-gray-500').textContent.trim();
            const page = row.dataset.page;
            const category = row.dataset.category;
            
            csvContent += `"${permissionName}","${page}","${category}","${description}"`;
            
            // Add role permissions
            for (let i = 1; i < cells.length; i++) {
                const hasCheck = cells[i].querySelector('.fa-check');
                csvContent += hasCheck ? ",Yes" : ",No";
            }
            csvContent += "\n";
        }
    });
    
    // Download CSV
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', 'permission_matrix.csv');
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}
</script>

<style>
.compact-view td {
    padding: 0.25rem 0.5rem;
}

.compact-view .text-sm {
    font-size: 0.75rem;
}

.compact-view .text-xs {
    font-size: 0.625rem;
}

.sticky {
    position: sticky;
}

.z-10 {
    z-index: 10;
}

.min-w-24 {
    min-width: 6rem;
}
</style>
{% endblock %}