<x-app-layout>
    <x-module-hero
        title="Payment API Logs"
        description="View and analyze payment API interactions"
        icon="fa-history">
        <x-slot name="tabs">
            <a href="{{ route('config.payment.index') }}"
               class="module-hero-tab {{ request()->routeIs('config.payment.index') ? '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 transition">
                <i class="fas fa-tachometer-alt"></i> Dashboard
            </a>
            @can('create payment configuration')
            <a href="{{ route('config.payment.create') }}"
               class="module-hero-tab {{ request()->routeIs('config.payment.create') || request()->routeIs('config.payment.edit') ? '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 transition">
                <i class="fas fa-plus"></i> Configure
            </a>
            @endcan
            @can('test payment connection')
            <a href="{{ route('config.payment.test-interface') }}"
               class="module-hero-tab {{ request()->routeIs('config.payment.test-interface') ? '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 transition">
                <i class="fas fa-plug"></i> Test Connection
            </a>
            @endcan
            @can('view payment logs')
            <a href="{{ route('config.payment.logs') }}"
               class="module-hero-tab {{ request()->routeIs('config.payment.logs') ? '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 transition">
                <i class="fas fa-history"></i> API Logs
            </a>
            @endcan
            <a href="{{ route('config.payment.documentation') }}"
               class="module-hero-tab {{ request()->routeIs('config.payment.documentation') ? '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 transition">
                <i class="fas fa-book"></i> Documentation
            </a>
        </x-slot>
    </x-module-hero>

    <div class="p-6">
        {{-- Stats Row --}}
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                <p class="text-xs text-gray-500 font-semibold uppercase tracking-wider">Total Logs</p>
                <p class="text-2xl font-bold mt-1 text-blue-600">{{ $stats['total'] ?? 0 }}</p>
            </div>
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                <p class="text-xs text-gray-500 font-semibold uppercase tracking-wider">Successful</p>
                <p class="text-2xl font-bold mt-1 text-green-600">{{ $stats['successful'] ?? 0 }}</p>
            </div>
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                <p class="text-xs text-gray-500 font-semibold uppercase tracking-wider">Failed</p>
                <p class="text-2xl font-bold mt-1 text-red-600">{{ $stats['failed'] ?? 0 }}</p>
            </div>
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                <p class="text-xs text-gray-500 font-semibold uppercase tracking-wider">Success Rate</p>
                <p class="text-2xl font-bold mt-1 text-purple-600">{{ $stats['success_rate'] ?? 0 }}%</p>
            </div>
        </div>

        {{-- Filters --}}
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4 mb-4">
            <form method="GET" action="{{ route('config.payment.logs') }}">
                <div class="grid grid-cols-1 md:grid-cols-5 gap-4">
                    <div>
                        <label class="block text-xs font-medium text-gray-700 mb-1">Type</label>
                        <select name="type" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500">
                            <option value="">All Types</option>
                            <option value="collection" {{ request('type') === 'collection' ? 'selected' : '' }}>Collection</option>
                            <option value="disbursement" {{ request('type') === 'disbursement' ? 'selected' : '' }}>Disbursement</option>
                            <option value="status_check" {{ request('type') === 'status_check' ? 'selected' : '' }}>Status Check</option>
                            <option value="test" {{ request('type') === 'test' ? 'selected' : '' }}>Test</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-gray-700 mb-1">Status</label>
                        <select name="status" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500">
                            <option value="">All Statuses</option>
                            <option value="success" {{ request('status') === 'success' ? 'selected' : '' }}>Success</option>
                            <option value="failed" {{ request('status') === 'failed' ? 'selected' : '' }}>Failed</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-gray-700 mb-1">From Date</label>
                        <input type="date" name="date_from" value="{{ request('date_from') }}"
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500">
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-gray-700 mb-1">To Date</label>
                        <input type="date" name="date_to" value="{{ request('date_to') }}"
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500">
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-gray-700 mb-1">Search Reference</label>
                        <div class="flex">
                            <input type="text" name="search" value="{{ request('search') }}"
                                   placeholder="Transaction reference..."
                                   class="flex-1 px-3 py-2 border border-gray-300 rounded-l-lg text-sm focus:ring-2 focus:ring-green-500">
                            <button type="submit" class="px-3 py-2 bg-green-600 text-white rounded-r-lg hover:bg-green-700 transition">
                                <i class="fas fa-search"></i>
                            </button>
                        </div>
                    </div>
                </div>
                @if(request()->hasAny(['type', 'status', 'date_from', 'date_to', 'search']))
                    <div class="mt-3">
                        <a href="{{ route('config.payment.logs') }}" class="text-xs text-green-600 hover:underline">
                            <i class="fas fa-times mr-1"></i> Clear all filters
                        </a>
                    </div>
                @endif
            </form>
        </div>

        {{-- Logs Table --}}
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full table-zebra">
                    <thead>
                        <tr>
                            <th class="px-4 py-3 text-left th-col-1">ID</th>
                            <th class="px-4 py-3 text-left th-col-2">Type</th>
                            <th class="px-4 py-3 text-left th-col-3">Endpoint</th>
                            <th class="px-4 py-3 text-left th-col-4">Reference</th>
                            <th class="px-4 py-3 text-left th-col-5">Status</th>
                            <th class="px-4 py-3 text-left th-col-6">Time</th>
                            <th class="px-4 py-3 text-left th-col-7">Date</th>
                            <th class="px-4 py-3 text-center th-col-8">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($logs as $log)
                            <tr class="odd:bg-white even:bg-gray-50 hover:bg-gray-100 transition-colors border-b border-gray-100 last:border-0">
                                <td class="px-4 py-3 text-sm font-mono text-gray-500">#{{ $log->id }}</td>
                                <td class="px-4 py-3 whitespace-nowrap">
                                    <span class="px-2 py-0.5 rounded text-xs font-semibold
                                        {{ $log->type === 'collection' ? 'bg-blue-100 text-blue-800' :
                                           ($log->type === 'disbursement' ? 'bg-purple-100 text-purple-800' :
                                           ($log->type === 'test' ? 'bg-yellow-100 text-yellow-800' : 'bg-gray-100 text-gray-800')) }}">
                                        {{ $log->getTypeLabel() }}
                                    </span>
                                </td>
                                <td class="px-4 py-3 text-xs font-mono text-gray-600">{{ Str::limit($log->endpoint, 35) }}</td>
                                <td class="px-4 py-3 text-xs font-mono text-gray-600">{{ $log->transaction_reference ?? '-' }}</td>
                                <td class="px-4 py-3 whitespace-nowrap">
                                    @if($log->response_status)
                                        <span class="px-2 py-0.5 rounded text-xs font-semibold
                                            {{ $log->isSuccessful() ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800' }}">
                                            {{ $log->response_status }}
                                        </span>
                                    @else
                                        <span class="text-gray-400 text-xs">-</span>
                                    @endif
                                </td>
                                <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">{{ $log->execution_time_ms ?? '-' }}ms</td>
                                <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">{{ $log->created_at->format('M d, H:i') }}</td>
                                <td class="px-4 py-3 whitespace-nowrap text-center">
                                    <button onclick="showLogDetails({{ $log->id }})" class="btn-action-view">
                                        <i class="fas fa-eye"></i> View
                                    </button>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="8" class="px-4 py-12 text-center">
                                    <i class="fas fa-inbox text-gray-300 text-4xl mb-4"></i>
                                    <p class="text-gray-500">No API logs found</p>
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
            @if($logs->hasPages())
                <div class="p-4 border-t border-gray-200">
                    {{ $logs->appends(request()->query())->links() }}
                </div>
            @endif
        </div>
    </div>

    {{-- Log Details Modal --}}
    <div id="logModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden items-center justify-center">
        <div class="bg-white rounded-lg max-w-5xl mx-4 max-h-[80vh] overflow-hidden flex flex-col">
            <div class="flex items-center justify-between px-6 py-4 bg-gradient-to-r from-blue-600 to-blue-700 rounded-t-lg">
                <h3 class="text-base font-semibold text-white flex items-center gap-2">
                    <i class="fas fa-info-circle"></i> Log Details
                </h3>
                <button onclick="closeLogModal()" class="text-white/80 hover:text-white transition">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div id="logDetails" class="p-6 overflow-y-auto">
                <div class="text-center py-8"><i class="fas fa-spinner fa-spin text-3xl text-green-600"></i></div>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        async function showLogDetails(logId) {
            const modal = document.getElementById('logModal');
            const detailsDiv = document.getElementById('logDetails');
            modal.classList.remove('hidden');
            modal.classList.add('flex');
            detailsDiv.innerHTML = '<div class="text-center py-8"><i class="fas fa-spinner fa-spin text-3xl text-green-600"></i></div>';
            try {
                const response = await fetch(`{{ url('config/payment/logs') }}/` + logId, { headers: { 'Accept': 'application/json' } });
                const data = await response.json();
                if (data.success) {
                    const log = data.log;
                    detailsDiv.innerHTML = `
                        <div class="space-y-3">
                            <div class="grid grid-cols-2 gap-3">
                                <div><p class="text-xs text-gray-500">Type</p><p class="font-medium text-sm">${log.type_label}</p></div>
                                <div><p class="text-xs text-gray-500">Status</p><span class="px-2 py-0.5 rounded text-xs font-semibold ${log.is_successful ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}">${log.response_status || 'N/A'}</span></div>
                                <div><p class="text-xs text-gray-500">Transaction Reference</p><p class="font-mono text-xs">${log.transaction_reference || 'N/A'}</p></div>
                                <div><p class="text-xs text-gray-500">Execution Time</p><p class="font-medium text-sm">${log.execution_time_ms || 'N/A'}ms</p></div>
                            </div>
                            <div><p class="text-xs text-gray-500 mb-1">Endpoint</p><p class="font-mono text-xs bg-gray-100 p-2 rounded">${log.endpoint}</p></div>
                            ${log.request_payload ? `<div><p class="text-xs text-gray-500 mb-1">Request Payload</p><pre class="bg-blue-50 p-2 rounded text-xs overflow-x-auto">${JSON.stringify(log.request_payload, null, 2)}</pre></div>` : ''}
                            ${log.response_body ? `<div><p class="text-xs text-gray-500 mb-1">Response Body</p><pre class="bg-green-50 p-2 rounded text-xs overflow-x-auto">${JSON.stringify(log.response_body, null, 2)}</pre></div>` : ''}
                            ${log.error_message ? `<div><p class="text-xs text-gray-500 mb-1">Error</p><p class="text-red-600 bg-red-50 p-2 rounded text-sm">${log.error_message}</p></div>` : ''}
                            <div><p class="text-xs text-gray-500">Created At</p><p class="font-medium text-sm">${log.created_at}</p></div>
                        </div>`;
                } else {
                    detailsDiv.innerHTML = '<p class="text-red-600 text-sm">Failed to load log details.</p>';
                }
            } catch (error) {
                detailsDiv.innerHTML = `<p class="text-red-600 text-sm">Error: ${error.message}</p>`;
            }
        }
        function closeLogModal() {
            document.getElementById('logModal').classList.add('hidden');
            document.getElementById('logModal').classList.remove('flex');
        }
        document.getElementById('logModal').addEventListener('click', function(e) {
            if (e.target === this) closeLogModal();
        });
    </script>
    @endpush
</x-app-layout>
