@extends('layouts.app')

@section('title', 'تفاصيل فاتورة الشراء')

@section('content')
@php
    $invoice   = $data['invoice'] ?? null;
    $items     = $data['items'] ?? collect();
    $payments  = $data['payments'] ?? collect();
    $remaining = $data['remaining_balance'] ?? (($invoice->total_amount ?? 0) - ($invoice->paid_amount ?? 0));

    $paymentStatus = $invoice->payment_status ?? 'pending';
    $approvalStatus = $invoice->status ?? 'pending';

    $paymentStatusMap = [
        'paid'    => ['label' => 'مدفوعة',        'class' => 'bg-green-100 text-green-700',  'dot' => 'bg-green-500'],
        'partial' => ['label' => 'مدفوعة جزئياً', 'class' => 'bg-yellow-100 text-yellow-700', 'dot' => 'bg-yellow-500'],
        'overdue' => ['label' => 'متأخرة',         'class' => 'bg-red-100 text-red-700',     'dot' => 'bg-red-500'],
        'sent'    => ['label' => 'مُرسلة',         'class' => 'bg-blue-100 text-blue-700',   'dot' => 'bg-blue-500'],
        'approved'=> ['label' => 'معتمدة',         'class' => 'bg-green-100 text-green-700', 'dot' => 'bg-green-500'],
        'pending' => ['label' => 'معلقة',          'class' => 'bg-gray-100 text-gray-700',   'dot' => 'bg-gray-500'],
    ];
    $paymentBadge = $paymentStatusMap[$paymentStatus] ?? ['label' => ucfirst($paymentStatus ?: 'معلقة'), 'class' => 'bg-gray-100 text-gray-700', 'dot' => 'bg-gray-500'];

    $approvalMap = [
        'approved'  => ['label' => 'معتمدة',  'class' => 'bg-green-100 text-green-700'],
        'rejected'  => ['label' => 'مرفوضة',  'class' => 'bg-red-100 text-red-700'],
        'cancelled' => ['label' => 'ملغاة',   'class' => 'bg-red-100 text-red-700'],
        'draft'     => ['label' => 'مسودة',   'class' => 'bg-gray-100 text-gray-700'],
        'pending'   => ['label' => 'قيد المراجعة', 'class' => 'bg-yellow-100 text-yellow-700'],
    ];
    $approvalBadge = $approvalMap[$approvalStatus] ?? ['label' => ucfirst($approvalStatus ?: '-'), 'class' => 'bg-gray-100 text-gray-700'];
@endphp

