@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">
        <!-- Page Header -->
        <div class="mb-8">
            <div class="flex items-center justify-between mb-6">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900 mb-2">📊 مقارنة الأسعار</h1>
                    <p class="text-gray-600">مقارنة شاملة لأسعار المنتجات من موردين مختلفين وتحديد أفضل الأسعار</p>
                </div>
                <div class="flex gap-2">
                    <a href="{{ route('reports.purchase.price-comparison', ['export' => true, 'format' => 'excel']) }}" 
                       class="inline-flex items-center px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition">
                        <i class="fas fa-file-excel mr-2"></i> Excel
                    </a>
                    <a href="{{ route('reports.purchase.price-comparison', ['export' => true, 'format' => 'pdf']) }}" 
                       class="inline-flex items-center px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition">
                        <i class="fas fa-file-pdf mr-2"></i> PDF
                    </a>
                    <button onclick="window.print()" class="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition">
                        <i class="fas fa-print mr-2"></i> طباعة
                    </button>
                </div>
            </div>

            <!-- Filters -->
            <div class="bg-white rounded-lg shadow-sm p-4 border border-gray-200">
                <form method="GET" class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">المنتج</label>
                        <select name="product_id" class="w-full rounded-lg border-gray-300 shadow-sm px-3 py-2 border focus:border-blue-500 focus:ring-1 focus:ring-blue-500">
                            <option value="">جميع المنتجات</option>
                            @foreach(\App\Models\Item::where('company_id', auth()->user()->company_id)->get() as $product)
                                <option value="{{ $product->id }}" {{ request('product_id') == $product->id ? 'selected' : '' }}>
                                    {{ $product->name }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="flex items-end gap-2">
                        <button type="submit" class="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition">
                            <i class="fas fa-search mr-1"></i> بحث
                        </button>
                        <a href="{{ route('reports.purchase.price-comparison') }}" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition">
                            <i class="fas fa-redo mr-1"></i>
                        </a>
                    </div>
                </form>
            </div>
        </div>

        <!-- Statistics Cards -->
        @if($data && $data->count() > 0)
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-8">
            <div class="bg-white rounded-lg shadow-md p-6 border-l-4 border-blue-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-600 text-sm font-medium">عدد المنتجات</p>
                        <p class="text-3xl font-bold text-gray-900 mt-2">{{ $data->count() }}</p>
                    </div>
                    <i class="fas fa-box text-blue-500 text-3xl opacity-20"></i>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow-md p-6 border-l-4 border-green-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-600 text-sm font-medium">إجمالي التوفيرات المحتملة</p>
                        <p class="text-3xl font-bold text-green-600 mt-2">
                            {{ number_format($data->sum('potential_savings'), 2) }}
                        </p>
                    </div>
                    <i class="fas fa-money-bill-wave text-green-500 text-3xl opacity-20"></i>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow-md p-6 border-l-4 border-purple-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-600 text-sm font-medium">متوسط فرق الأسعار</p>
                        <p class="text-3xl font-bold text-gray-900 mt-2">
                            {{ number_format($data->avg('price_difference'), 2) }}
                        </p>
                    </div>
                    <i class="fas fa-chart-line text-purple-500 text-3xl opacity-20"></i>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow-md p-6 border-l-4 border-orange-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-600 text-sm font-medium">متوسط عدد الموردين</p>
                        <p class="text-3xl font-bold text-gray-900 mt-2">
                            {{ round($data->avg('suppliers_count')) }}
                        </p>
                    </div>
                    <i class="fas fa-users text-orange-500 text-3xl opacity-20"></i>
                </div>
            </div>
        </div>
        @endif

        <!-- Price Comparison Chart -->
        @if($data && $data->count() > 0)
        <div class="bg-white rounded-xl shadow-lg border border-gray-200 mb-8 p-6">
            <h2 class="text-xl font-bold text-gray-900 mb-6">📈 مقارنة الأسعار بصريّة</h2>
            <canvas id="priceComparisonChart" height="80"></canvas>
        </div>
        @endif

        <!-- Main Table -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden border border-gray-200">
            @if($data && $data->count() > 0)
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gradient-to-r from-gray-800 to-gray-900 text-white">
                            <tr>
                                <th class="px-6 py-4 text-right font-semibold text-sm">#</th>
                                <th class="px-6 py-4 text-right font-semibold text-sm">المنتج</th>
                                <th class="px-6 py-4 text-right font-semibold text-sm">عدد الموردين</th>
                                <th class="px-6 py-4 text-right font-semibold text-sm">أقل سعر</th>
                                <th class="px-6 py-4 text-right font-semibold text-sm">أغلى سعر</th>
                                <th class="px-6 py-4 text-right font-semibold text-sm">فرق الأسعار</th>
                                <th class="px-6 py-4 text-right font-semibold text-sm">متوسط السعر</th>
                                <th class="px-6 py-4 text-right font-semibold text-sm">التوفير المحتمل</th>
                                <th class="px-6 py-4 text-center font-semibold text-sm">الإجراءات</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            @forelse($data as $index => $item)
                            <tr class="hover:bg-blue-50 transition-colors duration-150">
                                <td class="px-6 py-4 text-gray-600 font-medium">{{ $index + 1 }}</td>
                                <td class="px-6 py-4">
                                    <div class="font-semibold text-gray-900">
                                        {{ \App\Models\Item::find($item['product_id'])->name ?? 'N/A' }}
                                    </div>
                                    <div class="text-sm text-gray-500">
                                        ID: {{ $item['product_id'] }}
                                    </div>
                                </td>
                                <td class="px-6 py-4 text-center">
                                    <span class="inline-flex items-center justify-center w-8 h-8 bg-blue-100 text-blue-700 rounded-full font-semibold">
                                        {{ $item['suppliers_count'] }}
                                    </span>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="flex items-center">
                                        <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-semibold bg-green-100 text-green-700">
                                            <i class="fas fa-arrow-down mr-1"></i>
                                            {{ number_format($item['cheapest_price'], 2) }}
                                        </span>
                                    </div>
                                    <div class="text-xs text-gray-500 mt-1">{{ $item['cheapest_supplier'] }}</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="flex items-center">
                                        <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-semibold bg-red-100 text-red-700">
                                            <i class="fas fa-arrow-up mr-1"></i>
                                            {{ number_format($item['most_expensive_price'], 2) }}
                                        </span>
                                    </div>
                                    <div class="text-xs text-gray-500 mt-1">{{ $item['most_expensive_supplier'] }}</div>
                                </td>
                                <td class="px-6 py-4">
                                    <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-semibold bg-yellow-100 text-yellow-700">
                                        {{ number_format($item['price_difference'], 2) }}
                                    </span>
                                </td>
                                <td class="px-6 py-4">
                                    <span class="text-gray-900 font-semibold">
                                        {{ number_format($item['average_price'], 2) }}
                                    </span>
                                </td>
                                <td class="px-6 py-4">
                                    <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-semibold bg-green-100 text-green-700">
                                        <i class="fas fa-piggy-bank mr-1"></i>
                                        {{ number_format($item['potential_savings'], 2) }}
                                    </span>
                                </td>
                                <td class="px-6 py-4 text-center whitespace-nowrap">
                                    <button onclick="showDetails('{{ $item['product_id'] }}')" 
                                            class="inline-flex items-center px-3 py-2 text-blue-600 hover:text-blue-900 transition" 
                                            title="عرض التفاصيل">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                </td>
                            </tr>
                            @empty
                            @endforelse
                        </tbody>
                        <tfoot class="bg-gray-50 border-t-2 border-gray-200">
                            <tr>
                                <td colspan="2" class="px-6 py-4 font-bold text-gray-900">الإجمالي</td>
                                <td class="px-6 py-4 text-center font-bold">{{ $data ? $data->sum('suppliers_count') : 0 }}</td>
                                <td colspan="4" class="px-6 py-4"></td>
                                <td class="px-6 py-4">
                                    <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-bold bg-green-100 text-green-700">
                                        {{ $data ? number_format($data->sum('potential_savings'), 2) : '0.00' }}
                                    </span>
                                </td>
                                <td></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            @else
                <div class="px-6 py-12 text-center">
                    <i class="fas fa-inbox text-gray-400 text-4xl mb-3 block"></i>
                    <p class="text-gray-600 font-medium">لا توجد بيانات مقارنة أسعار</p>
                    <p class="text-gray-500 text-sm mt-1">لا توجد أوامر شراء لمقارنة الأسعار</p>
                </div>
            @endif
        </div>

        <!-- Tips Section -->
        @if($data && $data->count() > 0)
        <div class="mt-8 bg-blue-50 border-l-4 border-blue-500 rounded-lg p-6">
            <h3 class="text-lg font-bold text-blue-900 mb-3">
                <i class="fas fa-lightbulb mr-2"></i> نصائح لتحسين الشراء
            </h3>
            <ul class="space-y-2 text-blue-800">
                <li><i class="fas fa-check-circle mr-2"></i> استخدم الموردين الذين يقدمون أقل الأسعار</li>
                <li><i class="fas fa-check-circle mr-2"></i> توازن بين السعر والجودة عند الاختيار</li>
                <li><i class="fas fa-check-circle mr-2"></i> تفاوض مع الموردين لتحقيق توفيرات أفضل</li>
                <li><i class="fas fa-check-circle mr-2"></i> راقب تغييرات الأسعار بشكل دوري</li>
            </ul>
        </div>
        @endif
    </div>
</div>

<!-- Modal for Supplier Details -->
<div id="supplierModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-lg max-w-2xl w-full max-h-96 overflow-y-auto">
        <div class="p-6 border-b border-gray-200 flex justify-between items-center sticky top-0 bg-white">
            <h3 class="text-xl font-bold">تفاصيل الموردين</h3>
            <button onclick="closeModal()" class="text-gray-500 hover:text-gray-700">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        <div id="modalContent" class="p-6">
            <!-- Content will be loaded via JavaScript -->
        </div>
    </div>
</div>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<script>
    // Price Comparison Chart
    @if($data && $data->count() > 0)
    const ctx = document.getElementById('priceComparisonChart').getContext('2d');
    const chartData = {
        labels: {!! json_encode($data->map(fn($item) => \App\Models\Item::find($item['product_id'])->name ?? 'N/A')->values()->take(10)) !!},
        datasets: [
            {
                label: 'أقل سعر',
                data: {!! json_encode($data->map(fn($item) => $item['cheapest_price'])->values()->take(10)) !!},
                backgroundColor: '#10b981',
                borderColor: '#059669',
                borderWidth: 2,
            },
            {
                label: 'متوسط السعر',
                data: {!! json_encode($data->map(fn($item) => $item['average_price'])->values()->take(10)) !!},
                backgroundColor: '#3b82f6',
                borderColor: '#1d4ed8',
                borderWidth: 2,
            },
            {
                label: 'أغلى سعر',
                data: {!! json_encode($data->map(fn($item) => $item['most_expensive_price'])->values()->take(10)) !!},
                backgroundColor: '#ef4444',
                borderColor: '#dc2626',
                borderWidth: 2,
            }
        ]
    };

    const chart = new Chart(ctx, {
        type: 'bar',
        data: chartData,
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: {
                    position: 'top',
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                }
            }
        }
    });
    @endif

    // Modal Functions
    function showDetails(productId) {
        // Placeholder for details loading
        document.getElementById('supplierModal').classList.remove('hidden');
        document.getElementById('modalContent').innerHTML = '<p class="text-center">جاري تحميل البيانات...</p>';
    }

    function closeModal() {
        document.getElementById('supplierModal').classList.add('hidden');
    }

    // Close modal on outside click
    document.getElementById('supplierModal').addEventListener('click', function(e) {
        if (e.target === this) closeModal();
    });
</script>
@endpush
@endsection