@extends('layouts.app')
@section('content')
<div class="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 py-8 px-4 md:px-8">
    <div class="max-w-7xl mx-auto">
        <!-- Header Section -->
        <div class="flex justify-between items-start mb-8">
            <div>
                <h1 class="text-4xl font-bold text-gray-900 mb-2">تقرير المطابقة الثلاثية</h1>
                <p class="text-gray-600">مطابقة أوامر الشراء والفواتير والاستقبالات للتحقق من التطابق الكامل</p>
            </div>
            <div class="flex gap-2">
                <button onclick="window.print()" class="inline-flex items-center px-4 py-2 bg-gradient-to-r from-blue-600 to-blue-700 text-white font-semibold rounded-lg hover:from-blue-700 hover:to-blue-800 transition-all duration-200 shadow-lg">
                    <i class="fas fa-print mr-2"></i>طباعة
                </button>
                <a href="{{ route('reports.purchase.three-way-matching', ['export' => true, 'format' => 'excel']) }}" class="inline-flex items-center px-4 py-2 bg-gradient-to-r from-green-600 to-green-700 text-white font-semibold rounded-lg hover:from-green-700 hover:to-green-800 transition-all duration-200 shadow-lg">
                    <i class="fas fa-file-excel mr-2"></i>تحميل Excel
                </a>
                <a href="{{ route('reports.purchase.three-way-matching', ['export' => true, 'format' => 'pdf']) }}" class="inline-flex items-center px-4 py-2 bg-gradient-to-r from-red-600 to-red-700 text-white font-semibold rounded-lg hover:from-red-700 hover:to-red-800 transition-all duration-200 shadow-lg">
                    <i class="fas fa-file-pdf mr-2"></i>تحميل PDF
                </a>
            </div>
        </div>

        @php
            $dataObj = is_array($data) ? collect($data) : ($data ?? collect());
            $totalInvoices = $dataObj['total_invoices'] ?? 0;
            $readyToPay = $dataObj['ready_to_pay'] ?? 0;
            $requiresReview = $dataObj['requires_review'] ?? 0;
            $details = collect($dataObj['details'] ?? []);
            $hasData = $details->count() > 0;
        @endphp

        @if($hasData)
        <!-- Statistics Cards -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <div class="bg-gradient-to-br from-blue-50 to-blue-100 rounded-lg p-6 shadow-md border border-blue-200">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-600 text-sm font-semibold">إجمالي الفواتير</p>
                        <p class="text-3xl font-bold text-blue-600">{{ $totalInvoices }}</p>
                    </div>
                    <i class="fas fa-file-invoice-dollar text-4xl text-blue-300"></i>
                </div>
            </div>

            <div class="bg-gradient-to-br from-green-50 to-green-100 rounded-lg p-6 shadow-md border border-green-200">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-600 text-sm font-semibold">جاهزة للدفع</p>
                        <p class="text-3xl font-bold text-green-600">{{ $readyToPay }}</p>
                        <p class="text-xs text-green-700 mt-1">{{ $totalInvoices > 0 ? number_format(($readyToPay / $totalInvoices) * 100, 1) : 0 }}%</p>
                    </div>
                    <i class="fas fa-check-circle text-4xl text-green-300"></i>
                </div>
            </div>

            <div class="bg-gradient-to-br from-orange-50 to-orange-100 rounded-lg p-6 shadow-md border border-orange-200">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-600 text-sm font-semibold">تحتاج مراجعة</p>
                        <p class="text-3xl font-bold text-orange-600">{{ $requiresReview }}</p>
                        <p class="text-xs text-orange-700 mt-1">{{ $totalInvoices > 0 ? number_format(($requiresReview / $totalInvoices) * 100, 1) : 0 }}%</p>
                    </div>
                    <i class="fas fa-exclamation-circle text-4xl text-orange-300"></i>
                </div>
            </div>

            <div class="bg-gradient-to-br from-purple-50 to-purple-100 rounded-lg p-6 shadow-md border border-purple-200">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-600 text-sm font-semibold">معدل المطابقة</p>
                        <p class="text-3xl font-bold text-purple-600">{{ $details->avg('match_percentage') ? number_format($details->avg('match_percentage'), 1) : 0 }}%</p>
                    </div>
                    <i class="fas fa-chart-pie text-4xl text-purple-300"></i>
                </div>
            </div>
        </div>

        <!-- Charts Row -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
            <div class="bg-white rounded-lg shadow-md p-6 border border-gray-200">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">توزيع حالة المطابقة</h3>
                <canvas id="matchingStatusChart" height="80"></canvas>
            </div>

            <div class="bg-white rounded-lg shadow-md p-6 border border-gray-200">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">نسب المطابقة</h3>
                <canvas id="matchPercentageChart" height="80"></canvas>
            </div>
        </div>

        <!-- Main Data Table -->
        <div class="bg-white rounded-lg shadow-md p-6 mb-8 overflow-x-auto border border-gray-200">
            <h3 class="text-lg font-semibold text-gray-900 mb-4">تفاصيل الفواتير</h3>
            <table class="w-full text-sm">
                <thead>
                    <tr class="bg-gradient-to-r from-gray-800 to-gray-900 text-white">
                        <th class="px-4 py-3 text-right">#</th>
                        <th class="px-4 py-3 text-right">رقم الفاتورة</th>
                        <th class="px-4 py-3 text-right">اسم المورد</th>
                        <th class="px-4 py-3 text-center">إجمالي البنود</th>
                        <th class="px-4 py-3 text-center">البنود المطابقة</th>
                        <th class="px-4 py-3 text-center">البنود غير المطابقة</th>
                        <th class="px-4 py-3 text-center">نسبة المطابقة</th>
                        <th class="px-4 py-3 text-center">الحالة</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($details as $index => $invoice)
                        <tr class="border-b hover:bg-blue-50 transition-colors duration-150">
                            <td class="px-4 py-3 text-gray-600 font-medium">{{ $index + 1 }}</td>
                            <td class="px-4 py-3 font-semibold text-gray-900">{{ $invoice['invoice_number'] ?? 'N/A' }}</td>
                            <td class="px-4 py-3 text-gray-700">{{ $invoice['supplier_name'] ?? 'N/A' }}</td>
                            <td class="px-4 py-3 text-center font-semibold">{{ $invoice['total_items'] ?? 0 }}</td>
                            <td class="px-4 py-3 text-center">
                                <span class="bg-green-100 text-green-700 px-3 py-1 rounded-full font-semibold text-xs">
                                    {{ $invoice['matched_items'] ?? 0 }}
                                </span>
                            </td>
                            <td class="px-4 py-3 text-center">
                                <span class="bg-red-100 text-red-700 px-3 py-1 rounded-full font-semibold text-xs">
                                    {{ $invoice['mismatched_items'] ?? 0 }}
                                </span>
                            </td>
                            <td class="px-4 py-3 text-center font-semibold">
                                <div class="flex items-center justify-center gap-2">
                                    <span>{{ number_format($invoice['match_percentage'] ?? 0, 1) }}%</span>
                                    <div class="w-16 h-2 bg-gray-200 rounded-full overflow-hidden">
                                        <div class="h-full bg-gradient-to-r from-green-400 to-green-600" style="width: {{ $invoice['match_percentage'] ?? 0 }}%"></div>
                                    </div>
                                </div>
                            </td>
                            <td class="px-4 py-3 text-center">
                                @if(($invoice['status'] ?? '') === 'ready_to_pay')
                                    <span class="inline-block bg-green-100 text-green-700 px-3 py-1 rounded-full font-semibold text-xs">
                                        <i class="fas fa-check-circle mr-1"></i>جاهزة للدفع
                                    </span>
                                @else
                                    <span class="inline-block bg-orange-100 text-orange-700 px-3 py-1 rounded-full font-semibold text-xs">
                                        <i class="fas fa-hourglass-half mr-1"></i>تحتاج مراجعة
                                    </span>
                                @endif
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>

        <!-- Issues Summary -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
            <div class="bg-gradient-to-br from-red-50 to-red-100 rounded-lg shadow-md p-6 border border-red-200">
                <h3 class="text-lg font-bold text-red-900 mb-4">
                    <i class="fas fa-exclamation-triangle text-red-600 mr-2"></i>الفواتير غير المطابقة
                </h3>
                <div class="space-y-3">
                    @forelse($details->filter(function($inv) { return ($inv['status'] ?? '') === 'requires_review'; }) as $invoice)
                        <div class="bg-white rounded p-3 border-l-4 border-red-500">
                            <p class="font-semibold text-gray-900">{{ $invoice['invoice_number'] ?? 'N/A' }}</p>
                            <p class="text-sm text-gray-600">المورد: {{ $invoice['supplier_name'] ?? 'N/A' }}</p>
                            <p class="text-sm text-red-700 font-medium">عدد المشاكل: {{ $invoice['mismatched_items'] ?? 0 }}</p>
                        </div>
                    @empty
                        <p class="text-gray-600 text-sm italic">جميع الفواتير متطابقة ✓</p>
                    @endforelse
                </div>
            </div>

            <div class="bg-gradient-to-br from-green-50 to-green-100 rounded-lg shadow-md p-6 border border-green-200">
                <h3 class="text-lg font-bold text-green-900 mb-4">
                    <i class="fas fa-check-double text-green-600 mr-2"></i>الفواتير المطابقة تماماً
                </h3>
                <div class="space-y-3">
                    @forelse($details->filter(function($inv) { return ($inv['status'] ?? '') === 'ready_to_pay'; }) as $invoice)
                        <div class="bg-white rounded p-3 border-l-4 border-green-500">
                            <p class="font-semibold text-gray-900">{{ $invoice['invoice_number'] ?? 'N/A' }}</p>
                            <p class="text-sm text-gray-600">المورد: {{ $invoice['supplier_name'] ?? 'N/A' }}</p>
                            <p class="text-sm text-green-700 font-medium">جميع البنود متطابقة ✓</p>
                        </div>
                    @empty
                        <p class="text-gray-600 text-sm italic">لا توجد فواتير متطابقة تماماً</p>
                    @endforelse
                </div>
            </div>
        </div>

        <!-- Three-Way Matching Information -->
        <div class="bg-blue-50 border-l-4 border-blue-500 rounded-lg p-6 mb-8">
            <h3 class="text-lg font-bold text-blue-900 mb-4">
                <i class="fas fa-info-circle text-blue-600 mr-2"></i>شرح المطابقة الثلاثية
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm text-gray-700">
                <div class="bg-white rounded p-4 border-t-4 border-blue-500">
                    <p class="font-semibold text-blue-900 mb-2">✓ أمر الشراء (PO)</p>
                    <p class="text-gray-600">البيانات المعتمدة بما في ذلك الكميات والأسعار والشروط</p>
                </div>
                <div class="bg-white rounded p-4 border-t-4 border-purple-500">
                    <p class="font-semibold text-purple-900 mb-2">✓ إشعار الاستقبال (GRN)</p>
                    <p class="text-gray-600">البيانات المستقبلة والتحقق من الكميات والجودة</p>
                </div>
                <div class="bg-white rounded p-4 border-t-4 border-green-500">
                    <p class="font-semibold text-green-900 mb-2">✓ فاتورة المورد</p>
                    <p class="text-gray-600">فاتورة المورد المستلمة للدفع</p>
                </div>
            </div>
            <div class="mt-4 bg-white rounded p-4">
                <p class="font-semibold text-blue-900 mb-2">المطابقة تعني:</p>
                <ul class="list-disc list-inside text-gray-700 space-y-1">
                    <li>تطابق الكميات المطلوبة والمستقبلة والمفوترة</li>
                    <li>تطابق الأسعار بين أمر الشراء والفاتورة</li>
                    <li>عدم وجود تناقضات تتطلب تصحيح</li>
                    <li>جاهزية الفاتورة للدفع دون احتياجات إضافية</li>
                </ul>
            </div>
        </div>

        @else
        <!-- Empty State -->
        <div class="bg-white rounded-lg shadow-md p-12 text-center border border-gray-200">
            <i class="fas fa-inbox text-6xl text-gray-400 mb-4"></i>
            <h3 class="text-2xl font-bold text-gray-900 mb-2">لا توجد بيانات</h3>
            <p class="text-gray-600">لم يتم العثور على فواتير موردين في الفترة المحددة</p>
        </div>
        @endif
    </div>
