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


{% block title %}Settings - HAVEN GRAZURI ADVANCE{% endblock %}

{% block content %}
<div class="min-h-screen">
    {% if not is_admin_user %}
    <script>
        // Disable all form inputs for non-admin users
        document.addEventListener('DOMContentLoaded', function() {
            const inputs = document.querySelectorAll('input, select, textarea, button[type="submit"]');
            inputs.forEach(input => {
                if (input.type !== 'hidden') {
                    input.disabled = true;
                    input.classList.add('bg-gray-100', 'cursor-not-allowed');
                }
            });
        });
    </script>
    {% endif %}
    <!-- Page header -->
    <div class="mb-8">
        <h1 class="text-2xl font-semibold text-gray-900">Settings</h1>
        {% if is_admin_user %}
        <p class="mt-2 text-sm text-gray-700">
            Manage system settings and preferences. Changes are saved automatically.
        </p>
        {% else %}
        <p class="mt-2 text-sm text-gray-700">
            View system settings and preferences. <span class="text-orange-600 font-medium">Read-only mode - Admin access required to modify settings.</span>
        </p>
        {% endif %}
    </div>

    <!-- Settings sections -->
    <div class="grid grid-cols-1 gap-8">
        <!-- Loan Products Settings -->
        <div class="bg-white shadow sm:rounded-lg hover:shadow-md transition-shadow duration-200">
            <div class="px-4 py-5 sm:p-6">
                <h3 class="text-base font-semibold leading-6 text-gray-900">
                    <span>💵</span>
                    Loan Products
                </h3>
                
                <!-- Biashara Loan Settings -->
                <div class="mt-6 border-t border-gray-200 pt-6">
                    <h4 class="text-lg font-medium text-gray-900 mb-4">Biashara Loan</h4>
                    <p class="text-sm text-gray-500 mb-4">Business loan — weekly repayment, flat rate on principal. KES 2,000–200,000.</p>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div class="space-y-4">
                            <div class="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50">
                                <div class="flex-1">
                                    <label class="block text-sm font-medium text-gray-900">Interest Rate (%)</label>
                                    <p class="text-sm text-gray-500">Flat rate on principal (default 15%)</p>
                                </div>
                                <div class="ml-4">
                                    <input type="number" step="0.01" min="0" max="100"
                                           value="{{ settings.loan|get_setting:'biashara_interest_rate' }}"
                                           onchange="updateSetting('biashara_interest_rate', this.value, this)"
                                           class="block w-32 rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                </div>
                            </div>
                            <div class="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50">
                                <div class="flex-1">
                                    <label class="block text-sm font-medium text-gray-900">Processing Fee (%)</label>
                                    <p class="text-sm text-gray-500">One-time processing fee on principal</p>
                                </div>
                                <div class="ml-4">
                                    <input type="number" step="0.01" min="0" max="100"
                                           value="{{ settings.loan|get_setting:'biashara_processing_fee' }}"
                                           onchange="updateSetting('biashara_processing_fee', this.value, this)"
                                           class="block w-32 rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                </div>
                            </div>
                            <div class="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50">
                                <div class="flex-1">
                                    <label class="block text-sm font-medium text-gray-900">Late Payment Penalty (%)</label>
                                    <p class="text-sm text-gray-500">Penalty rate for late payments</p>
                                </div>
                                <div class="ml-4">
                                    <input type="number" step="0.01" min="0" max="100"
                                           value="{{ settings.loan|get_setting:'biashara_late_payment_penalty' }}"
                                           onchange="updateSetting('biashara_late_payment_penalty', this.value, this)"
                                           class="block w-32 rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                </div>
                            </div>
                        </div>
                        <div class="space-y-4">
                            <div class="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50">
                                <div class="flex-1">
                                    <label class="block text-sm font-medium text-gray-900">Minimum Amount (KES)</label>
                                    <p class="text-sm text-gray-500">Minimum loan amount allowed</p>
                                </div>
                                <div class="ml-4">
                                    <input type="number" step="1000" min="0"
                                           value="{{ settings.loan|get_setting:'biashara_min_amount' }}"
                                           onchange="updateSetting('biashara_min_amount', this.value, this)"
                                           class="block w-32 rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                </div>
                            </div>
                            <div class="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50">
                                <div class="flex-1">
                                    <label class="block text-sm font-medium text-gray-900">Maximum Amount (KES)</label>
                                    <p class="text-sm text-gray-500">Maximum loan amount allowed</p>
                                </div>
                                <div class="ml-4">
                                    <input type="number" step="1000" min="0"
                                           value="{{ settings.loan|get_setting:'biashara_max_amount' }}"
                                           onchange="updateSetting('biashara_max_amount', this.value, this)"
                                           class="block w-32 rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Log Book Loan Settings -->
                <div class="mt-6 border-t border-gray-200 pt-6">
                    <h4 class="text-lg font-medium text-gray-900 mb-4">Log Book Loan</h4>
                    <p class="text-sm text-gray-500 mb-4">Logbook secured loan — total fees 17% on principal. KES 1,000–1,000,000.</p>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div class="space-y-4">
                            <div class="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50">
                                <div class="flex-1">
                                    <label class="block text-sm font-medium text-gray-900">Total Fee Rate (%)</label>
                                    <p class="text-sm text-gray-500">Combined fees on principal (default 17%: 5% initiation + 2% collection + 1% credit life + 3.5% services + 5.5% admin)</p>
                                </div>
                                <div class="ml-4">
                                    <input type="number" step="0.01" min="0" max="100"
                                           value="{{ settings.loan|get_setting:'logbook_interest_rate' }}"
                                           onchange="updateSetting('logbook_interest_rate', this.value, this)"
                                           class="block w-32 rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                </div>
                            </div>
                            <div class="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50">
                                <div class="flex-1">
                                    <label class="block text-sm font-medium text-gray-900">Initiation Fee (%)</label>
                                    <p class="text-sm text-gray-500">One-time initiation fee on principal (default 5%)</p>
                                </div>
                                <div class="ml-4">
                                    <input type="number" step="0.01" min="0" max="100"
                                           value="{{ settings.loan|get_setting:'logbook_processing_fee' }}"
                                           onchange="updateSetting('logbook_processing_fee', this.value, this)"
                                           class="block w-32 rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                </div>
                            </div>
                            <div class="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50">
                                <div class="flex-1">
                                    <label class="block text-sm font-medium text-gray-900">Late Payment Penalty (%)</label>
                                    <p class="text-sm text-gray-500">Penalty rate for late payments</p>
                                </div>
                                <div class="ml-4">
                                    <input type="number" step="0.01" min="0" max="100"
                                           value="{{ settings.loan|get_setting:'logbook_late_payment_penalty' }}"
                                           onchange="updateSetting('logbook_late_payment_penalty', this.value, this)"
                                           class="block w-32 rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                </div>
                            </div>
                        </div>
                        <div class="space-y-4">
                            <div class="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50">
                                <div class="flex-1">
                                    <label class="block text-sm font-medium text-gray-900">Minimum Amount (KES)</label>
                                    <p class="text-sm text-gray-500">Minimum loan amount allowed</p>
                                </div>
                                <div class="ml-4">
                                    <input type="number" step="1000" min="0"
                                           value="{{ settings.loan|get_setting:'logbook_min_amount' }}"
                                           onchange="updateSetting('logbook_min_amount', this.value, this)"
                                           class="block w-32 rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                </div>
                            </div>
                            <div class="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50">
                                <div class="flex-1">
                                    <label class="block text-sm font-medium text-gray-900">Maximum Amount (KES)</label>
                                    <p class="text-sm text-gray-500">Maximum loan amount allowed</p>
                                </div>
                                <div class="ml-4">
                                    <input type="number" step="1000" min="0"
                                           value="{{ settings.loan|get_setting:'logbook_max_amount' }}"
                                           onchange="updateSetting('logbook_max_amount', this.value, this)"
                                           class="block w-32 rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- General Loan Settings -->
                <div class="mt-6 border-t border-gray-200 pt-6">
                    <h4 class="text-lg font-medium text-gray-900 mb-4">General Loan Settings</h4>
                    <div class="space-y-4">
                        <div class="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50">
                            <div class="flex-1">
                                <label class="block text-sm font-medium text-gray-900">Late Payment Penalty (%)</label>
                                <p class="text-sm text-gray-500">Monthly penalty rate for late payments</p>
                            </div>
                            <div class="ml-4">
                                <input type="number" step="0.01" min="0" max="100"
                                       value="{{ settings.loan|get_setting:'late_payment_penalty' }}"
                                       onchange="updateSetting('late_payment_penalty', this.value, this)"
                                       class="block w-32 rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                            </div>
                        </div>
                        <div class="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50">
                            <div class="flex-1">
                                <label class="block text-sm font-medium text-gray-900">Auto-Approval Score</label>
                                <p class="text-sm text-gray-500">Minimum credit score for auto-approval</p>
                            </div>
                            <div class="ml-4">
                                <input type="number" step="1" min="0" max="100"
                                       value="{{ settings.loan|get_setting:'auto_approval_min_score' }}"
                                       onchange="updateSetting('auto_approval_min_score', this.value, this)"
                                       class="block w-32 rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Reports & Statements Settings -->
        <div class="bg-white shadow sm:rounded-lg hover:shadow-md transition-shadow duration-200">
            <div class="px-4 py-5 sm:p-6">
                <h3 class="text-base font-semibold leading-6 text-gray-900">
                    <span>📊</span>
                    Reports & Statements
                </h3>
                <p class="mt-2 text-sm text-gray-600">Configure reporting settings and system preferences</p>
                
                <div class="mt-6 space-y-6">
                    <!-- Customer Requests Management -->
                    <div class="border-t border-gray-200 pt-6">
                        <div class="flex items-center justify-between mb-4">
                            <h4 class="text-lg font-medium text-gray-900">Customer Requests</h4>
                        </div>
                        <p class="text-sm text-gray-500 mb-4">Manage customer service requests and inquiries</p>
                        
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div class="bg-gray-50 p-4 rounded-lg">
                                <h5 class="font-medium text-gray-900 mb-2">Quick Actions</h5>
                                <div class="space-y-2">
                                    <a href="{% url 'reports:customer_requests_list' %}" 
                                       class="block text-sm text-primary hover:text-primary-dark">
                                        <span>📋</span> Manage Requests
                                    </a>
                                    <a href="{% url 'reports:create_customer_request' %}" 
                                       class="block text-sm text-primary hover:text-primary-dark">
                                        <span>+</span> Create New Request
                                    </a>
                                    <a href="{% url 'reports:customer_requests_report' %}" 
                                       class="block text-sm text-primary hover:text-primary-dark">
                                        <span>📊</span> View Request Reports
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Report Generation Settings -->
                    <div class="border-t border-gray-200 pt-6">
                        <h4 class="text-lg font-medium text-gray-900 mb-4">Report Generation</h4>
                        <div class="space-y-4">
                            <div class="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50">
                                <div class="flex-1">
                                    <label class="block text-sm font-medium text-gray-900">Auto-refresh Dashboard (minutes)</label>
                                    <p class="text-sm text-gray-500">How often to refresh the reports dashboard automatically</p>
                                </div>
                                <div class="ml-4">
                                    <input type="number" step="1" min="1" max="60"
                                           value="5"
                                           onchange="updateSetting('dashboard_refresh_interval', this.value, this)"
                                           class="block w-32 rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                </div>
                            </div>
                            <div class="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50">
                                <div class="flex-1">
                                    <label class="block text-sm font-medium text-gray-900">Default Report Period (days)</label>
                                    <p class="text-sm text-gray-500">Default time period for generating reports</p>
                                </div>
                                <div class="ml-4">
                                    <input type="number" step="1" min="1" max="365"
                                           value="30"
                                           onchange="updateSetting('default_report_period', this.value, this)"
                                           class="block w-32 rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                </div>
                            </div>
                            <div class="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50">
                                <div class="flex-1">
                                    <label class="block text-sm font-medium text-gray-900">Enable Email Reports</label>
                                    <p class="text-sm text-gray-500">Send daily/weekly reports via email</p>
                                </div>
                                <div class="ml-4">
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" class="sr-only peer" 
                                               onchange="updateSetting('enable_email_reports', this.checked, this)">
                                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary/25 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Analytics Settings -->
                    <div class="border-t border-gray-200 pt-6">
                        <h4 class="text-lg font-medium text-gray-900 mb-4">Analytics & Insights</h4>
                        <div class="space-y-4">
                            <div class="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50">
                                <div class="flex-1">
                                    <label class="block text-sm font-medium text-gray-900">Track Customer Behavior</label>
                                    <p class="text-sm text-gray-500">Enable detailed customer interaction tracking</p>
                                </div>
                                <div class="ml-4">
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" class="sr-only peer" checked
                                               onchange="updateSetting('track_customer_behavior', this.checked, this)">
                                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary/25 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                                    </label>
                                </div>
                            </div>
                            <div class="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50">
                                <div class="flex-1">
                                    <label class="block text-sm font-medium text-gray-900">Advanced Analytics</label>
                                    <p class="text-sm text-gray-500">Enable predictive analytics and ML insights</p>
                                </div>
                                <div class="ml-4">
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" class="sr-only peer"
                                               onchange="updateSetting('enable_advanced_analytics', this.checked, this)">
                                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary/25 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Other Settings Sections -->
        {% for category, category_name in categories %}
        {% if category != 'loan' %}
        <div class="bg-white shadow sm:rounded-lg hover:shadow-md transition-shadow duration-200">
            <div class="px-4 py-5 sm:p-6">
                <h3 class="text-base font-semibold leading-6 text-gray-900">
                    <span>⚙️</span>
                    {{ category_name }}
                </h3>
                <div class="mt-6 space-y-6">
                    {% for setting in settings|get_item:category %}
                    <div class="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50 transition-colors duration-150">
                        <div class="flex-1">
                            <label class="block text-sm font-medium text-gray-900">{{ setting.key }}</label>
                            <p class="text-sm text-gray-500">{{ setting.description }}</p>
                        </div>
                        <div class="ml-4 flex items-center space-x-2">
                            {% if setting.is_public or user.is_staff %}
                            <div class="relative">
                                <input type="text" 
                                       id="setting-{{ setting.key }}"
                                       value="{{ setting.value }}"
                                       data-original-value="{{ setting.value }}"
                                       onchange="updateSetting('{{ setting.key }}', this.value, this)"
                                       onblur="validateSetting('{{ setting.key }}', this)"
                                       class="block w-48 rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm transition-all duration-200">
                                <div class="absolute inset-y-0 right-0 flex items-center pr-3 hidden" id="loading-{{ setting.key }}">
                                    <span>⟳</span>
                                </div>
                            </div>
                            <button onclick="resetSetting('{{ setting.key }}')" 
                                    class="text-gray-400 hover:text-gray-600 transition-colors duration-150"
                                    title="Reset to original value">
                                <span>↶</span>
                            </button>
                            {% else %}
                            <span class="text-gray-500">Restricted</span>
                            {% endif %}
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
        {% endif %}
        {% endfor %}
    </div>
