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

{% block title %}Create Staff User - HAVEN GRAZURI ADVANCE{% endblock %}

{% block content %}
<div class="min-h-screen bg-gray-50">
    <div class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
        <!-- Page header -->
        <div class="mb-8">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-2xl font-semibold text-gray-900">Create Staff User</h1>
                    <p class="mt-2 text-sm text-gray-700">
                        Create a new staff member with role-based permissions and access control.
                    </p>
                </div>
                <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 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                    <span>←</span>
                    Back to Staff List
                </a>
        </div>
    </div>

        <form method="post" enctype="multipart/form-data" class="space-y-8">
            {% csrf_token %}
            
            <!-- Basic Information -->
            <div class="bg-white shadow sm:rounded-lg">
            <div class="px-4 py-5 sm:p-6">
                    <h3 class="text-lg font-medium text-gray-900 mb-4">
                            <span>👤</span>
                            Basic Information
                        </h3>
                    
                    <div class="grid grid-cols-1 gap-6 sm:grid-cols-2">
                        <div>
                                <label for="username" class="block text-sm font-medium text-gray-700">Username *</label>
                                <input type="text" name="username" id="username" required
                                   class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                            </div>

                        <div>
                            <label for="email" class="block text-sm font-medium text-gray-700">Email *</label>
                                <input type="email" name="email" id="email" required
                                   class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                            </div>

                        <div>
                            <label for="branch" class="block text-sm font-medium text-gray-700">Branch</label>
                            <select name="branch" id="branch" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                <option value="">Select branch (optional)</option>
                                {% for branch in branches %}
                                <option value="{{ branch.id }}">{{ branch.name }}</option>
                                {% endfor %}
                            </select>
                        </div>
                                <label for="phone_number" class="block text-sm font-medium text-gray-700">Phone Number *</label>
                                <input type="tel" name="phone_number" id="phone_number" required
                                   placeholder="+254XXXXXXXXX"
                                   class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                            </div>

                        <div>
                            <label for="role" class="block text-sm font-medium text-gray-700">Role *</label>
                            <select name="role" id="role" required onchange="updatePermissions()"
                                    class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                <option value="">Select Role</option>
                                {% for role_code, role_name in staff_roles %}
                                <option value="{{ role_code }}">{{ role_name }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        
                        <div>
                            <label for="first_name" class="block text-sm font-medium text-gray-700">First Name *</label>
                            <input type="text" name="first_name" id="first_name" required
                                   class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                        </div>
                        
                        <div>
                            <label for="last_name" class="block text-sm font-medium text-gray-700">Last Name *</label>
                            <input type="text" name="last_name" id="last_name" required
                                   class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                        </div>
                        
                        <div>
                            <label for="status" class="block text-sm font-medium text-gray-700">Status</label>
                            <select name="status" id="status"
                                    class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                {% for status_code, status_name in status_choices %}
                                <option value="{{ status_code }}" {% if status_code == 'active' %}selected{% endif %}>{{ status_name }}</option>
                                {% endfor %}
                            </select>
                        </div>
                    </div>
                    
                    <!-- Profile Image Section -->
                    <div class="mt-6 pt-6 border-t border-gray-200">
                        <h4 class="text-md font-medium text-gray-900 mb-4">
                            <span>📷</span>
                            Profile Image
                        </h4>
                        
                        <div class="flex items-center space-x-6">
                            <div class="shrink-0">
                                <img id="profile-preview" class="h-20 w-20 object-cover rounded-full border-2 border-gray-300" 
                                     src="/static/images/avatars/default-avatar.png" alt="Profile preview">
                            </div>
                            <div class="flex-1">
                                <label for="profile_image" class="block text-sm font-medium text-gray-700">
                                    Upload Profile Image
                                </label>
                                <div class="mt-1 flex items-center">
                                    <input type="file" name="profile_image" id="profile_image" accept="image/*"
                                           onchange="previewImage(this)"
                                           class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-primary file:text-white hover:file:bg-primary-dark">
                                </div>
                                <p class="mt-1 text-xs text-gray-500">
                                    PNG, JPG, GIF up to 5MB. Image will be resized to 300x300px.
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Security -->
            <div class="bg-white shadow sm:rounded-lg">
            <div class="px-4 py-5 sm:p-6">
                    <h3 class="text-lg font-medium text-gray-900 mb-4">
                            <span>🔒</span>
                        Security
                        </h3>
                    
                    <div class="grid grid-cols-1 gap-6 sm:grid-cols-2">
                        <div>
                                <label for="password" class="block text-sm font-medium text-gray-700">Password *</label>
                                <input type="password" name="password" id="password" required
                                   class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                            </div>

                        <div>
                                <label for="confirm_password" class="block text-sm font-medium text-gray-700">Confirm Password *</label>
                                <input type="password" name="confirm_password" id="confirm_password" required
                                   class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                        </div>
                    </div>
                </div>
            </div>

            <!-- Role Permissions -->
            <div class="bg-white shadow sm:rounded-lg">
            <div class="px-4 py-5 sm:p-6">
                    <h3 class="text-lg font-medium text-gray-900 mb-4">
                            <i class="fas fa-shield-alt text-primary mr-2"></i>
                        Role Permissions
                        </h3>
                    
                    <div class="mb-4">
                        <p class="text-sm text-gray-600">
                            Configure access permissions for this user. Default permissions are shown based on the selected role.
                        </p>
                            </div>

                    <div id="permissions-container" class="space-y-6">
                        <!-- Permissions will be loaded here via JavaScript -->
                    </div>
                </div>
            </div>

            <!-- Submit Button -->
            <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 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                    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>
                    Create Staff User
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Permission Templates -->
<script id="permission-template" type="text/template">
    <div class="border border-gray-200 rounded-lg p-4">
        <h4 class="text-md font-medium text-gray-900 mb-3">{{ module_name }}</h4>
        <div class="grid grid-cols-2 gap-4 sm:grid-cols-4 lg:grid-cols-5">
            {{ permission_checkboxes }}
        </div>
    </div>
</script>
{% endblock %}

{% block scripts %}
<script>
// Store default permissions data
const defaultPermissions = {{ default_permissions|safe }};

// Module names for display
const moduleNames = {
    'dashboard': 'Dashboard',
    'users': 'User Management',
    'clients': 'Client Management',
    'loans': 'Loan Management',
    'applications': 'Loan Applications',
    'repayments': 'Repayments',
    'reports': 'Reports & Analytics',
    'documents': 'Document Management',
    'settings': 'System Settings',
    'notifications': 'Notifications',
    'audit': 'Audit Logs',
    'kyc': 'KYC Management',
    'payments': 'Payment Management',
    'communications': 'Communications',
    'portfolio': 'Portfolio Management',
    'receipts': 'Receipt Management',
    'statements': 'Statement Generation',
    'media': 'Media Management',
    'backup': 'Backup & Restore',
    'system': 'System Administration'
};

// Action names for display
const actionNames = {
    'view': 'View',
    'create': 'Create',
    'edit': 'Edit',
    'delete': 'Delete',
    'approve': 'Approve',
    'reject': 'Reject',
    'export': 'Export',
    'import': 'Import',
    'manage': 'Manage',
    'assign': 'Assign',
    'reassign': 'Reassign',
    'suspend': 'Suspend',
    'activate': 'Activate',
    'verify': 'Verify',
    'generate': 'Generate',
    'download': 'Download',
    'upload': 'Upload',
    'share': 'Share',
    'print': 'Print'
};

function updatePermissions() {
    const roleSelect = document.getElementById('role');
    const selectedRole = roleSelect.value;
    const container = document.getElementById('permissions-container');
    
    if (!selectedRole) {
        container.innerHTML = '<p class="text-gray-500">Select a role to see permissions</p>';
        return;
    }
    
    const permissions = defaultPermissions[selectedRole];
    if (!permissions) {
        container.innerHTML = '<p class="text-red-500">No permissions found for this role</p>';
        return;
    }
    
    let html = '';
    
    for (const [module, actions] of Object.entries(permissions)) {
        html += `
            <div class="border border-gray-200 rounded-lg p-4">
                <h4 class="text-md font-medium text-gray-900 mb-3">
                    <i class="fas fa-${getModuleIcon(module)} text-primary mr-2"></i>
                    ${moduleNames[module] || module}
                </h4>
                <div class="grid grid-cols-2 gap-4 sm:grid-cols-4 lg:grid-cols-5">
        `;
        
        for (const [action, isAllowed] of Object.entries(actions)) {
            html += `
                <label class="flex items-center">
                    <input type="checkbox" 
                           name="perm_${module}_${action}" 
                           ${isAllowed ? 'checked' : ''}
                           class="rounded border-gray-300 text-primary focus:ring-primary">
                    <span class="ml-2 text-sm text-gray-700">${actionNames[action] || action}</span>
                </label>
            `;
        }
        
        html += `
                </div>
            </div>
        `;
    }
    
    container.innerHTML = html;
}

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';
}

function previewImage(input) {
    const preview = document.getElementById('profile-preview');
    
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        
        reader.onload = function(e) {
            preview.src = e.target.result;
        };
        
        reader.readAsDataURL(input.files[0]);
    }
}

// Initialize permissions on page load
document.addEventListener('DOMContentLoaded', function() {
    updatePermissions();
    
    // Add password confirmation validation
    const password = document.getElementById('password');
    const confirmPassword = document.getElementById('confirm_password');
    
    function validatePasswords() {
        if (password.value !== confirmPassword.value) {
            confirmPassword.setCustomValidity('Passwords do not match');
        } else {
            confirmPassword.setCustomValidity('');
        }
    }
    
    password.addEventListener('change', validatePasswords);
    confirmPassword.addEventListener('keyup', validatePasswords);
});
</script>
{% endblock %}