</div>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const data = @json($details ?? []);
        
        @if($hasData)
        // Chart 1: Matching Status Distribution
        const statusCtx = document.getElementById('matchingStatusChart').getContext('2d');
        new Chart(statusCtx, {
            type: 'doughnut',
            data: {
                labels: ['جاهزة للدفع', 'تحتاج مراجعة'],
                datasets: [{
                    data: [{{ $readyToPay }}, {{ $requiresReview }}],
                    backgroundColor: ['#10b981', '#f97316'],
                    borderColor: ['#059669', '#d97706'],
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: { position: 'bottom' }
                }
            }
        });

        // Chart 2: Match Percentage Distribution
        const percentageData = data.map(inv => ({
            label: inv.invoice_number,
            percentage: inv.match_percentage || 0
        }));

        const percentageCtx = document.getElementById('matchPercentageChart').getContext('2d');
        new Chart(percentageCtx, {
            type: 'bar',
            data: {
                labels: percentageData.map(d => d.label),
                datasets: [{
                    label: 'نسبة المطابقة (%)',
                    data: percentageData.map(d => d.percentage),
                    backgroundColor: percentageData.map(d => d.percentage === 100 ? '#10b981' : '#f97316'),
                    borderColor: percentageData.map(d => d.percentage === 100 ? '#059669' : '#d97706'),
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                indexAxis: 'y',
                scales: {
                    x: { max: 100 }
                },
                plugins: { legend: { display: false } }
            }
        });
        @endif
    });
</script>
@endpush
@endsection