@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 -->
        <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="?export=true&format=excel" class="inline-flex items-center px-4 py-2 bg-green-600 hover:bg-green-700 text-white font-semibold rounded-lg transition-all duration-200">
                        <i class="fas fa-file-excel mr-2"></i>
                        <span>تصدير Excel</span>
                    </a>
                    <a href="?export=true&format=pdf" class="inline-flex items-center px-4 py-2 bg-red-600 hover:bg-red-700 text-white font-semibold rounded-lg transition-all duration-200">
                        <i class="fas fa-file-pdf mr-2"></i>
                        <span>تصدير PDF</span>
                    </a>
                </div>
            </div>
        </div>

        <!-- Success/Error Messages -->
        @if(session('success'))
        <div class="bg-green-50 border-l-4 border-green-500 p-4 mb-6 rounded-r-lg">
            <div class="flex">
                <div class="flex-shrink-0">
                    <i class="fas fa-check-circle text-green-500 text-xl"></i>
                </div>
                <div class="ml-3">
                    <p class="text-green-700 font-medium">{{ session('success') }}</p>
                </div>
            </div>
        </div>
        @endif

        <!-- Statistics Cards -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg: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-2xl font-bold text-gray-900 mt-2">{{ $data->sum('invoice_count') }}</p>
                    </div>
                    <div class="text-3xl text-blue-500 opacity-20">
                        <i class="fas fa-file-invoice-dollar"></i>
                    </div>
                </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-2xl font-bold text-gray-900 mt-2">{{ number_format($data->sum('total_amount'), 2) }}</p>
                    </div>
                    <div class="text-3xl text-green-500 opacity-20">
                        <i class="fas fa-money-bill-wave"></i>
                    </div>
                </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-2xl font-bold text-gray-900 mt-2">{{ number_format($data->sum('paid_amount'), 2) }}</p>
                    </div>
                    <div class="text-3xl text-purple-500 opacity-20">
                        <i class="fas fa-check-double"></i>
                    </div>
                </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-2xl font-bold text-gray-900 mt-2">{{ number_format($data->sum('total_amount') - $data->sum('paid_amount'), 2) }}</p>
                    </div>
                    <div class="text-3xl text-orange-500 opacity-20">
                        <i class="fas fa-hourglass-half"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Chart Section -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
            <!-- Line Chart -->
            <div class="lg:col-span-2 bg-white rounded-xl shadow-lg p-6">
                <h2 class="text-lg font-semibold text-gray-900 mb-4">
                    <i class="fas fa-chart-line text-blue-500 mr-2"></i>
                    اتجاه الفواتير اليومي
                </h2>
                <div class="h-80">
                    <canvas id="invoiceTrendChart"></canvas>
                </div>
            </div>

            <!-- Summary Box -->
            <div class="bg-white rounded-xl shadow-lg p-6">
                <h2 class="text-lg font-semibold text-gray-900 mb-4">
                    <i class="fas fa-info-circle text-green-500 mr-2"></i>
                    ملخص الفترة
                </h2>
                <div class="space-y-3">
                    <div class="p-3 bg-blue-50 rounded-lg">
                        <p class="text-sm text-gray-600">متوسط الفواتير اليومي</p>
                        <p class="text-xl font-bold text-blue-600">{{ round($data->avg('invoice_count'), 1) }}</p>
                    </div>
                    <div class="p-3 bg-green-50 rounded-lg">
                        <p class="text-sm text-gray-600">متوسط المبلغ اليومي</p>
                        <p class="text-xl font-bold text-green-600">{{ number_format($data->avg('total_amount'), 2) }}</p>
                    </div>
                    <div class="p-3 bg-purple-50 rounded-lg">
                        <p class="text-sm text-gray-600">نسبة التحصيل</p>
                        <p class="text-xl font-bold text-purple-600">
                            {{ $data->sum('total_amount') > 0 ? round(($data->sum('paid_amount') / $data->sum('total_amount')) * 100, 1) : 0 }}%
                        </p>
                    </div>
                    <div class="p-3 bg-orange-50 rounded-lg">
                        <p class="text-sm text-gray-600">أيام بدون فواتير</p>
                        <p class="text-xl font-bold text-orange-600">{{ $data->where('invoice_count', 0)->count() }}</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Data Table -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden border border-gray-200">
            <div class="overflow-x-auto">
                <table class="w-full divide-y divide-gray-200">
                    <thead class="bg-gradient-to-r from-gray-800 to-gray-900 text-white sticky top-0">
                        <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-center 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 => $record)
                        <tr class="hover:bg-blue-50 transition-colors duration-150 border-b border-gray-100">
                            <td class="px-6 py-4 text-gray-600 font-medium">{{ $index + 1 }}</td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-blue-100 text-blue-700">
                                    <i class="fas fa-calendar-alt mr-2"></i>
                                    {{ \Carbon\Carbon::parse($record['date'])->format('d/m/Y') }}
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-cyan-100 text-cyan-700">
                                    {{ $record['invoice_count'] }}
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="font-semibold text-green-600">{{ number_format($record['total_amount'], 2) }}</span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="font-semibold text-purple-600">{{ number_format($record['paid_amount'], 2) }}</span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="font-semibold {{ $record['total_amount'] - $record['paid_amount'] > 0 ? 'text-orange-600' : 'text-green-600' }}">
                                    {{ number_format($record['total_amount'] - $record['paid_amount'], 2) }}
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-center">
                                @if($record['total_amount'] > 0)
                                    @php
                                        $percentage = ($record['paid_amount'] / $record['total_amount']) * 100;
                                        $color = $percentage >= 100 ? 'green' : ($percentage >= 50 ? 'yellow' : 'red');
                                    @endphp
                                    <div class="flex items-center justify-center">
                                        <div class="w-16 bg-gray-200 rounded-full h-2 mr-2">
                                            <div class="bg-{{ $color }}-500 h-2 rounded-full" style="width: {{ min($percentage, 100) }}%"></div>
                                        </div>
                                        <span class="text-sm font-semibold text-{{ $color }}-600">{{ round($percentage, 1) }}%</span>
                                    </div>
                                @else
                                    <span class="text-gray-400">-</span>
                                @endif
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-center">
                                @if($record['invoice_count'] == 0)
                                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-700">
                                        <i class="fas fa-minus-circle mr-1"></i>
                                        بدون فواتير
                                    </span>
                                @elseif($record['paid_amount'] >= $record['total_amount'])
                                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-green-100 text-green-700">
                                        <i class="fas fa-check-circle mr-1"></i>
                                        مكتمل
                                    </span>
                                @elseif($record['paid_amount'] > 0)
                                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-yellow-100 text-yellow-700">
                                        <i class="fas fa-clock mr-1"></i>
                                        جزئي
                                    </span>
                                @else
                                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-orange-100 text-orange-700">
                                        <i class="fas fa-hourglass-half mr-1"></i>
                                        معلق
                                    </span>
                                @endif
                            </td>
                        </tr>
                        @empty
                        <tr>
                            <td colspan="8" class="px-6 py-12 text-center">
                                <div class="flex flex-col items-center justify-center">
                                    <i class="fas fa-inbox text-gray-400 text-4xl mb-3"></i>
                                    <p class="text-gray-600 font-medium">لا توجد بيانات حالياً</p>
                                    <p class="text-gray-500 text-sm mt-1">لم يتم العثور على فواتير في الفترة المحددة</p>
                                </div>
                            </td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Footer Info -->
        <div class="mt-8 grid grid-cols-1 md:grid-cols-3 gap-4">
            <div class="bg-blue-50 rounded-lg p-4 border border-blue-200">
                <p class="text-sm text-blue-700"><i class="fas fa-info-circle mr-2"></i> <strong>ملاحظة:</strong> التقرير يعرض حركة الفواتير اليومية للفترة المحددة</p>
            </div>
            <div class="bg-green-50 rounded-lg p-4 border border-green-200">
                <p class="text-sm text-green-700"><i class="fas fa-check-circle mr-2"></i> <strong>تحديث التقرير:</strong> يتم تحديثه تلقائياً يومياً</p>
            </div>
            <div class="bg-purple-50 rounded-lg p-4 border border-purple-200">
                <p class="text-sm text-purple-700"><i class="fas fa-file-export mr-2"></i> <strong>التصدير:</strong> يمكنك تصدير البيانات بصيغة Excel أو PDF</p>
            </div>
        </div>
    </div>