</div>

{% if is_admin_user %}
<!-- SasaPay & SMS Integration Section -->
<div class="bg-white overflow-hidden shadow rounded-lg mt-8">
    <div class="px-4 py-5 sm:p-6">
        <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4">
            <span>💳</span>
            SasaPay &amp; SMS Integration
        </h3>
        <p class="text-sm text-gray-600 mb-4">
            Manage SasaPay payment gateway and Africa's Talking SMS notifications.
        </p>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <a href="{% url 'payments:sasapay_dashboard' %}"
               style="display:inline-flex;align-items:center;padding:8px 16px;border:none;border-radius:6px;box-shadow:0 2px 4px rgba(0,0,0,0.1);font-size:14px;font-weight:600;color:white;background:linear-gradient(135deg,#11998e 0%,#38ef7d 100%);text-decoration:none;cursor:pointer;">
                <span>💳</span>&nbsp; SasaPay Dashboard
            </a>
            <a href="{% url 'payments:sms_logs' %}"
               style="display:inline-flex;align-items:center;padding:8px 16px;border:none;border-radius:6px;box-shadow:0 2px 4px rgba(0,0,0,0.1);font-size:14px;font-weight:600;color:white;background:linear-gradient(135deg,#56ab2f 0%,#a8e063 100%);text-decoration:none;cursor:pointer;">
                <span>📱</span>&nbsp; SMS Logs
            </a>
            <a href="{% url 'payments:sasapay_unknown_payments' %}"
               style="display:inline-flex;align-items:center;padding:8px 16px;border:none;border-radius:6px;box-shadow:0 2px 4px rgba(0,0,0,0.1);font-size:14px;font-weight:600;color:white;background:linear-gradient(135deg,#f7971e 0%,#ffd200 100%);text-decoration:none;cursor:pointer;">
                <span>⚠️</span>&nbsp; Unknown Payments
            </a>
            <a href="{% url 'payments:dashboard' %}"
               style="display:inline-flex;align-items:center;padding:8px 16px;border:none;border-radius:6px;box-shadow:0 2px 4px rgba(0,0,0,0.1);font-size:14px;font-weight:600;color:white;background:linear-gradient(135deg,#0A3D62 0%,#3C9EBD 100%);text-decoration:none;cursor:pointer;">
                <span>📱</span>&nbsp; M-Pesa Dashboard
            </a>
        </div>
        <div class="mt-4 p-3 bg-gray-50 rounded-lg">
            <p class="text-xs text-gray-500 font-medium mb-1">Callback URLs (register with SasaPay):</p>
            <p class="text-xs text-gray-700">IPN: <code>https://uzuriapps.xyz/payments/sasapay/ipn/</code></p>
            <p class="text-xs text-gray-700">STK: <code>https://uzuriapps.xyz/payments/sasapay/stk-callback/</code></p>
            <p class="text-xs text-gray-700">B2C: <code>https://uzuriapps.xyz/payments/sasapay/disbursement-callback/</code></p>
        </div>
    </div>
