@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">
        <!-- رأس الصفحة -->
        <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">
                        <i class="fas fa-file-invoice-dollar text-blue-600 mr-3"></i>
                        الذمم الدائنة
                    </h1>
                    <p class="text-gray-600">تقرير مفصل عن المبالغ المستحقة للموردين</p>
                </div>
            </div>
        </div>

        <!-- رسائل النجاح والخطأ -->
        @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="mr-3">
                        <p class="text-green-700 font-medium">{{ session('success') }}</p>
                    </div>
                </div>
            </div>
        @endif

        <!-- الإحصائيات الرئيسية -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
            <!-- إجمالي الذمم الدائنة -->
            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-red-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['total_payable'] ?? 0, 2) }}
                        </p>
                    </div>
                    <div class="bg-red-100 rounded-full p-3">
                        <i class="fas fa-money-bill-wave text-red-600 text-2xl"></i>
                    </div>
                </div>
            </div>

            <!-- عدد الموردين -->
            <div class="bg-white rounded-xl shadow-lg 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['supplier_count'] ?? 0 }}
                        </p>
                    </div>
                    <div class="bg-blue-100 rounded-full p-3">
                        <i class="fas fa-users text-blue-600 text-2xl"></i>
                    </div>
                </div>
            </div>

            <!-- متوسط الدين -->
            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-yellow-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['average_debt'] ?? 0, 2) }}
                        </p>
                    </div>
                    <div class="bg-yellow-100 rounded-full p-3">
                        <i class="fas fa-chart-pie text-yellow-600 text-2xl"></i>
                    </div>
                </div>
            </div>

            <!-- أقدم ديون -->
            <div class="bg-white rounded-xl shadow-lg 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">
                            {{ $data['most_overdue'] ?? 0 }}
                        </p>
                    </div>
                    <div class="bg-orange-100 rounded-full p-3">
                        <i class="fas fa-hourglass-end text-orange-600 text-2xl"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- جدول الموردين والديون -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden border border-gray-200 mb-8">
            <div class="bg-gradient-to-r from-gray-800 to-gray-900 px-6 py-4">
                <h2 class="text-xl font-semibold text-white flex items-center">
                    <i class="fas fa-list mr-3"></i>
                    الموردين والذمم المستحقة
                </h2>
            </div>

            @if(isset($data['by_supplier']) && count($data['by_supplier']) > 0)
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-50 border-b border-gray-200">
                            <tr>
                                <th class="px-6 py-4 text-right font-semibold text-sm text-gray-700">#</th>
                                <th class="px-6 py-4 text-right font-semibold text-sm text-gray-700">المورد</th>
                                <th class="px-6 py-4 text-right font-semibold text-sm text-gray-700">المبلغ المستحق</th>
                                <th class="px-6 py-4 text-right font-semibold text-sm text-gray-700">عدد الفواتير</th>
                                <th class="px-6 py-4 text-right font-semibold text-sm text-gray-700">أقدم فاتورة</th>
                                <th class="px-6 py-4 text-right font-semibold text-sm text-gray-700">أيام التأخير</th>
                                <th class="px-6 py-4 text-center font-semibold text-sm text-gray-700">الحالة</th>
                                <th class="px-6 py-4 text-center font-semibold text-sm text-gray-700">الإجراء المقترح</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            @foreach($data['by_supplier'] as $index => $supplier)
                                <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">{{ $supplier['supplier_name'] }}</div>
                                        <div class="text-sm text-gray-500">ID: {{ $supplier['supplier_id'] }}</div>
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="font-bold text-red-600">{{ number_format($supplier['total_debt'], 2) }}</div>
                                    </td>
                                    <td class="px-6 py-4 text-center">
                                        <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-blue-100 text-blue-700">
                                            {{ $supplier['invoice_count'] }}
                                        </span>
                                    </td>
                                    <td class="px-6 py-4">
                                        @if($supplier['oldest_invoice_date'])
                                            <div class="text-sm">{{ \Carbon\Carbon::parse($supplier['oldest_invoice_date'])->format('Y-m-d') }}</div>
                                            <div class="text-xs text-gray-500">{{ \Carbon\Carbon::parse($supplier['oldest_invoice_date'])->diffForHumans() }}</div>
                                        @else
                                            <span class="text-gray-400">-</span>
                                        @endif
                                    </td>
                                    <td class="px-6 py-4 text-center">
                                        @if($supplier['days_overdue'] > 0)
                                            <div class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-red-100 text-red-700">
                                                <i class="fas fa-exclamation-triangle mr-1"></i>
                                                {{ $supplier['days_overdue'] }} يوم
                                            </div>
                                        @else
                                            <span class="text-gray-400">-</span>
                                        @endif
                                    </td>
                                    <td class="px-6 py-4 text-center">
                                        @if($supplier['days_overdue'] > 30)
                                            <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-red-100 text-red-700">
                                                <i class="fas fa-times-circle mr-1"></i>
                                                متأخر جداً
                                            </span>
                                        @elseif($supplier['days_overdue'] > 0)
                                            <span class="inline-flex items-center px-3 py-1 rounded-full text-sm 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-sm font-medium bg-green-100 text-green-700">
                                                <i class="fas fa-check-circle mr-1"></i>
                                                عادي
                                            </span>
                                        @endif
                                    </td>
                                    <td class="px-6 py-4 text-center">
                                        @if($supplier['action'] === 'Immediate')
                                            <button type="button" class="inline-flex items-center px-3 py-2 rounded-lg bg-red-100 text-red-600 hover:bg-red-200 transition-all duration-150 text-sm font-medium">
                                                <i class="fas fa-phone mr-1"></i>
                                                اتصال فوري
                                            </button>
                                        @elseif($supplier['action'] === 'Urgent')
                                            <button type="button" class="inline-flex items-center px-3 py-2 rounded-lg bg-yellow-100 text-yellow-600 hover:bg-yellow-200 transition-all duration-150 text-sm font-medium">
                                                <i class="fas fa-exclamation mr-1"></i>
                                                عاجل
                                            </button>
                                        @else
                                            <button type="button" class="inline-flex items-center px-3 py-2 rounded-lg bg-blue-100 text-blue-600 hover:bg-blue-200 transition-all duration-150 text-sm font-medium">
                                                <i class="fas fa-envelope mr-1"></i>
                                                تذكير
                                            </button>
                                        @endif
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                        <tfoot class="bg-gray-50 border-t border-gray-200">
                            <tr>
                                <td colspan="2" class="px-6 py-4 font-bold text-gray-900">الإجمالي</td>
                                <td class="px-6 py-4 font-bold text-red-600">
                                    {{ number_format($data['total_payable'], 2) }}
                                </td>
                                <td class="px-6 py-4 font-bold text-center">
                                    {{ $data['by_supplier']->sum('invoice_count') ?? 0 }}
                                </td>
                                <td colspan="4"></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            @else
                <div class="px-6 py-12 text-center">
                    <div class="flex flex-col items-center justify-center">
                        <i class="fas fa-check-circle text-green-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>
                </div>
            @endif
        </div>

        <!-- رسوم بيانية -->
        @if(isset($data['by_supplier']) && count($data['by_supplier']) > 0)
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
                <!-- رسم بياني للديون الكبرى -->
                <div class="bg-white rounded-xl shadow-lg p-6 border border-gray-200">
                    <h3 class="text-lg font-semibold text-gray-900 mb-4 flex items-center">
                        <i class="fas fa-chart-bar text-blue-600 mr-2"></i>
                        أكبر الديون
                    </h3>
                    <canvas id="topDebtorsChart" height="300"></canvas>
                </div>

                <!-- رسم بياني لتوزيع الديون -->
                <div class="bg-white rounded-xl shadow-lg p-6 border border-gray-200">
                    <h3 class="text-lg font-semibold text-gray-900 mb-4 flex items-center">
                        <i class="fas fa-chart-pie text-green-600 mr-2"></i>
                        توزيع الديون
                    </h3>
                    <canvas id="debtDistributionChart" height="300"></canvas>
                </div>
            </div>
        @endif

        <!-- معلومات إضافية -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
            <!-- الديون المتأخرة -->
            <div class="bg-white rounded-xl shadow-lg p-6 border border-gray-200">
                <h3 class="text-lg font-semibold text-gray-900 mb-4 flex items-center">
                    <i class="fas fa-exclamation-triangle text-red-600 mr-2"></i>
                    الديون المتأخرة
                </h3>
                @php
                    $overdueCount = isset($data['by_supplier']) ? $data['by_supplier']->where('days_overdue', '>', 0)->count() : 0;
                    $overdueAmount = isset($data['by_supplier']) ? $data['by_supplier']->where('days_overdue', '>', 0)->sum('total_debt') : 0;
                @endphp
                <div class="space-y-2">
                    <div class="flex justify-between items-center">
                        <span class="text-gray-600">عدد الموردين المتأخرين:</span>
                        <span class="font-bold text-red-600">{{ $overdueCount }}</span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-gray-600">المبلغ المتأخر:</span>
                        <span class="font-bold text-red-600">{{ number_format($overdueAmount, 2) }}</span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-gray-600">نسبة الديون المتأخرة:</span>
                        <span class="font-bold text-red-600">
                            @php
                                $percentage = $data['total_payable'] > 0 ? ($overdueAmount / $data['total_payable']) * 100 : 0;
                            @endphp
                            {{ round($percentage, 2) }}%
                        </span>
                    </div>
                </div>
            </div>

            <!-- الديون الحالية -->
            <div class="bg-white rounded-xl shadow-lg p-6 border border-gray-200">
                <h3 class="text-lg font-semibold text-gray-900 mb-4 flex items-center">
                    <i class="fas fa-calendar-check text-yellow-600 mr-2"></i>
                    الديون الحالية
                </h3>
                @php
                    $currentCount = isset($data['by_supplier']) ? $data['by_supplier']->where('days_overdue', '<=', 0)->count() : 0;
                    $currentAmount = isset($data['by_supplier']) ? $data['by_supplier']->where('days_overdue', '<=', 0)->sum('total_debt') : 0;
                @endphp
                <div class="space-y-2">
                    <div class="flex justify-between items-center">
                        <span class="text-gray-600">عدد الموردين:</span>
                        <span class="font-bold text-yellow-600">{{ $currentCount }}</span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-gray-600">المبلغ الحالي:</span>
                        <span class="font-bold text-yellow-600">{{ number_format($currentAmount, 2) }}</span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-gray-600">نسبة الديون الحالية:</span>
                        <span class="font-bold text-yellow-600">
                            @php
                                $currentPercentage = $data['total_payable'] > 0 ? ($currentAmount / $data['total_payable']) * 100 : 0;
                            @endphp
                            {{ round($currentPercentage, 2) }}%
                        </span>
                    </div>
                </div>
            </div>

            <!-- ملخص التوصيات -->
            <div class="bg-white rounded-xl shadow-lg p-6 border border-gray-200">
                <h3 class="text-lg font-semibold text-gray-900 mb-4 flex items-center">
                    <i class="fas fa-lightbulb text-blue-600 mr-2"></i>
                    التوصيات
                </h3>
                <div class="space-y-2 text-sm">
                    <div class="flex items-start">
                        <i class="fas fa-check text-green-600 mt-1 mr-2 flex-shrink-0"></i>
                        <span class="text-gray-600">
                            @if($overdueCount > 0)
                                يوجد {{ $overdueCount }} موردين متأخرين يحتاجون متابعة فورية
                            @else
                                جميع الحسابات محدثة - وضع جيد
                            @endif
                        </span>
                    </div>
                    <div class="flex items-start">
                        <i class="fas fa-check text-green-600 mt-1 mr-2 flex-shrink-0"></i>
                        <span class="text-gray-600">إجمالي الديون: {{ number_format($data['total_payable'], 2) }}</span>
                    </div>
                    <div class="flex items-start">
                        <i class="fas fa-check text-green-600 mt-1 mr-2 flex-shrink-0"></i>
                        <span class="text-gray-600">متوسط سداد: {{ round($currentPercentage, 1) }}% على الموعد</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- خيارات التصدير -->
        <div class="bg-white rounded-xl shadow-lg p-6 border border-gray-200">
            <h3 class="text-lg font-semibold text-gray-900 mb-4 flex items-center">
                <i class="fas fa-download text-blue-600 mr-2"></i>
                خيارات التصدير والطباعة
            </h3>
            <div class="flex flex-wrap gap-3">
                <a href="{{ route('reports.purchase.accounts-payable', ['export' => true, 'format' => 'pdf']) }}" 
                   class="inline-flex items-center px-4 py-2 bg-red-100 text-red-600 hover:bg-red-200 rounded-lg font-medium transition-all duration-150">
                    <i class="fas fa-file-pdf mr-2"></i>
                    تصدير PDF
                </a>
                <a href="{{ route('reports.purchase.accounts-payable', ['export' => true, 'format' => 'excel']) }}" 
                   class="inline-flex items-center px-4 py-2 bg-green-100 text-green-600 hover:bg-green-200 rounded-lg font-medium transition-all duration-150">
                    <i class="fas fa-file-excel mr-2"></i>
                    تصدير Excel
                </a>
                <button onclick="window.print()" 
                   class="inline-flex items-center px-4 py-2 bg-blue-100 text-blue-600 hover:bg-blue-200 rounded-lg font-medium transition-all duration-150">
                    <i class="fas fa-print mr-2"></i>
                    طباعة
                </button>
            </div>
        </div>
    </div>
