@extends('layouts.app')

@section('title', 'قائمة فواتير الموردين')

@section('content')
<style>
    .table-responsive {
        overflow-x: auto !important;
    }
    .table th, .table td {
        padding: 0.5rem !important;
        vertical-align: middle;
    }
</style>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">{{ \App\Helpers\TranslationHelper::transFromDatabase('Supplier Invoices List', __('Supplier Invoices List')) }}</h3>
                    <div class="card-tools">
                        @can('supplier_invoices.create')
                        <a href="{{ route('supplier-invoices.show-import') }}" class="btn btn-success btn-sm" title="استيراد فواتير من ملف Excel">
                            <i class="fas fa-file-import"></i> {{ \App\Helpers\TranslationHelper::transFromDatabase('Import Invoices', __('Import Invoices')) }}
                        </a>
                        <a href="{{ route('supplier-invoices.create') }}" class="btn btn-primary btn-sm">
                            <i class="fas fa-plus"></i> {{ \App\Helpers\TranslationHelper::transFromDatabase('Add New Invoice', __('Add New Invoice')) }}
                        </a>
                        @endcan
                    </div>
                </div>

                <div class="card-body">
                    @if(session('success'))
                    <div class="alert alert-success alert-dismissible">
                        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                        {{ session('success') }}
                    </div>
                    @endif

                    <div class="card card-primary card-outline">
                        <div class="card-header">
                            <h3 class="card-title">{{ \App\Helpers\TranslationHelper::transFromDatabase('Search and Filter', __('Search and Filter')) }}</h3>
                        </div>
                        <div class="card-body">
                            <form action="{{ route('supplier-invoices.index') }}" method="GET">
                                <input type="hidden" name="sort_by" value="{{ request('sort_by', 'created_at') }}">
                                <input type="hidden" name="sort_dir" value="{{ request('sort_dir', 'desc') }}">
                                <div class="row">
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label for="supplier_id">{{ \App\Helpers\TranslationHelper::transFromDatabase('Supplier', __('Supplier')) }}</label>
                                            <select name="supplier_id" id="supplier_id" class="form-control">
                                                <option value="">{{ \App\Helpers\TranslationHelper::transFromDatabase('All Suppliers', __('All Suppliers')) }}</option>
                                                @foreach($suppliers as $supplier)
                                                <option value="{{ $supplier->id }}" {{ request('supplier_id') == $supplier->id ? 'selected' : '' }}>
                                                    {{ $supplier->name }}
                                                </option>
                                                @endforeach
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label for="status">{{ \App\Helpers\TranslationHelper::transFromDatabase('Status', __('Status')) }}</label>
                                            <select name="status" id="status" class="form-control">
                                                <option value="">{{ \App\Helpers\TranslationHelper::transFromDatabase('All Statuses', __('All Statuses')) }}</option>
                                                <option value="draft" {{ request('status') == 'draft' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Draft', __('Draft')) }}</option>
                                                <option value="approved" {{ request('status') == 'approved' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Approved', __('Approved')) }}</option>
                                                <option value="paid" {{ request('status') == 'paid' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Paid', __('Paid')) }}</option>
                                                <option value="partially_paid" {{ request('status') == 'partially_paid' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Partially Paid', __('Partially Paid')) }}</option>
                                                <option value="overdue" {{ request('status') == 'overdue' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Overdue', __('Overdue')) }}</option>
                                                <option value="cancelled" {{ request('status') == 'cancelled' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Cancelled', __('Cancelled')) }}</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label for="search">{{ \App\Helpers\TranslationHelper::transFromDatabase('Search', __('Search')) }}</label>
                                            <input type="text" name="search" id="search" value="{{ request('search') }}" placeholder="رقم الفاتورة أو اسم المورد" class="form-control">
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label for="date_from">من تاريخ</label>
                                            <input type="date" name="date_from" id="date_from" value="{{ request('date_from') }}" class="form-control">
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label for="date_to">إلى تاريخ</label>
                                            <input type="date" name="date_to" id="date_to" value="{{ request('date_to') }}" class="form-control">
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-search"></i> {{ \App\Helpers\TranslationHelper::transFromDatabase('Search', __('Search')) }}
                                    </button>
                                    <a href="{{ route('supplier-invoices.index') }}" class="btn btn-secondary">
                                        <i class="fas fa-redo"></i> {{ \App\Helpers\TranslationHelper::transFromDatabase('Reset', __('Reset')) }}
                                    </a>
                                </div>
                            </form>
                        </div>
                    </div>

                    @php
                        $currentSortBy = request('sort_by', 'created_at');
                        $currentSortDir = request('sort_dir', 'desc');
                        $filterParams = request()->only(['supplier_id','status','search','date_from','date_to']);
                        $sortLink = function($col) use ($currentSortBy, $currentSortDir, $filterParams) {
                            $dir = ($currentSortBy === $col && $currentSortDir === 'asc') ? 'desc' : 'asc';
                            return route('supplier-invoices.index', array_merge($filterParams, ['sort_by' => $col, 'sort_dir' => $dir]));
                        };
                        $sortIcon = function($col) use ($currentSortBy, $currentSortDir) {
                            if ($currentSortBy !== $col) return 'fa-sort';
                            return $currentSortDir === 'asc' ? 'fa-sort-up' : 'fa-sort-down';
                        };
                    @endphp
                    <div class="table-responsive">
                        <table class="table table-sm table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th style="width: 40px;">#</th>
                                    <th style="width: 110px;">
                                        <a href="{{ $sortLink('invoice_number') }}" class="text-dark text-decoration-none d-flex align-items-center justify-content-between">
                                            {{ \App\Helpers\TranslationHelper::transFromDatabase('Invoice Number', __('Invoice Number')) }}
                                            <i class="fas {{ $sortIcon('invoice_number') }} mr-1"></i>
                                        </a>
                                    </th>
                                    <th style="width: 110px;">
                                        <a href="{{ $sortLink('supplier_name') }}" class="text-dark text-decoration-none d-flex align-items-center justify-content-between">
                                            {{ \App\Helpers\TranslationHelper::transFromDatabase('Supplier', __('Supplier')) }}
                                            <i class="fas {{ $sortIcon('supplier_name') }} mr-1"></i>
                                        </a>
                                    </th>
                                    <th style="width: 70px;">{{ \App\Helpers\TranslationHelper::transFromDatabase('Total', __('Total')) }}</th>
                                    <th style="width: 70px;">{{ \App\Helpers\TranslationHelper::transFromDatabase('Paid', __('Paid')) }}</th>
                                    <th style="width: 70px;">{{ \App\Helpers\TranslationHelper::transFromDatabase('Remaining', __('Remaining')) }}</th>
                                    <th style="width: 80px;">
                                        <a href="{{ $sortLink('invoice_date') }}" class="text-dark text-decoration-none d-flex align-items-center justify-content-between">
                                            التاريخ
                                            <i class="fas {{ $sortIcon('invoice_date') }} mr-1"></i>
                                        </a>
                                    </th>
                                    <th style="width: 70px;">{{ \App\Helpers\TranslationHelper::transFromDatabase('Status', __('Status')) }}</th>
                                    <th style="width: 100px;">{{ \App\Helpers\TranslationHelper::transFromDatabase('Actions', __('Actions')) }}</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($invoices as $invoice)
                                <tr>
                                    <td>{{ $loop->iteration }}</td>
                                    <td><strong>{{ $invoice->invoice_number }}</strong></td>
                                    <td>{{ $invoice->supplier->name }}</td>
                                    <td>{{ number_format($invoice->total_amount, 0) }}</td>
                                    <td><span class="text-success">{{ number_format($invoice->paid_amount, 0) }}</span></td>
                                    <td><span class="text-danger">{{ number_format($invoice->remaining_amount, 0) }}</span></td>
                                    <td>{{ \Carbon\Carbon::parse($invoice->invoice_date)->format('Y-m-d') }}</td>
                                    <td>
                                        @switch($invoice->status)
                                            @case('draft')
                                                <span class="badge bg-secondary">{{ \App\Helpers\TranslationHelper::transFromDatabase('Draft', __('Draft')) }}</span>
                                                @break
                                            @case('approved')
                                                <span class="badge bg-info text-white">{{ \App\Helpers\TranslationHelper::transFromDatabase('Approved', __('Approved')) }}</span>
                                                @break
                                            @case('paid')
                                                <span class="badge bg-success">{{ \App\Helpers\TranslationHelper::transFromDatabase('Paid', __('Paid')) }}</span>
                                                @break
                                            @case('partially_paid')
                                                <span class="badge bg-warning text-dark">{{ \App\Helpers\TranslationHelper::transFromDatabase('Partially Paid', __('Partially Paid')) }}</span>
                                                @break
                                            @case('overdue')
                                                <span class="badge bg-danger">{{ \App\Helpers\TranslationHelper::transFromDatabase('Overdue', __('Overdue')) }}</span>
                                                @break
                                            @case('cancelled')
                                                <span class="badge bg-danger">{{ \App\Helpers\TranslationHelper::transFromDatabase('Cancelled', __('Cancelled')) }}</span>
                                                @break
                                            @default
                                                <span class="badge bg-secondary">{{ $invoice->status }}</span>
                                        @endswitch
                                    </td>
                                    <td class="text-center">
                                        <div x-data="{ open: false }">
                                            <!-- Actions Button -->
                                            <button @click="open = true" type="button" 
                                                    class="inline-flex items-center px-3 py-1.5 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 -->
                                            <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 --}}
                                                                <a href="{{ route('supplier-invoices.show', $invoice) }}" 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>

                                                                {{-- Edit --}}
                                                                <a href="{{ route('supplier-invoices.edit', $invoice) }}" 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>

                                                                {{-- Return --}}
                                                                <a href="{{ route('supplier-invoice-returns.create-from-invoice', ['invoice' => $invoice->id, 'returnType' => 'purchase_return']) }}" 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-undo-alt text-xs"></i>
                                                                    </div>
                                                                    <span class="text-[10px] font-bold">مرتجع</span>
                                                                </a>

                                                                {{-- Journal --}}
                                                                @if($invoice->journalEntry)
                                                                    <a href="{{ route('accounting.journal-entries.show', $invoice->journalEntry) }}" 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">{{ \App\Helpers\TranslationHelper::transFromDatabase('Journal Entry', __('Journal Entry')) }}</span>
                                                                    </a>
                                                                @else
                                                                    <form action="{{ route('supplier-invoices.create-journal', $invoice) }}" method="POST" class="flex h-full">
                                                                        @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">{{ \App\Helpers\TranslationHelper::transFromDatabase('Create Journal', __('Create Journal')) }}</span>
                                                                        </button>
                                                                    </form>
                                                                @endif

                                                                {{-- Payment --}}
                                                                <a href="{{ route('supplier-payments.create', ['invoice_id' => $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 text-xs"></i>
                                                                    </div>
                                                                    <span class="text-[10px] font-bold">{{ \App\Helpers\TranslationHelper::transFromDatabase('Payment', __('Payment')) }}</span>
                                                                </a>

                                                                {{-- Delete --}}
                                                                <form action="{{ route('supplier-invoices.destroy', $invoice) }}" method="POST" class="flex h-full">
                                                                    @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 text-right" onclick="return confirm('{{ \App\Helpers\TranslationHelper::transFromDatabase('Are you sure you want to delete this invoice?', __('Are you sure you want to delete this invoice?')) }}')">
                                                                        <div class="w-7 h-7 rounded bg-red-100 flex items-center justify-center ml-2 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>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                @empty
                                <tr>
                                    <td colspan="9" class="text-center">{{ \App\Helpers\TranslationHelper::transFromDatabase('No invoices', __('No invoices')) }}</td>
                                </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>

                    <div class="mt-4">
                        {{ $invoices->links() }}
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
    $(function() {
        $('[data-toggle="tooltip"]').tooltip();
    });
</script>
@endpush
@endsection