</div>

<!-- System Backup Section -->
<div class="bg-white overflow-hidden shadow rounded-lg mt-8">
    <div class="px-4 py-5 sm:p-6">
        <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4">
            <span>💾</span>
            System Backup
        </h3>
        <p class="text-sm text-gray-600 mb-4">
            Create a complete backup of your system including database, media files, and configuration.
        </p>
        <a href="{% url 'utils:backup_system' %}" style="display: inline-flex; align-items: center; padding: 8px 16px; border: none; border-radius: 6px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); font-size: 14px; font-weight: 600; color: white; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); text-decoration: none; cursor: pointer;">
            <span>⬇️</span>
            Create System Backup
        </a>
    </div>
</div>
{% endif %}

{% if is_admin_user and default_role_permissions %}
<!-- Default Access Levels by Role -->
<div class="bg-white overflow-hidden shadow rounded-lg mt-8">
    <div class="px-4 py-5 sm:p-6">
        <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4">
            <span>🛡️</span>
            Default Access Levels by Role
        </h3>
        <p class="text-sm text-gray-600 mb-6">
            Configure default permissions that will be automatically assigned to new users based on their role. These can be overridden on a per-user basis.
        </p>
        
        <div class="space-y-6">
            {% for role in roles %}
            <div class="border border-gray-200 rounded-lg p-4">
                <h4 class="text-md font-semibold text-gray-900 mb-4 capitalize flex items-center">
                    <span>🏷️</span>
                    {{ role|replace }}
                </h4>
                
                {% with role_perms=default_role_permissions|get_item:role %}
                    {% if role_perms %}
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                        {% for module, actions in role_perms.items %}
                        <div class="border border-gray-100 rounded-lg p-3 bg-gray-50">
                            <h5 class="font-medium text-sm text-gray-800 mb-3 capitalize flex items-center">
                                <span>📦</span>
                                {{ module|replace }}
                            </h5>
                            <div class="space-y-2">
                                {% for action_data in actions %}
                                {% comment %}Convert module name to code for API call{% endcomment %}
                                {% with module_code=module|lower|cut:" "|cut:"&"|cut:"-" %}
                                <div class="flex items-center justify-between bg-white p-2 rounded hover:bg-gray-50">
                                    <label class="text-sm text-gray-700 flex-1 cursor-pointer" title="{{ action_data.description }}">
                                        {{ action_data.action_name|default:action_data.action|replace }}
                                    </label>
                                    <input type="checkbox" 
                                           {% if action_data.is_allowed %}checked{% endif %}
                                           onchange="updateDefaultPermission('{{ role }}', '{{ module_code }}', '{{ action_data.action }}', this.checked)"
                                           class="h-4 w-4 text-primary focus:ring-primary border-gray-300 rounded cursor-pointer">
                                </div>
                                {% endwith %}
                                {% endfor %}
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                    {% else %}
                    <p class="text-sm text-gray-500 italic">No default permissions configured for this role yet.</p>
                    {% endif %}
                {% endwith %}
            </div>
            {% endfor %}
        </div>
    </div>