<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">

        @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

        @if(session('error'))
        <div class="bg-red-50 border-l-4 border-red-500 p-4 mb-6 rounded-r-lg">
            <div class="flex">
                <div class="flex-shrink-0"><i class="fas fa-exclamation-circle text-red-500 text-xl"></i></div>
                <div class="mr-3"><p class="text-red-700 font-medium">{{ session('error') }}</p></div>
            </div>
        </div>
        @endif

        <!-- Page Header -->
        <div class="mb-8 flex items-center justify-between">
            <div>
                <h1 class="text-3xl font-bold text-gray-900 mb-2">
                    <i class="fas fa-file-invoice text-blue-600 ml-2"></i>
                    تفاصيل فاتورة الشراء
                </h1>
                <p class="text-gray-600">
                    رقم الفاتورة:
                    <span class="font-semibold text-gray-900">{{ $invoice->invoice_number ?? '-' }}</span>
                </p>
            </div>
            <div class="flex gap-3 flex-wrap">
                <a href="{{ route('reports.purchase.invoice-list') }}"
                   class="inline-flex items-center px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-all">
                    <i class="fas fa-arrow-right ml-2"></i> عودة للقائمة
                </a>
                <button type="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-all">
                    <i class="fas fa-print ml-2"></i> طباعة
                </button>
                <a href="{{ url()->current() }}?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-all">
                    <i class="fas fa-file-pdf ml-2"></i> PDF
                </a>
                <a href="{{ url()->current() }}?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-all">
                    <i class="fas fa-download ml-2"></i> Excel
                </a>
            </div>
        </div>

        <!-- Statistics Cards -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
            <div class="bg-white rounded-lg shadow p-4 border-l-4 border-blue-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-600 text-sm">إجمالي الفاتورة</p>
                        <p class="text-2xl font-bold text-gray-900">{{ number_format($invoice->total_amount ?? 0, 2) }} ر.س</p>
                    </div>
                    <i class="fas fa-money-bill-wave text-3xl text-blue-200"></i>
                </div>
            </div>
            <div class="bg-white rounded-lg shadow p-4 border-l-4 border-green-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-600 text-sm">المدفوع</p>
                        <p class="text-2xl font-bold text-green-600">{{ number_format($invoice->paid_amount ?? 0, 2) }} ر.س</p>
                    </div>
                    <i class="fas fa-check-circle text-3xl text-green-200"></i>
                </div>
            </div>
            <div class="bg-white rounded-lg shadow p-4 border-l-4 border-orange-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-600 text-sm">المتبقي</p>
                        <p class="text-2xl font-bold text-orange-600">{{ number_format($remaining, 2) }} ر.س</p>
                    </div>
                    <i class="fas fa-hourglass-end text-3xl text-orange-200"></i>
                </div>
            </div>
            <div class="bg-white rounded-lg shadow p-4 border-l-4 border-purple-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-600 text-sm">عدد البنود</p>
                        <p class="text-2xl font-bold text-gray-900">{{ $items->count() }}</p>
                    </div>
                    <i class="fas fa-list text-3xl text-purple-200"></i>
                </div>
            </div>
        </div>

        <!-- Invoice Info + Financial Summary -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
            <!-- Invoice Basic Info -->
            <div class="space-y-4">
                <div class="bg-white rounded-xl shadow-lg border border-gray-200 p-6">
                    <h2 class="text-lg font-bold text-gray-900 mb-4 border-b border-gray-200 pb-2">
                        <i class="fas fa-info-circle text-blue-600 ml-2"></i>معلومات الفاتورة
                    </h2>
                    <div class="divide-y divide-gray-100">
                        <div class="flex justify-between py-2">
                            <span class="text-gray-600">رقم الفاتورة</span>
                            <span class="font-semibold text-gray-900">{{ $invoice->invoice_number ?? '-' }}</span>
                        </div>
                        <div class="flex justify-between py-2">
                            <span class="text-gray-600">تاريخ الإصدار</span>
                            <span class="font-semibold text-gray-900">
                                {{ $invoice->invoice_date ? $invoice->invoice_date->format('Y-m-d') : '-' }}
                            </span>
                        </div>
                        <div class="flex justify-between py-2">
                            <span class="text-gray-600">تاريخ الاستحقاق</span>
                            <span class="font-semibold text-gray-900">
                                {{ $invoice->due_date ? $invoice->due_date->format('Y-m-d') : '-' }}
                            </span>
                        </div>
                        <div class="flex justify-between py-2">
                            <span class="text-gray-600">المستودع</span>
                            <span class="font-semibold text-gray-900">{{ $invoice->warehouse->name ?? '—' }}</span>
                        </div>
                        <div class="flex justify-between py-2">
                            <span class="text-gray-600">حالة الاعتماد</span>
                            <span>
                                <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium {{ $approvalBadge['class'] }}">
                                    <span class="w-2 h-2 bg-current rounded-full ml-2 opacity-70"></span>
                                    {{ $approvalBadge['label'] }}
                                </span>
                            </span>
                        </div>
                        <div class="flex justify-between py-2">
                            <span class="text-gray-600">حالة الدفع</span>
                            <span>
                                <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium {{ $paymentBadge['class'] }}">
                                    <span class="w-2 h-2 {{ $paymentBadge['dot'] }} rounded-full ml-2"></span>
                                    {{ $paymentBadge['label'] }}
                                </span>
                            </span>
                        </div>
                    </div>
                </div>

                <!-- Supplier Info -->
                <div class="bg-white rounded-xl shadow-lg border border-gray-200 p-6">
                    <h2 class="text-lg font-bold text-gray-900 mb-4 border-b border-gray-200 pb-2">
                        <i class="fas fa-truck text-blue-600 ml-2"></i>المورد
                    </h2>
                    <div class="divide-y divide-gray-100">
                        <div class="flex justify-between py-2">
                            <span class="text-gray-600">الاسم</span>
                            <span class="font-semibold text-gray-900">{{ $invoice->supplier->name ?? '—' }}</span>
                        </div>
                        @if(!empty($invoice->supplier->code ?? null))
                        <div class="flex justify-between py-2">
                            <span class="text-gray-600">كود المورد</span>
                            <span class="font-semibold text-gray-900">{{ $invoice->supplier->code }}</span>
                        </div>
                        @endif
                        @if(!empty($invoice->supplier->phone ?? null))
                        <div class="flex justify-between py-2">
                            <span class="text-gray-600">الهاتف</span>
                            <span class="font-semibold text-gray-900">{{ $invoice->supplier->phone }}</span>
                        </div>
                        @endif
                        @if(!empty($invoice->supplier->email ?? null))
                        <div class="flex justify-between py-2">
                            <span class="text-gray-600">البريد الإلكتروني</span>
                            <span class="font-semibold text-gray-900">{{ $invoice->supplier->email }}</span>
                        </div>
                        @endif
                        @if(!empty($invoice->supplier->city ?? null))
                        <div class="flex justify-between py-2">
                            <span class="text-gray-600">المدينة</span>
                            <span class="font-semibold text-gray-900">{{ $invoice->supplier->city }}</span>
                        </div>
                        @endif
                    </div>
                </div>
            </div>

            <!-- Financial Summary -->
            <div>
                <div class="bg-white rounded-xl shadow-lg border border-gray-200 p-6">
                    <h2 class="text-lg font-bold text-gray-900 mb-4 border-b border-gray-200 pb-2">
                        <i class="fas fa-calculator text-blue-600 ml-2"></i>الملخص المالي
                    </h2>
                    <div class="space-y-3">
                        <div class="flex justify-between p-3 bg-gray-50 rounded">
                            <span class="text-gray-600">المجموع الفرعي</span>
                            <span class="font-semibold text-gray-900">{{ number_format($invoice->subtotal ?? 0, 2) }} ر.س</span>
                        </div>
                        <div class="flex justify-between p-3 bg-gray-50 rounded">
                            <span class="text-gray-600">قيمة الضريبة</span>
                            <span class="font-semibold text-purple-600">{{ number_format($invoice->tax_amount ?? 0, 2) }} ر.س</span>
                        </div>
                        <div class="flex justify-between p-4 bg-blue-100 rounded-lg border-2 border-blue-300">
                            <span class="text-blue-900 font-bold">الإجمالي</span>
                            <span class="font-bold text-blue-900 text-xl">{{ number_format($invoice->total_amount ?? 0, 2) }} ر.س</span>
                        </div>
                        @php
                            $paid = (float) ($invoice->paid_amount ?? 0);
                            $total = (float) ($invoice->total_amount ?? 0);
                            $paidPct = $total > 0 ? min(100, round(($paid / $total) * 100, 1)) : 0;
                        @endphp
                        <div class="flex justify-between p-3 bg-gray-50 rounded">
                            <span class="text-gray-600">المدفوع</span>
                            <span class="font-semibold text-green-600">
                                {{ number_format($paid, 2) }} ر.س
                                <span class="text-xs text-gray-500">({{ $paidPct }}%)</span>
                            </span>
                        </div>
                        <div class="flex justify-between p-4 bg-orange-100 rounded-lg border-2 border-orange-300">
                            <span class="text-orange-900 font-bold">المتبقي</span>
                            <span class="font-bold text-orange-900 text-xl">{{ number_format($remaining, 2) }} ر.س</span>
                        </div>

                        <!-- Progress Bar -->
                        <div class="mt-2">
                            <div class="flex justify-between text-xs text-gray-500 mb-1">
                                <span>نسبة السداد</span>
                                <span>{{ $paidPct }}%</span>
                            </div>
                            <div class="w-full bg-gray-200 rounded-full h-2.5 overflow-hidden">
                                <div class="bg-green-500 h-2.5 rounded-full transition-all" style="width: {{ $paidPct }}%"></div>
                            </div>
                        </div>
                    </div>
                </div>

                @if($invoice && !empty($invoice->notes))
                <div class="bg-white rounded-xl shadow-lg border border-gray-200 p-6 mt-4">
                    <h2 class="text-lg font-bold text-gray-900 mb-3 border-b border-gray-200 pb-2">
                        <i class="fas fa-sticky-note text-blue-600 ml-2"></i>ملاحظات
                    </h2>
                    <p class="text-gray-700 leading-relaxed whitespace-pre-line">{{ $invoice->notes }}</p>
                </div>
                @endif
            </div>
        </div>

        <!-- Line Items Table -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden border border-gray-200 mb-6">
            <div class="px-6 py-4 bg-gradient-to-r from-gray-800 to-gray-900 text-white border-b border-gray-200">
                <h2 class="text-lg font-semibold">
                    <i class="fas fa-list-ul ml-2"></i>بنود الفاتورة
                    <span class="text-sm text-gray-300 mr-2">({{ $items->count() }} بند)</span>
                </h2>
            </div>
            <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-3 text-right font-semibold text-sm text-gray-700">#</th>
                            <th class="px-6 py-3 text-right font-semibold text-sm text-gray-700">الصنف</th>
                            <th class="px-6 py-3 text-right font-semibold text-sm text-gray-700">الوصف</th>
                            <th class="px-6 py-3 text-right font-semibold text-sm text-gray-700">الكمية</th>
                            <th class="px-6 py-3 text-right font-semibold text-sm text-gray-700">سعر الوحدة</th>
                            <th class="px-6 py-3 text-right font-semibold text-sm text-gray-700">الخصم</th>
                            <th class="px-6 py-3 text-right font-semibold text-sm text-gray-700">الضريبة</th>
                            <th class="px-6 py-3 text-right font-semibold text-sm text-gray-700">الإجمالي</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-200">
                        @forelse($items as $item)
                        <tr class="hover:bg-blue-50 transition-colors duration-150">
                            <td class="px-6 py-3 text-gray-600">{{ $loop->iteration }}</td>
                            <td class="px-6 py-3 font-medium text-gray-900">
                                {{ $item->item->name ?? ($item->item_id ? '#'.$item->item_id : '—') }}
                            </td>
                            <td class="px-6 py-3 text-gray-700">{{ $item->description ?: '—' }}</td>
                            <td class="px-6 py-3 text-gray-700">{{ number_format($item->quantity ?? 0, 2) }}</td>
                            <td class="px-6 py-3 text-gray-700">{{ number_format($item->unit_price ?? 0, 2) }}</td>
                            <td class="px-6 py-3 text-orange-600">{{ number_format($item->discount_amount ?? 0, 2) }}</td>
                            <td class="px-6 py-3 text-purple-600">{{ number_format($item->tax_amount ?? 0, 2) }}</td>
                            <td class="px-6 py-3 font-semibold text-gray-900">{{ number_format($item->line_total ?? 0, 2) }}</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>
                                </div>
                            </td>
                        </tr>
                        @endforelse
                    </tbody>
                    @if($items->count() > 0)
                    <tfoot class="bg-gray-50 border-t-2 border-gray-200">
                        <tr>
                            <td colspan="7" class="px-6 py-4 text-left font-semibold text-gray-900">إجمالي البنود</td>
                            <td class="px-6 py-4 font-bold text-blue-900 text-lg">
                                {{ number_format($items->sum('line_total'), 2) }} ر.س
                            </td>
                        </tr>
                    </tfoot>
                    @endif
                </table>
            </div>
        </div>

        <!-- Payment History -->
        @if($payments->count() > 0)
        <div class="bg-white rounded-xl shadow-lg overflow-hidden border border-gray-200 mb-6">
            <div class="px-6 py-4 bg-gradient-to-r from-green-800 to-green-900 text-white border-b border-gray-200">
                <h2 class="text-lg font-semibold">
                    <i class="fas fa-money-check-alt ml-2"></i>سجل الدفعات
                    <span class="text-sm text-green-200 mr-2">({{ $payments->count() }} دفعة)</span>
                </h2>
            </div>
            <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-3 text-right font-semibold text-sm text-gray-700">#</th>
                            <th class="px-6 py-3 text-right font-semibold text-sm text-gray-700">رقم الدفعة</th>
                            <th class="px-6 py-3 text-right font-semibold text-sm text-gray-700">تاريخ الدفع</th>
                            <th class="px-6 py-3 text-right font-semibold text-sm text-gray-700">طريقة الدفع</th>
                            <th class="px-6 py-3 text-right font-semibold text-sm text-gray-700">المرجع</th>
                            <th class="px-6 py-3 text-right font-semibold text-sm text-gray-700">المبلغ</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-200">
                        @foreach($payments as $payment)
                        <tr class="hover:bg-green-50 transition-colors duration-150">
                            <td class="px-6 py-3 text-gray-600">{{ $loop->iteration }}</td>
                            <td class="px-6 py-3 font-medium text-gray-900">{{ $payment->payment_number ?? '—' }}</td>
                            <td class="px-6 py-3 text-gray-700">
                                {{ $payment->payment_date ? $payment->payment_date->format('Y-m-d') : '—' }}
                            </td>
                            <td class="px-6 py-3">
                                <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-700">
                                    {{ $payment->payment_method ?? '—' }}
                                </span>
                            </td>
                            <td class="px-6 py-3 text-gray-700">{{ $payment->reference_number ?? '—' }}</td>
                            <td class="px-6 py-3 font-semibold text-green-600">{{ number_format($payment->amount ?? 0, 2) }} ر.س</td>
                        </tr>
                        @endforeach
                    </tbody>
                    <tfoot class="bg-gray-50 border-t-2 border-gray-200">
                        <tr>
                            <td colspan="5" class="px-6 py-4 text-left font-semibold text-gray-900">إجمالي المدفوع</td>
                            <td class="px-6 py-4 font-bold text-green-700 text-lg">
                                {{ number_format($payments->sum('amount'), 2) }} ر.س
                            </td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
        @endif

    </div>
</div>
@endsection

@push('scripts')
<script>
    document.addEventListener('DOMContentLoaded', function () {
        // ready
    });
</script>
@endpush
