{{-- Admin Membership Renewal Configs --}}
<x-app-layout title="Renewal Period Configuration">

    <x-module-hero title="Renewal Period Configuration" description="Configure membership validity periods per category" icon="fa-rotate">
        <x-slot name="tabs">
            @can('view members')
                <a href="{{ route('admin.membership.dashboard') }}"
                   class="module-hero-tab {{ request()->routeIs('admin.membership.dashboard') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                          inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                          md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                    <i class="fas fa-tachometer-alt text-sm"></i> Dashboard
                </a>
            @endcan
            @can('view members')
                <a href="{{ route('admin.members.index') }}"
                   class="module-hero-tab {{ request()->routeIs('admin.members.index') || request()->routeIs('admin.members.show') || request()->routeIs('admin.members.create') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                          inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                          md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                    <i class="fas fa-users text-sm"></i> Members
                </a>
            @endcan
            @can('view members')
                <a href="{{ route('admin.members.applications.index') }}"
                   class="module-hero-tab {{ request()->routeIs('admin.members.applications.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                          inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                          md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                    <i class="fas fa-file-alt text-sm"></i> Applications
                </a>
            @endcan
            @can('view membership categories')
                <a href="{{ route('admin.membership-categories.index') }}"
                   class="module-hero-tab {{ request()->routeIs('admin.membership-categories.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                          inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                          md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                    <i class="fas fa-tags text-sm"></i> Categories
                </a>
            @endcan
            @can('manage renewal configs')
                <a href="{{ route('admin.renewal-configs.index') }}"
                   class="module-hero-tab {{ request()->routeIs('admin.renewal-configs.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                          inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                          md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                    <i class="fas fa-rotate text-sm"></i> Renewal Config
                </a>
            @endcan
            @can('view contributions')
                <a href="{{ route('admin.contributions.index') }}"
                   class="module-hero-tab {{ request()->routeIs('admin.contributions.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                          inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                          md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                    <i class="fas fa-hand-holding-usd text-sm"></i> Contributions
                </a>
            @endcan
            @can('view loan products')
                <a href="{{ route('admin.loan-products.index') }}"
                   class="module-hero-tab {{ request()->routeIs('admin.loan-products.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                          inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                          md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                    <i class="fas fa-box text-sm"></i> Loan Products
                </a>
            @endcan
            @can('view loan applications')
                <a href="{{ route('admin.loan-applications.index') }}"
                   class="module-hero-tab {{ request()->routeIs('admin.loan-applications.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                          inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                          md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                    <i class="fas fa-money-bill-wave text-sm"></i> Loan Applications
                </a>
            @endcan
        </x-slot>
        <x-slot name="actions">
            @can('manage renewal configs')
                <button onclick="document.getElementById('add-config-modal').classList.remove('hidden')"
                        class="inline-flex items-center gap-2 px-4 py-2 bg-[#1e293b]/10 hover:bg-[#1e293b]/20 text-[#1e293b] text-sm font-medium rounded transition">
                    <i class="fas fa-plus"></i> Add Config
                </button>
            @endcan
        </x-slot>
    </x-module-hero>

    <div class="p-6">

        {{-- Flash messages --}}
        @if(session('success'))
            <div class="mb-6 p-4 bg-green-100 border border-green-400 text-green-700 rounded-lg flex items-center gap-2">
                <i class="fas fa-check-circle"></i> {{ session('success') }}
            </div>
        @endif
        @if(session('error'))
            <div class="mb-6 p-4 bg-red-100 border border-red-400 text-red-700 rounded-lg flex items-center gap-2">
                <i class="fas fa-exclamation-circle"></i> {{ session('error') }}
            </div>
        @endif
        @if($errors->any())
            <div class="mb-6 p-4 bg-red-100 border border-red-400 text-red-700 rounded-lg">
                <ul class="list-disc list-inside space-y-1">
                    @foreach($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        {{-- Info banner --}}
        <div class="mb-6 p-4 bg-blue-50 border border-blue-200 text-blue-700 rounded-lg text-sm flex items-start gap-3">
            <i class="fas fa-info-circle mt-0.5 flex-shrink-0"></i>
            <div>
                When a member's certificate is generated, the system looks for a category-specific config first.
                If none exists, it uses the <strong>Default</strong> config. If no default exists, it falls back to <strong>12 months</strong>.
            </div>
        </div>

        {{-- Configs table --}}
        @if($configs->count() > 0)
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Category</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Period (Months)</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Effective From</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Effective Until</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Type</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Created By</th>
                            <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        @foreach($configs as $config)
                            <tr class="odd:bg-white even:bg-gray-50 hover:bg-gray-100 transition-colors">
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                                    {{ $config->membershipCategory?->name ?? '—' }}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700">
                                    <span class="font-semibold text-blue-700">{{ $config->renewal_period_months }}</span>
                                    <span class="text-gray-400 ml-1">month{{ $config->renewal_period_months !== 1 ? 's' : '' }}</span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">
                                    {{ $config->effective_from?->format('M j, Y') ?? '—' }}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">
                                    {{ $config->effective_until?->format('M j, Y') ?? 'No end date' }}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    @if($config->is_default)
                                        <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-star mr-1"></i> Default
                                        </span>
                                    @else
                                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600">
                                            Category-specific
                                        </span>
                                    @endif
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    {{ $config->creator?->name ?? '—' }}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-right text-sm">
                                    <div class="flex justify-end gap-2">
                                        <button
                                            onclick="openEditModal(
                                                {{ $config->id }},
                                                {{ $config->membership_category_id ?? 'null' }},
                                                {{ $config->renewal_period_months }},
                                                {{ $config->is_default ? 'true' : 'false' }},
                                                '{{ $config->effective_from?->format('Y-m-d') ?? '' }}',
                                                '{{ $config->effective_until?->format('Y-m-d') ?? '' }}'
                                            )"
                                            class="btn-action-edit">
                                            <i class="fas fa-edit"></i> Edit
                                        </button>
                                        <form method="POST" action="{{ route('admin.renewal-configs.destroy', $config) }}"
                                              onsubmit="return confirm('Delete this configuration?')">
                                            @csrf @method('DELETE')
                                            <button type="submit" class="btn-action-delete">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        @else
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-12 text-center">
                <i class="fas fa-rotate text-5xl text-gray-300 mb-4"></i>
                <h3 class="text-lg font-semibold text-gray-700 mb-2">No Renewal Configurations</h3>
                <p class="text-gray-500 mb-6">The system will use the default of 12 months until a configuration is added.</p>
                <button onclick="document.getElementById('add-config-modal').classList.remove('hidden')"
                        class="inline-flex items-center px-6 py-2.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition text-sm font-medium">
                    <i class="fas fa-plus mr-2"></i> Add First Configuration
                </button>
            </div>
        @endif

    </div>

    {{-- ===================== ADD MODAL ===================== --}}
    @push('modals')
    <div id="add-config-modal"
         class="hidden fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50"
         x-data="{ isDefault: false }"
         x-init="document.getElementById('add-config-modal').addEventListener('modal:open', () => { isDefault = false })">
        <div class="bg-white rounded-lg shadow-xl w-full max-w-6xl mx-auto overflow-hidden">

            {{-- Header --}}
            <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between"
                 style="background-color: var(--theme-bg-sidebar);">
                <div class="flex items-center gap-2">
                    <i class="fas fa-plus-circle text-white"></i>
                    <h3 class="font-semibold text-white">Add Renewal Configuration</h3>
                </div>
                <button type="button"
                        onclick="document.getElementById('add-config-modal').classList.add('hidden')"
                        class="text-white/70 hover:text-white transition">
                    <i class="fas fa-times"></i>
                </button>
            </div>

            {{-- Form --}}
            <form method="POST" action="{{ route('admin.renewal-configs.store') }}">
                @csrf
                <div class="p-6 space-y-5">

                    <div>
                        <h4 class="text-sm font-semibold text-gray-700 border-b pb-2 mb-4">Configuration Details</h4>
                    </div>

                    {{-- Membership Category --}}
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            Membership Category
                            <span class="text-gray-400 font-normal">(leave blank for default)</span>
                        </label>
                        <select name="membership_category_id"
                                class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500 focus:border-transparent">
                            <option value="">— Default (applies to all categories) —</option>
                            @foreach($categories as $cat)
                                <option value="{{ $cat->id }}"
                                    {{ old('membership_category_id') == $cat->id ? 'selected' : '' }}>
                                    {{ $cat->name }}
                                </option>
                            @endforeach
                        </select>
                        <x-input-error :messages="$errors->get('membership_category_id')" class="mt-1" />
                    </div>

                    {{-- Renewal Period --}}
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            Renewal Period (Months) <span class="text-red-500">*</span>
                        </label>
                        <input type="number" name="renewal_period_months" min="1" max="120"
                               value="{{ old('renewal_period_months', 12) }}"
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500 focus:border-transparent"
                               placeholder="e.g. 12">
                        <p class="mt-1 text-xs text-gray-500">Must be between 1 and 120 months.</p>
                        <x-input-error :messages="$errors->get('renewal_period_months')" class="mt-1" />
                    </div>

                    {{-- Effective dates --}}
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">
                                Effective From <span class="text-red-500">*</span>
                            </label>
                            <input type="date" name="effective_from"
                                   value="{{ old('effective_from') }}"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500 focus:border-transparent">
                            <x-input-error :messages="$errors->get('effective_from')" class="mt-1" />
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Effective Until</label>
                            <input type="date" name="effective_until"
                                   value="{{ old('effective_until') }}"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500 focus:border-transparent">
                            <p class="mt-1 text-xs text-gray-500">Leave blank for no end date.</p>
                            <x-input-error :messages="$errors->get('effective_until')" class="mt-1" />
                        </div>
                    </div>

                    {{-- Default toggle --}}
                    <div>
                        <label class="flex items-center gap-3 cursor-pointer">
                            <input type="checkbox" name="is_default" id="add_is_default" value="1"
                                   {{ old('is_default') ? 'checked' : '' }}
                                   x-model="isDefault"
                                   class="h-5 w-5 text-green-600 rounded focus:ring-green-500">
                            <span class="text-sm font-medium text-gray-700">
                                Set as default configuration
                                <span class="text-gray-400 font-normal">(used when no category-specific config exists)</span>
                            </span>
                        </label>
                    </div>

                </div>

                {{-- Footer actions --}}
                <div class="px-6 py-4 bg-gray-50 border-t border-gray-200 flex justify-end gap-3">
                    <button type="button"
                            onclick="document.getElementById('add-config-modal').classList.add('hidden')"
                            class="px-5 py-2 bg-gray-200 text-gray-700 text-sm rounded-lg hover:bg-gray-300 transition-colors">
                        Cancel
                    </button>
                    <button type="submit"
                            class="px-5 py-2 text-white text-sm rounded-lg transition-colors"
                            style="background-color: var(--theme-bg-sidebar);">
                        <i class="fas fa-save mr-2"></i> Save Configuration
                    </button>
                </div>
            </form>

        </div>
    </div>

    {{-- ===================== EDIT MODAL ===================== --}}
    <div id="edit-config-modal"
         class="hidden fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50"
         x-data="{ isDefault: false }">
        <div class="bg-white rounded-lg shadow-xl w-full max-w-6xl mx-auto overflow-hidden">

            {{-- Header --}}
            <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between"
                 style="background: linear-gradient(90deg, #1e40af 0%, #1d4ed8 100%);">
                <div class="flex items-center gap-2">
                    <i class="fas fa-edit text-white"></i>
                    <h3 class="font-semibold text-white">Edit Renewal Configuration</h3>
                </div>
                <button type="button"
                        onclick="document.getElementById('edit-config-modal').classList.add('hidden')"
                        class="text-white/70 hover:text-white transition">
                    <i class="fas fa-times"></i>
                </button>
            </div>

            {{-- Form --}}
            <form id="edit-config-form" method="POST" action="">
                @csrf @method('PUT')
                <div class="p-6 space-y-5">

                    <div>
                        <h4 class="text-sm font-semibold text-gray-700 border-b pb-2 mb-4">Configuration Details</h4>
                    </div>

                    {{-- Membership Category --}}
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            Membership Category
                            <span class="text-gray-400 font-normal">(leave blank for default)</span>
                        </label>
                        <select name="membership_category_id"
                                class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            <option value="">— Default (applies to all categories) —</option>
                            @foreach($categories as $cat)
                                <option value="{{ $cat->id }}">{{ $cat->name }}</option>
                            @endforeach
                        </select>
                        <x-input-error :messages="$errors->get('membership_category_id')" class="mt-1" />
                    </div>

                    {{-- Renewal Period --}}
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            Renewal Period (Months) <span class="text-red-500">*</span>
                        </label>
                        <input type="number" name="renewal_period_months" min="1" max="120"
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                               placeholder="e.g. 12">
                        <p class="mt-1 text-xs text-gray-500">Must be between 1 and 120 months.</p>
                        <x-input-error :messages="$errors->get('renewal_period_months')" class="mt-1" />
                    </div>

                    {{-- Effective dates --}}
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">
                                Effective From <span class="text-red-500">*</span>
                            </label>
                            <input type="date" name="effective_from"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            <x-input-error :messages="$errors->get('effective_from')" class="mt-1" />
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Effective Until</label>
                            <input type="date" name="effective_until"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            <p class="mt-1 text-xs text-gray-500">Leave blank for no end date.</p>
                            <x-input-error :messages="$errors->get('effective_until')" class="mt-1" />
                        </div>
                    </div>

                    {{-- Default toggle --}}
                    <div>
                        <label class="flex items-center gap-3 cursor-pointer">
                            <input type="checkbox" name="is_default" id="edit_is_default" value="1"
                                   x-model="isDefault"
                                   class="h-5 w-5 text-blue-600 rounded focus:ring-blue-500">
                            <span class="text-sm font-medium text-gray-700">
                                Set as default configuration
                                <span class="text-gray-400 font-normal">(used when no category-specific config exists)</span>
                            </span>
                        </label>
                    </div>

                </div>

                {{-- Footer actions --}}
                <div class="px-6 py-4 bg-gray-50 border-t border-gray-200 flex justify-end gap-3">
                    <button type="button"
                            onclick="document.getElementById('edit-config-modal').classList.add('hidden')"
                            class="px-5 py-2 bg-gray-200 text-gray-700 text-sm rounded-lg hover:bg-gray-300 transition-colors">
                        Cancel
                    </button>
                    <button type="submit"
                            class="px-5 py-2 text-white text-sm rounded-lg transition-colors"
                            style="background: linear-gradient(90deg, #1e40af 0%, #1d4ed8 100%);">
                        <i class="fas fa-save mr-2"></i> Update Configuration
                    </button>
                </div>
            </form>

        </div>
    </div>
    @endpush

    @push('scripts')
    <script>
        function openEditModal(id, categoryId, months, isDefault, effectiveFrom, effectiveUntil) {
            const modal = document.getElementById('edit-config-modal');
            const form  = document.getElementById('edit-config-form');

            // Set form action to the correct update route
            form.action = `/admin/renewal-configs/${id}`;

            // Populate fields
            form.querySelector('[name="membership_category_id"]').value = categoryId ?? '';
            form.querySelector('[name="renewal_period_months"]').value  = months;
            form.querySelector('[name="effective_from"]').value         = effectiveFrom ?? '';
            form.querySelector('[name="effective_until"]').value        = effectiveUntil ?? '';

            // Sync the Alpine x-model for the checkbox
            const checkbox = form.querySelector('[name="is_default"]');
            checkbox.checked = isDefault;

            // Update Alpine's reactive state so the checkbox renders correctly
            if (modal._x_dataStack) {
                modal._x_dataStack[0].isDefault = isDefault;
            }

            modal.classList.remove('hidden');
        }
    </script>
    @endpush

</x-app-layout>