</div>
{% endif %}
{% endblock %}

{% block extra_js %}
<script>
    function updateSetting(key, value, input) {
        const loadingIcon = document.getElementById(`loading-${key}`);
        if (loadingIcon) loadingIcon.classList.remove('hidden');
        
        fetch("{% url 'utils:update_setting' %}", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{ csrf_token }}'
            },
            body: JSON.stringify({ key, value })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast('success', `Setting ${key} updated successfully`);
                if (input) input.dataset.originalValue = value;
            } else {
                showToast('error', data.error || 'Failed to update setting');
                if (input) input.value = input.dataset.originalValue;
            }
        })
        .catch(error => {
            showToast('error', 'An error occurred while updating the setting');
            if (input) input.value = input.dataset.originalValue;
        })
        .finally(() => {
            if (loadingIcon) loadingIcon.classList.add('hidden');
        });
    }

    function resetSetting(key) {
        const input = document.getElementById(`setting-${key}`);
        if (input && input.dataset.originalValue) {
            input.value = input.dataset.originalValue;
            updateSetting(key, input.dataset.originalValue, input);
        }
    }

    function validateSetting(key, input) {
        if (input.value !== input.dataset.originalValue) {
            updateSetting(key, input.value, input);
        }
    }

    function showToast(type, message) {
        const toast = document.createElement('div');
        toast.className = `fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg z-50 ${
            type === 'success' ? 'bg-green-600 text-white' : 'bg-red-600 text-white'
        }`;
        toast.innerHTML = message;
        document.body.appendChild(toast);
        setTimeout(() => toast.remove(), 3000);
    }
    
    // Function to update default role permissions
    function updateDefaultPermission(role, module, action, isAllowed) {
        fetch('{% url "utils:update_default_permission" %}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: JSON.stringify({
                role: role,
                module: module,
                action: action,
                is_allowed: isAllowed
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast('success', 'Default permission updated successfully');
            } else {
                showToast('error', data.error || 'Failed to update permission');
            }
        })
        .catch(error => {
            showToast('error', 'Error updating permission');
        });
    }
    
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
</script>
{% endblock %}