@extends('admin.layouts.app')

@section('title', admin_trans('delivery_report'))
@section('page-title', admin_trans('delivery_report') . ' - ' . Str::limit($notification->title, 30))

@section('content')

<div class="space-y-6">
    
    <!-- Header -->
    <div class="flex items-center justify-between">
        <x-button 
            variant="outline" 
            icon="arrow-left"
            href="{{ route('admin.notifications.show', $notification) }}"
        >
            {{ admin_trans('back_to_notification') }}
        </x-button>

        <div class="flex items-center gap-3">
            <x-button variant="outline" icon="download" onclick="exportReport()">
                {{ admin_trans('export_report') }}
            </x-button>
        </div>
    </div>

    <!-- Notification Summary -->
    <div class="card">
        <div class="flex items-center gap-4">
            @php
                $typeColors = [
                    'system' => 'info',
                    'promotional' => 'warning', 
                    'offer' => 'success',
                    'store' => 'primary',
                    'brand' => 'secondary',
                    'user' => 'purple'
                ];
                $statusColors = [
                    'pending' => 'warning',
                    'sent' => 'success',
                    'failed' => 'danger'
                ];
            @endphp
            <div class="w-12 h-12 rounded-xl flex items-center justify-center gradient-{{ $typeColors[$notification->type] ?? 'primary' }}">
                <i data-lucide="bell" class="w-6 h-6 text-white"></i>
            </div>
            <div class="flex-1">
                <h2 class="text-lg font-bold text-primary">{{ $notification->title }}</h2>
                <div class="flex items-center gap-2 mt-1">
                    <x-badge variant="{{ $typeColors[$notification->type] ?? 'info' }}">
                        {{ admin_trans($notification->type) }}
                    </x-badge>
                    <x-badge variant="{{ $statusColors[$notification->status] ?? 'info' }}">
                        {{ admin_trans($notification->status) }}
                    </x-badge>
                    <span class="text-xs text-tertiary">{{ $notification->created_at->format('M d, Y H:i') }}</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Delivery Stats Summary -->
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        @php
            $totalDeliveries = $deliveries->total();
            $sentCount = $deliveries->where('status', 'sent')->count() + $deliveries->where('status', 'read')->count();
            $readCount = $deliveries->where('status', 'read')->count();
            $failedCount = $deliveries->where('status', 'failed')->count();
            $pendingCount = $deliveries->where('status', 'pending')->count();
        @endphp
        
        <x-stat-card 
            :title="admin_trans('total_deliveries')"
            :value="number_format($totalDeliveries)"
            icon="send"
            gradient="primary"
        />
        
        <x-stat-card 
            :title="admin_trans('successful')"
            :value="number_format($sentCount)"
            icon="check-circle"
            gradient="success"
        />
        
        <x-stat-card 
            :title="admin_trans('read')"
            :value="number_format($readCount)"
            icon="eye"
            gradient="secondary"
        />
        
        <x-stat-card 
            :title="admin_trans('failed')"
            :value="number_format($failedCount)"
            icon="x-circle"
            gradient="danger"
        />
    </div>

    <!-- Delivery Details Table -->
    <div class="card">
        <div class="flex items-center justify-between mb-6">
            <h3 class="text-lg font-bold text-primary">{{ admin_trans('delivery_details') }}</h3>
            
            <!-- Filters -->
            <div class="flex items-center gap-2">
                <form method="GET" class="flex items-center gap-2">
                    <x-select name="status" onchange="this.form.submit()" class="text-sm">
                        <option value="">{{ admin_trans('all_statuses') }}</option>
                        <option value="pending" {{ request('status') === 'pending' ? 'selected' : '' }}>
                            {{ admin_trans('pending') }}
                        </option>
                        <option value="sent" {{ request('status') === 'sent' ? 'selected' : '' }}>
                            {{ admin_trans('sent') }}
                        </option>
                        <option value="read" {{ request('status') === 'read' ? 'selected' : '' }}>
                            {{ admin_trans('read') }}
                        </option>
                        <option value="failed" {{ request('status') === 'failed' ? 'selected' : '' }}>
                            {{ admin_trans('failed') }}
                        </option>
                    </x-select>

                    <x-select name="channel" onchange="this.form.submit()" class="text-sm">
                        <option value="">{{ admin_trans('all_channels') }}</option>
                        @foreach($notification->channels as $channel)
                            <option value="{{ $channel }}" {{ request('channel') === $channel ? 'selected' : '' }}>
                                {{ admin_trans($channel) }}
                            </option>
                        @endforeach
                    </x-select>
                </form>
            </div>
        </div>

        @if ($deliveries->isEmpty())
            <x-empty-state 
                icon="inbox"
                :title="admin_trans('no_deliveries_found')"
                :description="admin_trans('no_deliveries_match_filters')"
            />
        @else
            <!-- Deliveries Table -->
            <x-enhanced-table 
                :headers="[
                    'user' => [
                        'text' => admin_trans('user'),
                        'align' => 'auto',
                        'width' => '250px'
                    ],
                    'channel' => [
                        'text' => admin_trans('channel'),
                        'align' => 'center',
                        'width' => '100px'
                    ],
                    'status' => [
                        'text' => admin_trans('status'),
                        'align' => 'center',
                        'width' => '100px'
                    ],
                    'delivered_at' => [
                        'text' => admin_trans('delivered_at'),
                        'align' => 'center',
                        'width' => '150px'
                    ],
                    'read_at' => [
                        'text' => admin_trans('read_at'),
                        'align' => 'center',
                        'width' => '150px'
                    ],
                    'device_info' => [
                        'text' => admin_trans('device'),
                        'align' => 'center',
                        'width' => '120px'
                    ]
                ]"
                :responsive="true"
            >
                @foreach($deliveries as $delivery)
                <tr class="delivery-row hover:bg-primary-light transition-colors">
                    
                    <!-- User Info -->
                    <x-table-cell type="text">
                        <div class="flex items-center gap-3">
                            <div class="w-10 h-10 rounded-full bg-primary text-white text-sm font-bold flex items-center justify-center">
                                {{ substr($delivery->user->name, 0, 1) }}
                            </div>
                            <div>
                                <div class="text-sm font-medium text-primary">{{ $delivery->user->name }}</div>
                                <div class="text-xs text-tertiary">{{ $delivery->user->email }}</div>
                                @if($delivery->user->phone)
                                    <div class="text-xs text-tertiary">{{ $delivery->user->phone }}</div>
                                @endif
                            </div>
                        </div>
                    </x-table-cell>

                    <!-- Channel -->
                    <x-table-cell type="center">
                        @php
                            $channelIcons = [
                                'database' => 'database',
                                'push' => 'smartphone',
                                'email' => 'mail'
                            ];
                            $channelColors = [
                                'database' => 'info',
                                'push' => 'warning',
                                'email' => 'secondary'
                            ];
                        @endphp
                        <div class="flex items-center justify-center">
                            <x-badge variant="{{ $channelColors[$delivery->channel] ?? 'info' }}" 
                                     :icon="$channelIcons[$delivery->channel] ?? 'bell'">
                                {{ admin_trans($delivery->channel) }}
                            </x-badge>
                        </div>
                    </x-table-cell>

                    <!-- Status -->
                    <x-table-cell type="center">
                        @php
                            $deliveryStatusColors = [
                                'pending' => 'warning',
                                'sent' => 'info',
                                'read' => 'success',
                                'failed' => 'danger'
                            ];
                            $deliveryStatusIcons = [
                                'pending' => 'clock',
                                'sent' => 'send',
                                'read' => 'eye',
                                'failed' => 'x-circle'
                            ];
                        @endphp
                        <x-badge variant="{{ $deliveryStatusColors[$delivery->status] ?? 'info' }}"
                                 :icon="$deliveryStatusIcons[$delivery->status] ?? 'help-circle'">
                            {{ admin_trans($delivery->status) }}
                        </x-badge>
                    </x-table-cell>

                    <!-- Delivered At -->
                    <x-table-cell type="center">
                        @if($delivery->status !== 'pending' && $delivery->created_at)
                            <div class="text-sm text-primary">
                                {{ $delivery->created_at->format('M d, H:i') }}
                            </div>
                            <div class="text-xs text-tertiary">
                                {{ $delivery->created_at->diffForHumans() }}
                            </div>
                        @else
                            <span class="text-xs text-tertiary">-</span>
                        @endif
                    </x-table-cell>

                    <!-- Read At -->
                    <x-table-cell type="center">
                        @if($delivery->read_at)
                            <div class="text-sm text-green-600">
                                {{ $delivery->read_at->format('M d, H:i') }}
                            </div>
                            <div class="text-xs text-tertiary">
                                {{ $delivery->read_at->diffForHumans() }}
                            </div>
                        @else
                            <span class="text-xs text-tertiary">-</span>
                        @endif
                    </x-table-cell>

                    <!-- Device Info -->
                    <x-table-cell type="center">
                        @if($delivery->user->devices->isNotEmpty())
                            @php $device = $delivery->user->devices->first(); @endphp
                            <div class="text-xs">
                                <div class="font-medium text-primary">{{ ucfirst($device->platform ?? 'Unknown') }}</div>
                                @if($device->app_version)
                                    <div class="text-tertiary">v{{ $device->app_version }}</div>
                                @endif
                                @if($device->ip_country)
                                    <div class="text-tertiary">{{ $device->ip_country }}</div>
                                @endif
                            </div>
                        @else
                            <span class="text-xs text-tertiary">{{ admin_trans('no_device') }}</span>
                        @endif
                    </x-table-cell>
                </tr>
                @endforeach
            </x-enhanced-table>

            <!-- Pagination -->
            @if ($deliveries->hasPages())
                <div class="mt-6">
                    <x-pagination :paginator="$deliveries" />
                </div>
            @endif
        @endif
    </div>

    <!-- Export Info -->
    <div class="card bg-blue-50 border-blue-200">
        <div class="flex items-start gap-3">
            <i data-lucide="info" class="w-5 h-5 text-blue-600 mt-0.5"></i>
            <div>
                <h4 class="font-semibold text-blue-800 mb-1">{{ admin_trans('export_information') }}</h4>
                <p class="text-sm text-blue-600">
                    {{ admin_trans('delivery_report_export_description') }}
                </p>
                <div class="mt-2">
                    <x-button size="sm" variant="outline" onclick="exportReport()">
                        <i data-lucide="download" class="w-4 h-4 mr-2"></i>
                        {{ admin_trans('download_csv_report') }}
                    </x-button>
                </div>
            </div>
        </div>
    </div>