</div>

@push('scripts')
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // بيانات الموردين
            const suppliers = @json(isset($data['by_supplier']) ? $data['by_supplier'] : []);
            
            if (suppliers.length > 0) {
                // أكبر الديون
                const topSuppliers = suppliers.slice(0, 10);
                const ctx1 = document.getElementById('topDebtorsChart');
                if (ctx1) {
                    new Chart(ctx1, {
                        type: 'bar',
                        data: {
                            labels: topSuppliers.map(s => s.supplier_name),
                            datasets: [{
                                label: 'المبلغ المستحق',
                                data: topSuppliers.map(s => s.total_debt),
                                backgroundColor: [
                                    'rgba(255, 99, 132, 0.8)',
                                    'rgba(255, 159, 64, 0.8)',
                                    'rgba(255, 205, 86, 0.8)',
                                    'rgba(75, 192, 192, 0.8)',
                                    'rgba(54, 162, 235, 0.8)',
                                    'rgba(153, 102, 255, 0.8)',
                                    'rgba(255, 99, 132, 0.8)',
                                    'rgba(255, 159, 64, 0.8)',
                                    'rgba(255, 205, 86, 0.8)',
                                    'rgba(75, 192, 192, 0.8)'
                                ],
                                borderRadius: 8,
                                borderColor: 'rgba(200, 200, 200, 1)',
                                borderWidth: 1
                            }]
                        },
                        options: {
                            indexAxis: 'y',
                            responsive: true,
                            plugins: {
                                legend: { display: false }
                            },
                            scales: {
                                x: {
                                    beginAtZero: true,
                                    ticks: {
                                        callback: function(value) {
                                            return value.toLocaleString() + ' ر.س';
                                        }
                                    }
                                }
                            }
                        }
                    });
                }

                // توزيع الديون
                const ctx2 = document.getElementById('debtDistributionChart');
                if (ctx2) {
                    new Chart(ctx2, {
                        type: 'doughnut',
                        data: {
                            labels: topSuppliers.map(s => s.supplier_name),
                            datasets: [{
                                data: topSuppliers.map(s => s.total_debt),
                                backgroundColor: [
                                    'rgba(255, 99, 132, 0.8)',
                                    'rgba(255, 159, 64, 0.8)',
                                    'rgba(255, 205, 86, 0.8)',
                                    'rgba(75, 192, 192, 0.8)',
                                    'rgba(54, 162, 235, 0.8)',
                                    'rgba(153, 102, 255, 0.8)',
                                    'rgba(255, 99, 132, 0.8)',
                                    'rgba(255, 159, 64, 0.8)',
                                    'rgba(255, 205, 86, 0.8)',
                                    'rgba(75, 192, 192, 0.8)'
                                ],
                                borderColor: '#fff',
                                borderWidth: 2
                            }]
                        },
                        options: {
                            responsive: true,
                            plugins: {
                                legend: {
                                    position: 'bottom',
                                    labels: {
                                        padding: 15,
                                        font: { size: 12 }
                                    }
                                }
                            }
                        }
                    });
                }
            }
        });
    </script>
@endpush
@endsection