@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.supplier-performance', ['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.supplier-performance', ['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
            // تحويل البيانات إلى Collection إذا كانت Array
            $dataCollection = is_array($data) ? collect($data) : $data;
            $supplierCount = $dataCollection->count();
            $hasData = $supplierCount > 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">
                <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">{{ $supplierCount }}</p>
                    </div>
                    <i class="fas fa-users 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">
                <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">{{ number_format($dataCollection->sum('total_purchases'), 2) }}</p>
                    </div>
                    <i class="fas fa-shopping-cart text-4xl text-green-300"></i>
                </div>
            </div>

            <div class="bg-gradient-to-br from-purple-50 to-purple-100 rounded-lg p-6 shadow-md">
                <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">{{ number_format($dataCollection->avg('overall_rating'), 2) }}/5</p>
                    </div>
                    <i class="fas fa-star text-4xl text-purple-300"></i>
                </div>
            </div>

            <div class="bg-gradient-to-br from-orange-50 to-orange-100 rounded-lg p-6 shadow-md">
                <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">{{ $dataCollection->sum('total_invoices') }}</p>
                    </div>
                    <i class="fas fa-receipt text-4xl text-orange-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="ratingsChart" 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="purchasesChart" 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="performanceChart" 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="qualityDeliveryChart" 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-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>
                        <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($dataCollection as $supplier)
                        <tr class="border-b hover:bg-blue-50 transition-colors duration-150">
                            <td class="px-4 py-3 font-semibold text-gray-900">{{ $supplier['supplier_name'] ?? 'N/A' }}</td>
                            <td class="px-4 py-3 text-center">
                                <span class="@if(($supplier['on_time_delivery'] ?? 0) >= 95) text-green-600 @elseif(($supplier['on_time_delivery'] ?? 0) >= 80) text-yellow-600 @else text-red-600 @endif font-semibold">
                                    {{ number_format($supplier['on_time_delivery'] ?? 0, 2) }}%
                                </span>
                            </td>
                            <td class="px-4 py-3 text-center">
                                <span class="@if(($supplier['quality_percentage'] ?? 0) >= 98) text-green-600 @elseif(($supplier['quality_percentage'] ?? 0) >= 90) text-yellow-600 @else text-red-600 @endif font-semibold">
                                    {{ number_format($supplier['quality_percentage'] ?? 0, 2) }}%
                                </span>
                            </td>
                            <td class="px-4 py-3 text-center">
                                <span class="inline-block bg-blue-100 text-blue-800 px-3 py-1 rounded-full font-semibold text-xs">
                                    {{ number_format($supplier['price_rating'] ?? 0, 2) }}/5
                                </span>
                            </td>
                            <td class="px-4 py-3 text-center">
                                <span class="@if(($supplier['growth_rate'] ?? 0) > 0) text-green-600 @else text-red-600 @endif font-semibold">
                                    {{ number_format($supplier['growth_rate'] ?? 0, 2) }}%
                                </span>
                            </td>
                            <td class="px-4 py-3 text-center">
                                <span class="@if(($supplier['overall_rating'] ?? 0) >= 4.5) text-green-600 @elseif(($supplier['overall_rating'] ?? 0) >= 3) text-yellow-600 @else text-red-600 @endif font-bold text-lg">
                                    {{ number_format($supplier['overall_rating'] ?? 0, 2) }}/5
                                </span>
                            </td>
                            <td class="px-4 py-3 text-center font-semibold text-gray-700">{{ number_format($supplier['total_purchases'] ?? 0, 2) }}</td>
                            <td class="px-4 py-3 text-center font-semibold text-gray-700">{{ $supplier['total_invoices'] ?? 0 }}</td>
                            <td class="px-4 py-3 text-center font-semibold text-gray-700">{{ number_format($supplier['total_payments'] ?? 0, 2) }}</td>
                            <td class="px-4 py-3 text-center">
                                @php $recommendation = $supplier['recommendation'] ?? 'Fair'; @endphp
                                @if($recommendation === 'Excellent')
                                    <span class="inline-block bg-green-100 text-green-800 px-3 py-1 rounded-full font-semibold text-xs">
                                        <i class="fas fa-check-circle mr-1"></i>ممتاز
                                    </span>
                                @elseif($recommendation === 'Good')
                                    <span class="inline-block bg-blue-100 text-blue-800 px-3 py-1 rounded-full font-semibold text-xs">
                                        <i class="fas fa-thumbs-up mr-1"></i>جيد
                                    </span>
                                @elseif($recommendation === 'Fair')
                                    <span class="inline-block bg-yellow-100 text-yellow-800 px-3 py-1 rounded-full font-semibold text-xs">
                                        <i class="fas fa-exclamation-triangle mr-1"></i>مقبول
                                    </span>
                                @else
                                    <span class="inline-block bg-red-100 text-red-800 px-3 py-1 rounded-full font-semibold text-xs">
                                        <i class="fas fa-times-circle mr-1"></i>ضعيف
                                    </span>
                                @endif
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>

        <!-- Summary Sections -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
            <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-star text-yellow-500 mr-2"></i>الموردون المتميزون
                </h3>
                <div class="space-y-3">
                    @php
                        $excellent = $dataCollection->filter(function($s) { return ($s['overall_rating'] ?? 0) >= 4.5; });
                    @endphp
                    @forelse($excellent as $supplier)
                        <div class="bg-white rounded p-3 border-l-4 border-green-500">
                            <p class="font-semibold text-gray-900">{{ $supplier['supplier_name'] ?? 'N/A' }}</p>
                            <p class="text-sm text-gray-600">التقييم: {{ number_format($supplier['overall_rating'] ?? 0, 2) }}/5</p>
                        </div>
                    @empty
                        <p class="text-gray-600 text-sm italic">لا توجد موردون متميزون حالياً</p>
                    @endforelse
                </div>
            </div>

            <div class="bg-gradient-to-br from-yellow-50 to-yellow-100 rounded-lg shadow-md p-6 border border-yellow-200">
                <h3 class="text-lg font-bold text-yellow-900 mb-4">
                    <i class="fas fa-exclamation-circle text-yellow-600 mr-2"></i>قيد الملاحظة
                </h3>
                <div class="space-y-3">
                    @php
                        $fair = $dataCollection->filter(function($s) { return ($s['overall_rating'] ?? 0) >= 3 && ($s['overall_rating'] ?? 0) < 4.5; });
                    @endphp
                    @forelse($fair as $supplier)
                        <div class="bg-white rounded p-3 border-l-4 border-yellow-500">
                            <p class="font-semibold text-gray-900">{{ $supplier['supplier_name'] ?? 'N/A' }}</p>
                            <p class="text-sm text-gray-600">التقييم: {{ number_format($supplier['overall_rating'] ?? 0, 2) }}/5</p>
                        </div>
                    @empty
                        <p class="text-gray-600 text-sm italic">لا توجد موردون قيد الملاحظة</p>
                    @endforelse
                </div>
            </div>

            <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-times-circle text-red-600 mr-2"></i>بحاجة للمراجعة
                </h3>
                <div class="space-y-3">
                    @php
                        $poor = $dataCollection->filter(function($s) { return ($s['overall_rating'] ?? 0) < 3; });
                    @endphp
                    @forelse($poor as $supplier)
                        <div class="bg-white rounded p-3 border-l-4 border-red-500">
                            <p class="font-semibold text-gray-900">{{ $supplier['supplier_name'] ?? 'N/A' }}</p>
                            <p class="text-sm text-gray-600">التقييم: {{ number_format($supplier['overall_rating'] ?? 0, 2) }}/5</p>
                        </div>
                    @empty
                        <p class="text-gray-600 text-sm italic">لا توجد موردون بحاجة للمراجعة</p>
                    @endforelse
                </div>
            </div>
        </div>

        <!-- Metrics 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-2 lg:grid-cols-3 gap-4 text-sm text-gray-700">
                <div class="bg-white rounded p-3">
                    <p class="font-semibold text-blue-900">التسليم في الموعد</p>
                    <p class="text-gray-600">نسبة الطلبات المسلمة في الموعد المحدد</p>
                </div>
                <div class="bg-white rounded p-3">
                    <p class="font-semibold text-blue-900">الجودة</p>
                    <p class="text-gray-600">نسبة المنتجات المقبولة من إجمالي المستلمة</p>
                </div>
                <div class="bg-white rounded p-3">
                    <p class="font-semibold text-blue-900">تقييم السعر</p>
                    <p class="text-gray-600">تقييم من 0 إلى 5 بناءً على توافقية السعر</p>
                </div>
                <div class="bg-white rounded p-3">
                    <p class="font-semibold text-blue-900">معدل النمو</p>
                    <p class="text-gray-600">النسبة المئوية لنمو حجم المشتريات</p>
                </div>
                <div class="bg-white rounded p-3">
                    <p class="font-semibold text-blue-900">التقييم الإجمالي</p>
                    <p class="text-gray-600">متوسط مرجح (توقيت 30% + جودة 40% + سعر 20% + نمو 10%)</p>
                </div>
                <div class="bg-white rounded p-3">
                    <p class="font-semibold text-blue-900">التوصية</p>
                    <p class="text-gray-600">ممتاز (≥4.5) / جيد / مقبول / ضعيف (<3)</p>
                </div>
            </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-300 mb-4 inline-block"></i>
            <p class="text-gray-600 text-lg font-semibold">لا توجد بيانات للعرض</p>
            <p class="text-gray-500 mt-2">يرجى اختيار مورد أو التحقق من البيانات المتاحة</p>
        </div>
    @endif

    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    @if($hasData)
        // Ratings Chart
        const ctx1 = document.getElementById('ratingsChart').getContext('2d');
        new Chart(ctx1, {
            type: 'bar',
            data: {
                labels: [
                    @foreach($dataCollection as $supplier)
                        '{{ $supplier['supplier_name'] ?? '' }}',
                    @endforeach
                ],
                datasets: [{
                    label: 'التقييم الإجمالي',
                    data: [
                        @foreach($dataCollection as $supplier)
                            {{ $supplier['overall_rating'] ?? 0 }},
                        @endforeach
                    ],
                    backgroundColor: [
                        @foreach($dataCollection as $supplier)
                            @if(($supplier['overall_rating'] ?? 0) >= 4.5)
                                'rgba(34, 197, 94, 0.7)',
                            @elseif(($supplier['overall_rating'] ?? 0) >= 3)
                                'rgba(234, 179, 8, 0.7)',
                            @else
                                'rgba(239, 68, 68, 0.7)',
                            @endif
                        @endforeach
                    ],
                    borderRadius: 4,
                    borderColor: '#ccc',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: { display: true, position: 'top' },
                    tooltip: { 
                        callbacks: {
                            label: function(context) {
                                return 'التقييم: ' + context.parsed.y.toFixed(2) + '/5';
                            }
                        }
                    }
                },
                scales: { 
                    y: { 
                        beginAtZero: true, 
                        max: 5,
                        ticks: { callback: function(value) { return value.toFixed(1); } }
                    } 
                }
            }
        });

        // Purchases Distribution Chart
        const ctx2 = document.getElementById('purchasesChart').getContext('2d');
        new Chart(ctx2, {
            type: 'doughnut',
            data: {
                labels: [
                    @foreach($dataCollection as $supplier)
                        '{{ $supplier['supplier_name'] ?? '' }}',
                    @endforeach
                ],
                datasets: [{
                    data: [
                        @foreach($dataCollection as $supplier)
                            {{ $supplier['total_purchases'] ?? 0 }},
                        @endforeach
                    ],
                    backgroundColor: ['#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6', '#EC4899', '#14B8A6', '#F97316', '#06B6D4', '#6366F1'],
                    borderColor: '#fff',
                    borderWidth: 2
                }]
            },
            options: { 
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: { position: 'right' },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return 'المشتريات: ' + context.parsed.toFixed(2);
                            }
                        }
                    }
                }
            }
        });

        // Performance Metrics Chart
        const ctx3 = document.getElementById('performanceChart').getContext('2d');
        new Chart(ctx3, {
            type: 'line',
            data: {
                labels: [
                    @foreach($dataCollection as $supplier)
                        '{{ $supplier['supplier_name'] ?? '' }}',
                    @endforeach
                ],
                datasets: [
                    {
                        label: 'التسليم في الموعد %',
                        data: [
                            @foreach($dataCollection as $supplier)
                                {{ $supplier['on_time_delivery'] ?? 0 }},
                            @endforeach
                        ],
                        borderColor: '#3B82F6',
                        backgroundColor: 'rgba(59, 130, 246, 0.1)',
                        tension: 0.4,
                        fill: true
                    },
                    {
                        label: 'الجودة %',
                        data: [
                            @foreach($dataCollection as $supplier)
                                {{ $supplier['quality_percentage'] ?? 0 }},
                            @endforeach
                        ],
                        borderColor: '#10B981',
                        backgroundColor: 'rgba(16, 185, 129, 0.1)',
                        tension: 0.4,
                        fill: true
                    },
                    {
                        label: 'معدل النمو %',
                        data: [
                            @foreach($dataCollection as $supplier)
                                {{ $supplier['growth_rate'] ?? 0 }},
                            @endforeach
                        ],
                        borderColor: '#F59E0B',
                        backgroundColor: 'rgba(245, 158, 11, 0.1)',
                        tension: 0.4,
                        fill: true
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: { position: 'top' },
                    tooltip: { mode: 'index', intersect: false }
                },
                scales: { 
                    y: { 
                        beginAtZero: true,
                        max: 100,
                        ticks: { callback: function(value) { return value + '%'; } }
                    } 
                }
            }
        });

        // Quality vs Delivery Scatter Chart
        const ctx4 = document.getElementById('qualityDeliveryChart').getContext('2d');
        new Chart(ctx4, {
            type: 'scatter',
            data: {
                datasets: [{
                    label: 'الموردون',
                    data: [
                        @foreach($dataCollection as $supplier)
                            { x: {{ $supplier['on_time_delivery'] ?? 0 }}, y: {{ $supplier['quality_percentage'] ?? 0 }}, label: '{{ $supplier['supplier_name'] ?? '' }}' },
                        @endforeach
                    ],
                    backgroundColor: [
                        @foreach($dataCollection as $supplier)
                            @if(($supplier['overall_rating'] ?? 0) >= 4.5)
                                'rgba(34, 197, 94, 0.8)',
                            @elseif(($supplier['overall_rating'] ?? 0) >= 3)
                                'rgba(234, 179, 8, 0.8)',
                            @else
                                'rgba(239, 68, 68, 0.8)',
                            @endif
                        @endforeach
                    ],
                    borderColor: '#fff',
                    borderWidth: 2,
                    pointRadius: 8
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: { display: true },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return 'التسليم: ' + context.raw.x.toFixed(1) + '%, الجودة: ' + context.raw.y.toFixed(1) + '%';
                            }
                        }
                    }
                },
                scales: {
                    x: { 
                        title: { display: true, text: 'التسليم في الموعد %' },
                        min: 0,
                        max: 100
                    },
                    y: { 
                        title: { display: true, text: 'الجودة %' },
                        min: 0,
                        max: 100
                    }
                }
            }
        });
    @endif
</script>
@endsection
