@extends('layouts.app')

@section('content')
<div class="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 py-12 px-4 md:px-8">
    <div class="max-w-7xl mx-auto">
        <!-- رأس الصفحة -->
        <div class="mb-8">
            <h1 class="text-4xl font-bold text-gray-900 mb-2">🔐 تكامل ZATCA</h1>
            <p class="text-lg text-gray-600">إدارة شاملة لتكامل نظام الزكاة والدخل</p>
        </div>

        <!-- رسائل الخطأ -->
        @if($hasErrors)
        <div class="bg-red-50 border-l-4 border-red-500 p-6 mb-8 rounded-r-lg">
            <h3 class="text-lg font-bold text-red-800 mb-2">⚠️ خطأ</h3>
            <p class="text-red-700 mb-4">{{ $errorMessage }}</p>
            <button onclick="clearError()" class="text-red-600 hover:text-red-800 font-semibold">
                ✓ حل المشكلة
            </button>
        </div>
        @endif

        <!-- شريط التقدم -->
        <div class="mb-8 bg-white rounded-lg shadow-lg p-6 border-l-4 border-blue-500">
            <div class="mb-4">
                <div class="flex justify-between items-center mb-3">
                    <h2 class="text-xl font-semibold text-gray-900">📊 التقدم الإجمالي</h2>
                    <span class="text-3xl font-bold text-blue-600">{{ $status['progress_percentage'] }}%</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-4 overflow-hidden">
                    <div class="bg-gradient-to-r from-blue-500 to-blue-600 h-4 rounded-full transition-all duration-500"
                         style="width: {{ $status['progress_percentage'] }}%"></div>
                </div>
            </div>
            <p class="text-gray-600">
                <strong>الحالة الحالية:</strong> {{ $status['current_stage'] }}
            </p>
        </div>

        <!-- 4 بطاقات الإحصائيات -->
        <div class="grid md:grid-cols-4 gap-4 mb-8">
            <div class="bg-white rounded-lg shadow-lg p-6 border-t-4 border-blue-500">
                <h4 class="text-sm font-medium text-gray-600 mb-2">📈 إجمالي العمليات</h4>
                <p class="text-3xl font-bold text-blue-600">{{ $retryStats['total'] ?? 0 }}</p>
            </div>
            <div class="bg-white rounded-lg shadow-lg p-6 border-t-4 border-green-500">
                <h4 class="text-sm font-medium text-gray-600 mb-2">✅ العمليات الناجحة</h4>
                <p class="text-3xl font-bold text-green-600">{{ $retryStats['successful'] ?? 0 }}</p>
            </div>
            <div class="bg-white rounded-lg shadow-lg p-6 border-t-4 border-red-500">
                <h4 class="text-sm font-medium text-gray-600 mb-2">❌ العمليات الفاشلة</h4>
                <p class="text-3xl font-bold text-red-600">{{ $retryStats['failed'] ?? 0 }}</p>
            </div>
            <div class="bg-white rounded-lg shadow-lg p-6 border-t-4 border-amber-500">
                <h4 class="text-sm font-medium text-gray-600 mb-2">📊 نسبة النجاح</h4>
                <p class="text-3xl font-bold text-amber-600">{{ $retryStats['success_rate'] ?? 0 }}%</p>
            </div>
        </div>

        <!-- الرسوم البيانية -->
        @if($reports && count($reports) > 0)
        <div class="grid md:grid-cols-2 gap-8 mb-8">
            <!-- رسم بياني 1: نوع العمليات -->
            @if(isset($reports['by_operation_type']) && count($reports['by_operation_type']) > 0)
            <div class="bg-white rounded-lg shadow-lg p-6">
                <h4 class="text-lg font-semibold mb-4">📊 العمليات حسب النوع</h4>
                <canvas id="operationTypeChart"></canvas>
            </div>
            @endif

            <!-- رسم بياني 2: الاتجاهات -->
            @if(isset($reports['trends']))
            <div class="bg-white rounded-lg shadow-lg p-6">
                <h4 class="text-lg font-semibold mb-4">📈 الاتجاهات الأسبوعية</h4>
                <div class="space-y-3">
                    <div>
                        <span class="text-sm font-medium text-gray-600">الأسبوع الماضي:</span>
                        <p class="text-xl font-bold text-blue-600">{{ $reports['trends']['last_week']['total'] ?? 0 }} عملية</p>
                    </div>
                    <div>
                        <span class="text-sm font-medium text-gray-600">الأسبوع السابق:</span>
                        <p class="text-xl font-bold text-gray-600">{{ $reports['trends']['previous_week']['total'] ?? 0 }} عملية</p>
                    </div>
                    <div>
                        <span class="text-sm font-medium text-gray-600">الاتجاه:</span>
                        <p class="text-xl font-bold {{ strpos($reports['trends']['trend'] ?? '', '↑') !== false ? 'text-green-600' : 'text-red-600' }}">
                            {{ $reports['trends']['trend'] ?? 'N/A' }}
                        </p>
                    </div>
                </div>
            </div>
            @endif
        </div>

        <!-- رسم بياني 3: الخط الزمني -->
        @if(isset($reports['timeline']) && count($reports['timeline']) > 0)
        <div class="bg-white rounded-lg shadow-lg p-6 mb-8">
            <h4 class="text-lg font-semibold mb-4">📅 الخط الزمني (آخر 7 أيام)</h4>
            <canvas id="timelineChart"></canvas>
        </div>
        @endif
        @endif

        <!-- جدول آخر العمليات -->
        @if($recentOperations && count($recentOperations) > 0)
        <div class="bg-white rounded-lg shadow-lg p-6 mb-8">
            <h4 class="text-lg font-semibold mb-4">🕐 آخر العمليات</h4>
            <div class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead class="bg-gray-50 border-b">
                        <tr>
                            <th class="px-4 py-3 text-right font-semibold text-gray-700">نوع العملية</th>
                            <th class="px-4 py-3 text-right font-semibold text-gray-700">الحالة</th>
                            <th class="px-4 py-3 text-right font-semibold text-gray-700">التاريخ</th>
                            <th class="px-4 py-3 text-right font-semibold text-gray-700">ملاحظات</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y">
                        @forelse($recentOperations as $operation)
                        <tr class="hover:bg-gray-50 transition">
                            <td class="px-4 py-3">
                                <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                    {{ $operation->operation_type ?? 'N/A' }}
                                </span>
                            </td>
                            <td class="px-4 py-3">
                                @if($operation->status === 'success')
                                    <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">✅ نجح</span>
                                @elseif($operation->status === 'failed')
                                    <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800">❌ فشل</span>
                                @else
                                    <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">⏳ قيد</span>
                                @endif
                            </td>
                            <td class="px-4 py-3 text-gray-600">{{ $operation->created_at->format('Y-m-d H:i') ?? 'N/A' }}</td>
                            <td class="px-4 py-3 text-gray-600">{{ substr($operation->response_message ?? 'بدون ملاحظات', 0, 50) }}...</td>
                        </tr>
                        @empty
                        <tr>
                            <td colspan="4" class="px-4 py-6 text-center text-gray-500">لا توجد عمليات حالياً</td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
        @endif

        <!-- جدول العمليات الفاشلة -->
        @if($failedOperations && count($failedOperations) > 0)
        <div class="bg-white rounded-lg shadow-lg p-6 mb-8 border-l-4 border-red-500">
            <h4 class="text-lg font-semibold mb-4 text-red-600">⚠️ العمليات الفاشلة التي تحتاج متابعة</h4>
            <div class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead class="bg-red-50 border-b">
                        <tr>
                            <th class="px-4 py-3 text-right font-semibold text-gray-700">نوع العملية</th>
                            <th class="px-4 py-3 text-right font-semibold text-gray-700">رسالة الخطأ</th>
                            <th class="px-4 py-3 text-right font-semibold text-gray-700">عدد المحاولات</th>
                            <th class="px-4 py-3 text-right font-semibold text-gray-700">التاريخ</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y">
                        @forelse($failedOperations as $operation)
                        <tr class="hover:bg-red-50 transition">
                            <td class="px-4 py-3">
                                <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                    {{ $operation->operation_type ?? 'N/A' }}
                                </span>
                            </td>
                            <td class="px-4 py-3 text-red-600">{{ substr($operation->error_message ?? 'بدون تفاصيل', 0, 50) }}...</td>
                            <td class="px-4 py-3">
                                <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-orange-100 text-orange-800">
                                    {{ $operation->attempt_number ?? 0 }}/3
                                </span>
                            </td>
                            <td class="px-4 py-3 text-gray-600">{{ $operation->created_at->format('Y-m-d H:i') ?? 'N/A' }}</td>
                        </tr>
                        @empty
                        <tr>
                            <td colspan="4" class="px-4 py-6 text-center text-green-600">✅ لا توجد عمليات فاشلة</td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
        @endif

        <!-- مراحل العملية -->
        <div class="mb-8">
            <h2 class="text-2xl font-bold text-gray-900 mb-6">📋 مراحل التكامل</h2>
            <div class="space-y-4">
                @foreach($status['all_stages'] as $stage)
                <div class="bg-white rounded-lg shadow-lg overflow-hidden border-l-4 
                    {{ $stage['status'] === 'completed' ? 'border-green-500' : 'border-gray-300' }}">
                    <div class="p-6 flex items-start">
                        <div class="flex-shrink-0 mr-6">
                            <div class="flex items-center justify-center h-12 w-12 rounded-full
                                {{ $stage['status'] === 'completed' ? 'bg-green-100' : 'bg-blue-100' }}">
                                @if($stage['status'] === 'completed')
                                    <span class="text-xl">✅</span>
                                @else
                                    <span class="text-lg font-bold text-blue-600">{{ $stage['number'] }}</span>
                                @endif
                            </div>
                        </div>
                        <div class="flex-1">
                            <h3 class="text-lg font-semibold text-gray-900">{{ $stage['name'] }}</h3>
                            <p class="text-gray-600 mt-1">{{ $stage['description'] }}</p>
                        </div>
                        <div class="flex-shrink-0 ml-4">
                            @if($stage['status'] === 'completed')
                            <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800">
                                ✅ مكتمل
                            </span>
                            @elseif($stage['status'] === 'ready')
                            <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-blue-100 text-blue-800">
                                🚀 جاهز
                            </span>
                            @else
                            <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-gray-100 text-gray-800">
                                ⏳ قريباً
                            </span>
                            @endif
                        </div>
                    </div>
                </div>
                @endforeach
            </div>
        </div>

        <!-- المتطلبات -->
        <div class="mb-8 bg-blue-50 rounded-lg shadow-lg p-6 border-l-4 border-blue-500">
            <h3 class="text-xl font-semibold text-blue-900 mb-4">📋 متطلبات المرحلة الحالية</h3>
            <ul class="space-y-3">
                @foreach($requirements as $requirement)
                <li class="flex items-center text-blue-800">
                    <span class="mr-3">✓</span>
                    {{ $requirement }}
                </li>
                @endforeach
            </ul>
        </div>

        <!-- الخطوة التالية -->
        @if($nextStep)
        <div class="mb-8 bg-gradient-to-r from-green-50 to-emerald-50 rounded-lg shadow-xl p-8 border-l-4 border-green-500">
            <h3 class="text-2xl font-bold text-gray-900 mb-3">🎯 الخطوة التالية</h3>
            <p class="text-lg text-gray-700 mb-6">{{ $nextStep['description'] }}</p>
            <button onclick="executeNextStep()" 
                    class="inline-flex items-center px-8 py-4 bg-gradient-to-r from-green-500 to-emerald-600 text-white font-bold rounded-lg hover:from-green-600 hover:to-emerald-700 transition-all duration-200 shadow-lg hover:shadow-xl transform hover:scale-105">
                ➜ {{ $nextStep['button_text'] }}
            </button>
        </div>
        @endif

        <!-- معلومات الشركة -->
        <div class="grid md:grid-cols-2 gap-6 mb-8">
            <div class="bg-white rounded-lg shadow-lg p-6">
                <h4 class="text-lg font-semibold text-gray-900 mb-4">📌 معلومات الشركة</h4>
                <dl class="space-y-3">
                    <div>
                        <dt class="text-sm font-medium text-gray-600">اسم الشركة</dt>
                        <dd class="text-lg font-semibold text-gray-900">{{ $company->name }}</dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-600">رقم الضريبة</dt>
                        <dd class="text-lg font-semibold text-gray-900">{{ $company->tax_number ?? 'غير محدد' }}</dd>
                    </div>
                </dl>
            </div>

            <div class="bg-white rounded-lg shadow-lg p-6">
                <h4 class="text-lg font-semibold text-gray-900 mb-4">⚙️ إعدادات ZATCA</h4>
                <dl class="space-y-3">
                    <div>
                        <dt class="text-sm font-medium text-gray-600">حالة التكامل</dt>
                        <dd class="text-lg font-semibold text-gray-900">{{ $company->zatca_status ?? 'لم يتم البدء' }}</dd>
                    </div>
                </dl>
            </div>
        </div>
    </div>