</div>

@endsection

@push('scripts')
<script>
// Export delivery report
function exportReport() {
    const notificationId = {{ $notification->id }};
    const status = new URLSearchParams(window.location.search).get('status') || '';
    const channel = new URLSearchParams(window.location.search).get('channel') || '';
    
    let exportUrl = `/admin/notifications/${notificationId}/delivery-report/export?`;
    
    if (status) exportUrl += `status=${status}&`;
    if (channel) exportUrl += `channel=${channel}&`;
    
    // Remove trailing & or ?
    exportUrl = exportUrl.replace(/[&?]$/, '');
    
    window.open(exportUrl, '_blank');
}

// Auto-refresh if there are pending deliveries
document.addEventListener('DOMContentLoaded', function() {
    const hasPending = {{ $deliveries->where('status', 'pending')->count() > 0 ? 'true' : 'false' }};
    
    if (hasPending) {
        // Refresh every 30 seconds if there are pending deliveries
        setTimeout(() => {
            location.reload();
        }, 30000);
    }
});

// Real-time status updates using polling
function pollForUpdates() {
    const notificationId = {{ $notification->id }};
    
    fetch(`/admin/notifications/${notificationId}/delivery-status`)
        .then(response => response.json())
        .then(data => {
            if (data.hasUpdates) {
                // Show notification that there are updates
                const toast = document.createElement('div');
                toast.className = 'fixed top-4 right-4 bg-blue-500 text-white px-4 py-2 rounded-lg shadow-lg z-50';
                toast.innerHTML = `
                    <div class="flex items-center gap-2">
                        <i data-lucide="refresh-cw" class="w-4 h-4"></i>
                        <span>{{ admin_trans('new_delivery_updates_available') }}</span>
                        <button onclick="location.reload()" class="ml-2 px-2 py-1 bg-white text-blue-500 rounded text-sm">
                            {{ admin_trans('refresh') }}
                        </button>
                    </div>
                `;
                document.body.appendChild(toast);
                
                // Remove toast after 10 seconds
                setTimeout(() => {
                    toast.remove();
                }, 10000);
            }
        })
        .catch(error => {
            console.log('Polling error:', error);
        });
}

// Start polling every 15 seconds
setInterval(pollForUpdates, 15000);
</script>
@endpush