@extends('layouts.app')
@section("title", \App\Helpers\TranslationHelper::transFromDatabase('Customer Invoices', __('Customer Invoices')))

@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="mb-8">
            <div class="flex flex-col gap-4">
                <div class="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
                    <div>
                        <h1 class="text-3xl font-bold text-gray-900 mb-2">
                            {{ \App\Helpers\TranslationHelper::transFromDatabase('Customer Invoices', __('Customer Invoices')) }}
                        </h1>
                        <p class="text-gray-600">
                            {{ \App\Helpers\TranslationHelper::transFromDatabase('Manage all customer invoices and payments', __('Manage all customer invoices and payments')) }}
                        </p>
                    </div>
                    @can("customer-invoices.create")
                    <a href="{{ route('customer-invoices.create') }}" 
                       class="inline-flex items-center px-6 py-3 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 hover:shadow-xl transform hover:scale-105 whitespace-nowrap">
                        <i class="fas fa-plus ml-2"></i>
                        {{ \App\Helpers\TranslationHelper::transFromDatabase('Add New Invoice', __('Add New Invoice')) }}
                    </a>
                    @endcan
                </div>

                {{-- Action Buttons --}}
                <div class="flex flex-wrap gap-3">
                    @can("customer-invoices.create")
                    <a href="{{ route('customer-invoices.show-import') }}" 
                       class="inline-flex items-center px-5 py-2.5 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-md hover:shadow-lg text-sm">
                        <i class="fas fa-file-import ml-2"></i>
                        استيراد من ملف
                    </a>
                    <a href="{{ route('customer-invoices.download-template') }}" 
                       class="inline-flex items-center px-5 py-2.5 bg-gradient-to-r from-amber-600 to-amber-700 text-white font-semibold rounded-lg hover:from-amber-700 hover:to-amber-800 transition-all duration-200 shadow-md hover:shadow-lg text-sm">
                        <i class="fas fa-download ml-2"></i>
                        تنزيل القالب
                    </a>
                    @endcan
                    
                    @can("customer-invoices.view")
                    <a href="{{ route('customer-invoices.export', request()->all()) }}" 
                       class="inline-flex items-center px-5 py-2.5 bg-gradient-to-r from-blue-600 to-indigo-700 text-white font-semibold rounded-lg hover:from-blue-700 hover:to-indigo-800 transition-all duration-200 shadow-md hover:shadow-lg text-sm">
                        <i class="fas fa-file-excel ml-2"></i>
                        تصدير إكسيل
                    </a>
                    @endcan
                </div>
            </div>
        </div>

        {{-- Success Message --}}
        @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

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

        {{-- Error Message --}}
        @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

        {{-- Table Card --}}
        <div class="bg-white rounded-xl shadow-lg border border-gray-200">
            
            {{-- Table Wrapper --}}
            <div class="overflow-x-auto">
                <table class="w-full">
                    {{-- Table Header --}}
                    <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">
                                {{ \App\Helpers\TranslationHelper::transFromDatabase('Invoice Number', __('Invoice Number')) }}
                            </th>
                            <th class="px-6 py-4 text-right font-semibold text-sm">
                                {{ \App\Helpers\TranslationHelper::transFromDatabase('Customer', __('Customer')) }}
                            </th>
                            <th class="px-6 py-4 text-right font-semibold text-sm">
                                {{ \App\Helpers\TranslationHelper::transFromDatabase('Invoice Date', __('Invoice Date')) }}
                            </th>
                            <th class="px-6 py-4 text-right font-semibold text-sm">
                                {{ \App\Helpers\TranslationHelper::transFromDatabase('Amount Before Tax', __('Amount Before Tax')) }}
                            </th>
                            <th class="px-6 py-4 text-right font-semibold text-sm">
                                {{ \App\Helpers\TranslationHelper::transFromDatabase('Tax Amount', __('Tax Amount')) }}
                            </th>
                            <th class="px-6 py-4 text-right font-semibold text-sm">
                                {{ \App\Helpers\TranslationHelper::transFromDatabase('Total', __('Total')) }}
                            </th>
                            <th class="px-6 py-4 text-right font-semibold text-sm">
                                {{ \App\Helpers\TranslationHelper::transFromDatabase('Paid', __('Paid')) }}
                            </th>
                            <th class="px-6 py-4 text-right font-semibold text-sm">
                                {{ \App\Helpers\TranslationHelper::transFromDatabase('Remaining', __('Remaining')) }}
                            </th>
                            <th class="px-6 py-4 text-right font-semibold text-sm">
                                {{ \App\Helpers\TranslationHelper::transFromDatabase('Status', __('Status')) }}
                            </th>
                            <th class="px-6 py-4 text-center font-semibold text-sm">
                                {{ \App\Helpers\TranslationHelper::transFromDatabase('Actions', __('Actions')) }}
                            </th>
                        </tr>
                    </thead>

                    {{-- Table Body --}}
                    <tbody class="divide-y divide-gray-200">
                        @forelse($invoices as $invoice)
                        <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 whitespace-nowrap">
                                {{ $loop->iteration }}
                            </td>
                            <td class="px-6 py-4">
                                <div class="font-semibold text-gray-900">{{ $invoice->invoice_number }}</div>
                                @if($invoice->contract)
                                <div class="text-sm text-gray-600">{{ $invoice->contract->contract_number }}</div>
                                @endif
                            </td>
                            <td class="px-6 py-4">
                                <div class="font-semibold text-gray-900">{{ $invoice->customer_name }}</div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-gray-600">
                                {{ $invoice->invoice_date->format("Y-m-d") }}
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-gray-600 font-semibold">{{ number_format($invoice->subtotal, 2) }}</div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-gray-600 font-semibold">{{ number_format($invoice->tax_amount, 2) }}</div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="font-semibold text-gray-900">{{ number_format($invoice->total_amount, 2) }}</div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-green-600 font-semibold">{{ number_format($invoice->paid_amount_sum ?? $invoice->paid_amount, 2) }}</div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-orange-600 font-semibold">{{ number_format(($invoice->total_amount - ($invoice->paid_amount_sum ?? $invoice->paid_amount)), 2) }}</div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                @if($invoice->status == "draft")
                                    <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-bold bg-slate-100 text-slate-700">
                                        <span class="w-2 h-2 bg-slate-500 rounded-full ml-2"></span>
                                        {{ \App\Helpers\TranslationHelper::transFromDatabase('Draft', __('Draft')) }}
                                    </span>
                                @elseif($invoice->status == "sent")
                                    <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-bold bg-blue-100 text-blue-700">
                                        <i class="fas fa-paper-plane ml-1"></i>
                                        {{ \App\Helpers\TranslationHelper::transFromDatabase('Sent', __('Sent')) }}
                                    </span>
                                @elseif($invoice->status == "paid")
                                    <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-bold bg-green-100 text-green-700">
                                        <span class="w-2 h-2 bg-green-500 rounded-full ml-2"></span>
                                        {{ \App\Helpers\TranslationHelper::transFromDatabase('Paid', __('Paid')) }}
                                    </span>
                                @elseif($invoice->status == "partially_paid")
                                    <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-bold bg-amber-100 text-amber-700">
                                        <i class="fas fa-hourglass-half ml-1"></i>
                                        {{ \App\Helpers\TranslationHelper::transFromDatabase('Partially Paid', __('Partially Paid')) }}
                                    </span>
                                @elseif($invoice->status == "overdue")
                                    <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-bold bg-red-100 text-red-700">
                                        <i class="fas fa-exclamation-triangle ml-1"></i>
                                        {{ \App\Helpers\TranslationHelper::transFromDatabase('Overdue', __('Overdue')) }}
                                    </span>
                                @elseif($invoice->status == "cancelled")
                                    <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-bold bg-gray-100 text-gray-700">
                                        <i class="fas fa-times-circle ml-1"></i>
                                        {{ \App\Helpers\TranslationHelper::transFromDatabase('Cancelled', __('Cancelled')) }}
                                    </span>
                                @endif
                            </td>
                            <td class="px-6 py-4 text-center">
                                <div x-data="{ open: false }">
                                    <!-- Actions Button -->
                                    <button @click="open = true" type="button" 
                                            class="inline-flex items-center px-4 py-2 rounded-lg bg-gray-100 text-gray-700 hover:bg-gray-200 transition-all duration-150 text-xs font-bold shadow-sm border border-gray-200">
                                        <i class="fas fa-cog ml-1.5"></i>
                                        {{ \App\Helpers\TranslationHelper::transFromDatabase('Actions', __('Actions')) }}
                                    </button>

                                    <!-- Modal (Simplified without x-teleport) -->
                                    <div x-show="open" 
                                         x-cloak
                                         class="fixed inset-0 z-[99999] overflow-y-auto" 
                                         aria-labelledby="modal-title" role="dialog" aria-modal="true">
                                        
                                        <!-- Backdrop -->
                                        <div x-show="open" 
                                             x-transition:enter="ease-out duration-300"
                                             x-transition:enter-start="opacity-0"
                                             x-transition:enter-end="opacity-100"
                                             x-transition:leave="ease-in duration-200"
                                             x-transition:leave-start="opacity-100"
                                             x-transition:leave-end="opacity-0"
                                             @click="open = false"
                                             class="fixed inset-0 bg-gray-900 bg-opacity-60 backdrop-blur-sm transition-opacity"></div>

                                        <div class="flex items-center justify-center min-h-screen p-4 text-center sm:p-0">
                                            <div x-show="open" 
                                                 x-transition:enter="ease-out duration-300"
                                                 x-transition:enter-start="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                                                 x-transition:enter-end="opacity-100 translate-y-0 sm:scale-100"
                                                 x-transition:leave="ease-in duration-200"
                                                 x-transition:leave-start="opacity-100 translate-y-0 sm:scale-100"
                                                 x-transition:leave-end="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                                                 @click.away="open = false"
                                                 class="relative transform overflow-hidden rounded-2xl bg-white text-right shadow-2xl transition-all sm:my-8 sm:w-full sm:max-w-xl border border-gray-100">
                                                
                                                <!-- Modal Header -->
                                                <div class="bg-gradient-to-r from-gray-800 to-gray-900 px-4 py-2 flex justify-between items-center">
                                                    <h3 class="text-xs font-bold text-white flex items-center">
                                                        <i class="fas fa-file-invoice ml-2 text-blue-400"></i>
                                                        التحكم بالفاتورة: {{ $invoice->invoice_number }}
                                                    </h3>
                                                    <button @click="open = false" class="text-gray-400 hover:text-white transition-colors">
                                                        <i class="fas fa-times text-base"></i>
                                                    </button>
                                                </div>

                                                <!-- Modal Content -->
                                                <div class="bg-white px-3 py-3">
                                                    <div class="grid grid-cols-2 sm:grid-cols-4 gap-2">
                                                        {{-- View --}}
                                                        @can("customer-invoices.view")
                                                        <a href="{{ route('customer-invoices.show', $invoice->id) }}" class="flex items-center p-1.5 rounded-lg bg-blue-50 text-blue-700 hover:bg-blue-100 transition-all border border-blue-100 group">
                                                            <div class="w-7 h-7 rounded bg-blue-100 flex items-center justify-center ml-2 group-hover:scale-110 transition-transform">
                                                                <i class="fas fa-eye text-xs"></i>
                                                            </div>
                                                            <span class="text-[10px] font-bold">{{ \App\Helpers\TranslationHelper::transFromDatabase('View', __('View')) }}</span>
                                                        </a>
                                                        @endcan

                                                        {{-- Edit --}}
                                                        @can("customer-invoices.edit")
                                                        <a href="{{ route('customer-invoices.edit', $invoice->id) }}" class="flex items-center p-1.5 rounded-lg bg-amber-50 text-amber-700 hover:bg-amber-100 transition-all border border-amber-100 group">
                                                            <div class="w-7 h-7 rounded bg-amber-100 flex items-center justify-center ml-2 group-hover:scale-110 transition-transform">
                                                                <i class="fas fa-edit text-xs"></i>
                                                            </div>
                                                            <span class="text-[10px] font-bold">{{ \App\Helpers\TranslationHelper::transFromDatabase('Edit', __('Edit')) }}</span>
                                                        </a>
                                                        @endcan

                                                        {{-- Payments --}}
                                                        @can("customer-invoices.payments")
                                                        <a href="{{ route('customer-invoices.payments', $invoice->id) }}" class="flex items-center p-1.5 rounded-lg bg-green-50 text-green-700 hover:bg-green-100 transition-all border border-green-100 group">
                                                            <div class="w-7 h-7 rounded bg-green-100 flex items-center justify-center ml-2 group-hover:scale-110 transition-transform">
                                                                <i class="fas fa-money-bill-wave text-xs"></i>
                                                            </div>
                                                            <span class="text-[10px] font-bold">{{ \App\Helpers\TranslationHelper::transFromDatabase('Payments', __('Payments')) }}</span>
                                                        </a>
                                                        @endcan

                                                        {{-- Return --}}
                                                        @can("customer-invoices.view")
                                                        <a href="{{ route('customer-invoice-returns.create-from-invoice', ['invoice' => $invoice->id, 'returnType' => 'sales_return']) }}" class="flex items-center p-1.5 rounded-lg bg-purple-50 text-purple-700 hover:bg-purple-100 transition-all border border-purple-100 group">
                                                            <div class="w-7 h-7 rounded bg-purple-100 flex items-center justify-center ml-2 group-hover:scale-110 transition-transform">
                                                                <i class="fas fa-undo-alt text-xs"></i>
                                                            </div>
                                                            <span class="text-[10px] font-bold">مرتجع</span>
                                                        </a>
                                                        @endcan

                                                        {{-- Journal --}}
                                                        @can("customer-invoices.create")
                                                            @if($invoice->journalEntry)
                                                            <a href="{{ route('customer-invoices.show-journal', $invoice->id) }}" class="flex items-center p-1.5 rounded-lg bg-cyan-50 text-cyan-700 hover:bg-cyan-100 transition-all border border-cyan-100 group">
                                                                <div class="w-7 h-7 rounded bg-cyan-100 flex items-center justify-center ml-2 group-hover:scale-110 transition-transform">
                                                                    <i class="fas fa-book text-xs"></i>
                                                                </div>
                                                                <span class="text-[10px] font-bold text-center">القيد</span>
                                                            </a>
                                                            @else
                                                            <form action="{{ route('customer-invoices.create-journal', $invoice->id) }}" method="POST" class="flex">
                                                                @csrf
                                                                <button type="submit" class="w-full flex items-center p-1.5 rounded-lg bg-indigo-50 text-indigo-700 hover:bg-indigo-100 transition-all border border-indigo-100 group text-right" onclick="return confirm('هل تريد إنشاء قيد اليومية التلقائي لهذه الفاتورة؟')">
                                                                    <div class="w-7 h-7 rounded bg-indigo-100 flex items-center justify-center ml-2 group-hover:scale-110 transition-transform">
                                                                        <i class="fas fa-plus-circle text-xs"></i>
                                                                    </div>
                                                                    <span class="text-[10px] font-bold">القيد</span>
                                                                </button>
                                                            </form>
                                                            @endif
                                                        @endcan

                                                        {{-- Inventory --}}
                                                        @php
                                                            $inventoryDocs = $invoice->inventoryDocuments()->get();
                                                        @endphp
                                                        
                                                        @if($inventoryDocs->count() > 0)
                                                            @foreach($inventoryDocs as $doc)
                                                                @php
                                                                    $effect = strtolower($doc->documentType->effect);
                                                                    $showUrl = $effect === 'out' ? route('inventory.issues.show', $doc->id) : route('inventory.receipts.show', $doc->id);
                                                                @endphp
                                                                <a href="{{ $showUrl }}" class="flex items-center p-1.5 rounded-lg bg-orange-50 text-orange-700 hover:bg-orange-100 transition-all border border-orange-100 group">
                                                                    <div class="w-7 h-7 rounded bg-orange-100 flex items-center justify-center ml-2 group-hover:scale-110 transition-transform">
                                                                        <i class="fas fa-file-invoice text-xs"></i>
                                                                    </div>
                                                                    <span class="text-[10px] font-bold text-center">سند: {{ $doc->document_number }}</span>
                                                                </a>
                                                            @endforeach
                                                        @else
                                                            @can("inventory.issues.create")
                                                            <a href="{{ route('inventory.issues.create', ['customer_invoice_id' => $invoice->id]) }}" class="flex items-center p-1.5 rounded-lg bg-orange-50 text-orange-700 hover:bg-orange-100 transition-all border border-orange-100 group">
                                                                <div class="w-7 h-7 rounded bg-orange-100 flex items-center justify-center ml-2 group-hover:scale-110 transition-transform">
                                                                    <i class="fas fa-plus-circle text-xs"></i>
                                                                </div>
                                                                <span class="text-[10px] font-bold text-center">صرف</span>
                                                            </a>
                                                            @endcan
                                                        @endif

                                                        {{-- Send / Cancel --}}
                                                        @if($invoice->status == "draft")
                                                            @can("customer-invoices.update")
                                                            <form action="{{ route('customer-invoices.update-status', $invoice->id) }}" method="POST" class="flex h-full">
                                                                @csrf
                                                                @method("PATCH")
                                                                <input type="hidden" name="status" value="sent">
                                                                <button type="submit" class="w-full flex items-center p-1.5 rounded-lg bg-purple-600 text-white hover:bg-purple-700 transition-all shadow-md group">
                                                                    <div class="w-7 h-7 rounded bg-purple-500 bg-opacity-30 flex items-center justify-center mb-1 group-hover:scale-110 transition-transform">
                                                                        <i class="fas fa-paper-plane text-xs"></i>
                                                                    </div>
                                                                    <span class="text-[10px] font-bold">إرسال</span>
                                                                </button>
                                                            </form>
                                                            @endcan
                                                        @elseif($invoice->status == "sent" || $invoice->status == "partially_paid")
                                                            @can("customer-invoices.update")
                                                            <form action="{{ route('customer-invoices.update-status', $invoice->id) }}" method="POST" class="flex h-full" onsubmit="return confirm('هل تريد إلغاء هذه الفاتورة؟')">
                                                                @csrf
                                                                @method("PATCH")
                                                                <input type="hidden" name="status" value="cancelled">
                                                                <button type="submit" class="w-full flex items-center p-1.5 rounded-lg bg-gray-600 text-white hover:bg-gray-700 transition-all shadow-md group">
                                                                    <div class="w-7 h-7 rounded bg-gray-500 bg-opacity-30 flex items-center justify-center mb-1 group-hover:scale-110 transition-transform">
                                                                        <i class="fas fa-times text-xs"></i>
                                                                    </div>
                                                                    <span class="text-[10px] font-bold">إلغاء</span>
                                                                </button>
                                                            </form>
                                                            @endcan
                                                        @endif

                                                        {{-- Delete --}}
                                                        @can("customer-invoices.delete")
                                                        <form action="{{ route('customer-invoices.destroy', $invoice->id) }}" method="POST" class="flex h-full" onsubmit="return confirm('{{ __('Are you sure?') }}')">
                                                            @csrf
                                                            @method("DELETE")
                                                            <button type="submit" class="w-full flex items-center p-1.5 rounded-lg bg-red-50 text-red-700 hover:bg-red-100 transition-all border border-red-100 group">
                                                                <div class="w-7 h-7 rounded bg-red-100 flex items-center justify-center mb-1 group-hover:scale-110 transition-transform">
                                                                    <i class="fas fa-trash text-xs"></i>
                                                                </div>
                                                                <span class="text-[10px] font-bold">{{ \App\Helpers\TranslationHelper::transFromDatabase('Delete', __('Delete')) }}</span>
                                                            </button>
                                                        </form>
                                                        @endcan
                                                    </div>
                                                </div>

                                                <!-- Modal Footer -->
                                                <div class="bg-gray-50 px-4 py-2 flex flex-row-reverse">
                                                    <button @click="open = false" type="button" class="inline-flex w-full justify-center rounded-lg bg-white px-4 py-1.5 text-xs font-bold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50 sm:w-auto">
                                                        إغلاق
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        @empty
                        <tr>
                            <td colspan="9" 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">{{ \App\Helpers\TranslationHelper::transFromDatabase('No invoices found', __('No invoices found')) }}</p>
                                    <p class="text-gray-500 text-sm mt-1">{{ \App\Helpers\TranslationHelper::transFromDatabase('Start by creating a new invoice', __('Start by creating a new invoice')) }}</p>
                                </div>
                            </td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>

            {{-- Pagination --}}
            @if($invoices->hasPages())
            <div class="px-6 py-4 bg-gray-50 border-t border-gray-200">
                <div class="flex justify-center">
                    {{ $invoices->links() }}
                </div>
            </div>
            @endif
        </div>
    </div>
</div>
@endsection