</div>

<!-- تضمين Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

@push('scripts')
<script>
    // رسم بياني نوع العمليات
    @if(isset($reports['by_operation_type']) && count($reports['by_operation_type']) > 0)
    const operationTypeCtx = document.getElementById('operationTypeChart')?.getContext('2d');
    if (operationTypeCtx) {
        new Chart(operationTypeCtx, {
            type: 'doughnut',
            data: {
                labels: {!! json_encode(array_column($reports['by_operation_type'], 'operation_type')) !!},
                datasets: [{
                    data: {!! json_encode(array_column($reports['by_operation_type'], 'total')) !!},
                    backgroundColor: ['#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6'],
                    borderColor: '#fff',
                    borderWidth: 2,
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'bottom',
                    }
                }
            }
        });
    }
    @endif

    // رسم بياني الخط الزمني
    @if(isset($reports['timeline']) && count($reports['timeline']) > 0)
    const timelineCtx = document.getElementById('timelineChart')?.getContext('2d');
    if (timelineCtx) {
        new Chart(timelineCtx, {
            type: 'line',
            data: {
                labels: {!! json_encode(array_column($reports['timeline'], 'date')) !!},
                datasets: [
                    {
                        label: 'نجح',
                        data: {!! json_encode(array_column($reports['timeline'], 'successful')) !!},
                        borderColor: '#10B981',
                        backgroundColor: 'rgba(16, 185, 129, 0.1)',
                        tension: 0.3,
                    },
                    {
                        label: 'فشل',
                        data: {!! json_encode(array_column($reports['timeline'], 'failed')) !!},
                        borderColor: '#EF4444',
                        backgroundColor: 'rgba(239, 68, 68, 0.1)',
                        tension: 0.3,
                    },
                    {
                        label: 'قيد',
                        data: {!! json_encode(array_column($reports['timeline'], 'pending')) !!},
                        borderColor: '#F59E0B',
                        backgroundColor: 'rgba(245, 158, 11, 0.1)',
                        tension: 0.3,
                    }
                ]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'bottom',
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                    }
                }
            }
        });
    }
    @endif

    async function executeNextStep() {
        try {
            const response = await fetch('{{ route("zatca.dashboard.execute-next-step") }}', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'Content-Type': 'application/json',
                },
            });

            const data = await response.json();
            if (data.success) {
                alert('✅ ' + data.message);
                if (data.redirect) {
                    window.location.href = data.redirect;
                } else {
                    setTimeout(() => location.reload(), 2000);
                }
            } else {
                alert('❌ ' + (data.message || 'حدث خطأ'));
            }
        } catch (error) {
            alert('❌ خطأ: ' + error.message);
        }
    }

    function clearError() {
        fetch('{{ route("zatca.dashboard.clear-error") }}', {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
            }
        }).then(() => location.reload());
    }
</script>
@endpush

@endsection