</div>

<!-- Chart.js Script -->
@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Prepare data for chart
        const labels = @json($data->pluck('date'));
        const invoiceCounts = @json($data->pluck('invoice_count'));
        const totalAmounts = @json($data->pluck('total_amount'));
        const paidAmounts = @json($data->pluck('paid_amount'));

        // Format dates to readable format
        const formattedLabels = labels.map(date => {
            return new Date(date).toLocaleDateString('ar-SA', {
                year: 'numeric',
                month: 'short',
                day: 'numeric'
            });
        });

        // Create chart
        const ctx = document.getElementById('invoiceTrendChart').getContext('2d');
        new Chart(ctx, {
            type: 'line',
            data: {
                labels: formattedLabels,
                datasets: [
                    {
                        label: 'عدد الفواتير',
                        data: invoiceCounts,
                        borderColor: 'rgb(59, 130, 246)',
                        backgroundColor: 'rgba(59, 130, 246, 0.1)',
                        tension: 0.4,
                        fill: true,
                        pointRadius: 4,
                        pointBackgroundColor: 'rgb(59, 130, 246)',
                        pointBorderColor: '#fff',
                        pointBorderWidth: 2,
                        yAxisID: 'y'
                    },
                    {
                        label: 'المبلغ الإجمالي',
                        data: totalAmounts,
                        borderColor: 'rgb(34, 197, 94)',
                        backgroundColor: 'rgba(34, 197, 94, 0.1)',
                        tension: 0.4,
                        fill: true,
                        pointRadius: 4,
                        pointBackgroundColor: 'rgb(34, 197, 94)',
                        pointBorderColor: '#fff',
                        pointBorderWidth: 2,
                        yAxisID: 'y1'
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    mode: 'index',
                    intersect: false,
                },
                plugins: {
                    legend: {
                        display: true,
                        position: 'top',
                        labels: {
                            usePointStyle: true,
                            padding: 15,
                            font: {
                                size: 12,
                                weight: 'bold'
                            }
                        }
                    }
                },
                scales: {
                    y: {
                        type: 'linear',
                        display: true,
                        position: 'left',
                        title: {
                            display: true,
                            text: 'عدد الفواتير',
                            font: {
                                size: 12,
                                weight: 'bold'
                            }
                        }
                    },
                    y1: {
                        type: 'linear',
                        display: true,
                        position: 'right',
                        title: {
                            display: true,
                            text: 'المبلغ',
                            font: {
                                size: 12,
                                weight: 'bold'
                            }
                        },
                        grid: {
                            drawOnChartArea: false,
                        }
                    }
                }
            }
        });
    });
</script>
@endpush
@endsection