@extends('layouts.admin')

@section('title', 'Purchases')

@section('page-title', 'Purchases')

@section('content')
<style>
    .purchases-table-scroll {
        overflow-x: auto;
    }
</style>
<div class="max-w-[1400px] mx-auto">
    <!-- Header Section -->
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <h1 class="text-2xl font-bold text-gray-900">Purchases</h1>
        <div class="flex items-center gap-3">
            <a href="{{ route('admin.purchases.create') }}" class="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium shadow-lg shadow-primary/30 hover:bg-blue-600 transition-colors">
                <span class="material-symbols-outlined text-lg">add</span>
                <span>New Purchase</span>
            </a>
            <form method="GET" action="{{ route('admin.purchases.index') }}" class="flex items-center">
                @if(request('search'))
                    <input type="hidden" name="search" value="{{ request('search') }}">
                @endif
                <select name="per_page" onchange="this.form.submit()" class="px-3 py-2 text-sm border border-gray-200 rounded-lg bg-white text-gray-700 focus:outline-none focus:ring-1 focus:ring-primary">
                    <option value="10" {{ request('per_page', 10) == 10 ? 'selected' : '' }}>10 / page</option>
                    <option value="15" {{ request('per_page', 10) == 15 ? 'selected' : '' }}>15 / page</option>
                    <option value="25" {{ request('per_page', 10) == 25 ? 'selected' : '' }}>25 / page</option>
                    <option value="50" {{ request('per_page', 10) == 50 ? 'selected' : '' }}>50 / page</option>
                    <option value="100" {{ request('per_page', 10) == 100 ? 'selected' : '' }}>100 / page</option>
                </select>
            </form>
        </div>
    </div>

    <!-- Search Bar -->
    <div class="mb-4">
        <form method="GET" action="{{ route('admin.purchases.index') }}" class="flex gap-2">
            @if(request('per_page'))
                <input type="hidden" name="per_page" value="{{ request('per_page') }}">
            @endif
            <input type="text" name="search" value="{{ request('search') }}" placeholder="Search..." class="flex-1 max-w-md h-10 px-4 rounded-lg border border-gray-200 bg-white text-gray-900 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-primary">
            <button type="submit" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-blue-600 transition-colors">
                <span class="material-symbols-outlined">search</span>
            </button>
            @if(request('search'))
                <a href="{{ route('admin.purchases.index', ['per_page' => request('per_page')]) }}" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors">
                    <span class="material-symbols-outlined">close</span>
                </a>
            @endif
        </form>
    </div>

    <!-- Purchases Table -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-visible">
        <div class="purchases-table-scroll">
            <table class="w-full text-left border-collapse">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 w-16">#</th>
                        <th class="py-4 px-6 text-sm font-semibold uppercase tracking-wider text-gray-500 min-w-[140px]">PURCHASE NUMBER</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 min-w-[120px]">PURCHASE DATE</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 min-w-[200px]">SUPPLIER</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 text-right min-w-[120px]">AMOUNT</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 min-w-[130px]">PAYMENT MODE</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 min-w-[110px]">CREATED ON</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 text-center min-w-[160px]">STATUS</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 text-right min-w-[100px]">ACTION</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    @forelse($purchases as $index => $purchase)
                        <tr class="group hover:bg-gray-50/50 transition-colors">
                            <td class="py-4 px-6 text-sm text-gray-600">{{ ($purchases->currentPage() - 1) * $purchases->perPage() + $index + 1 }}</td>
                            <td class="py-4 px-6 text-sm">
                                <a href="{{ route('admin.purchases.show', $purchase) }}" class="text-sm font-semibold text-primary hover:underline hover:text-blue-600">
                                    {{ $purchase->purchase_number }}
                                </a>
                            </td>
                            <td class="py-4 px-6 text-sm text-gray-600">
                                {{ $purchase->purchase_date ? $purchase->purchase_date->format('M d, Y') : 'Invalid Date' }}
                            </td>
                            <td class="py-4 px-6">
                                @if($purchase->supplier)
                                    <div class="flex items-center gap-3">
                                        <div class="size-8 rounded-full bg-primary flex items-center justify-center text-white font-bold text-xs shrink-0">
                                            @if($purchase->supplier->image && \Illuminate\Support\Facades\Storage::disk('public')->exists($purchase->supplier->image))
                                                <img src="{{ \Illuminate\Support\Facades\Storage::disk('public')->url($purchase->supplier->image) }}" alt="{{ $purchase->supplier->name }}" class="w-full h-full rounded-full object-cover">
                                            @else
                                                {{ strtoupper(substr($purchase->supplier->name ?? 'N', 0, 1)) }}
                                            @endif
                                        </div>
                                        <span class="text-sm font-medium text-gray-900">{{ $purchase->supplier->name ?? 'N/A' }}</span>
                                    </div>
                                @else
                                    <div class="flex items-center gap-3">
                                        <div class="size-8 rounded-full bg-gray-300 flex items-center justify-center text-gray-600 font-bold text-xs shrink-0">?</div>
                                        <span class="text-sm text-gray-500">Deleted User</span>
                                    </div>
                                @endif
                            </td>
                            <td class="py-4 px-6 text-sm font-medium text-gray-900 text-right">
                                {{ \App\Models\Currency::formatAmount($purchase->total, $purchase->currency ?? null) }}
                            </td>
                            <td class="py-4 px-6">
                                @php
                                    $paymentMethod = $purchase->payment_method ?? 'cash';
                                    $paymentConfig = [
                                        'cash' => ['label' => 'Cash $', 'bg' => 'bg-green-100', 'text' => 'text-green-800'],
                                        'bank_transfer' => ['label' => 'Bank Transfer', 'bg' => 'bg-blue-100', 'text' => 'text-blue-800'],
                                        'credit_card' => ['label' => 'Credit Card', 'bg' => 'bg-purple-100', 'text' => 'text-purple-800'],
                                        'cheque' => ['label' => 'Cheque', 'bg' => 'bg-yellow-100', 'text' => 'text-yellow-800'],
                                    ];
                                    $config = $paymentConfig[$paymentMethod] ?? $paymentConfig['cash'];
                                @endphp
                                <span class="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium {{ $config['bg'] }} {{ $config['text'] }}">
                                    {{ $config['label'] }}
                                </span>
                            </td>
                            <td class="py-4 px-6 text-sm text-gray-600 whitespace-nowrap">
                                {{ $purchase->created_at ? $purchase->created_at->format('M d, Y') : 'Invalid Date' }}
                            </td>
                            <td class="py-4 px-6 text-center align-middle">
                                @php
                                    $statusConfig = [
                                        'new' => ['label' => 'New', 'bg' => 'bg-sky-100', 'text' => 'text-sky-900', 'icon' => 'fiber_new'],
                                        'pending' => ['label' => 'Pending', 'bg' => 'bg-amber-100', 'text' => 'text-amber-900', 'icon' => 'schedule'],
                                        'partially_paid' => ['label' => 'Partially Paid', 'bg' => 'bg-blue-100', 'text' => 'text-blue-900', 'icon' => 'payments'],
                                        'completed' => ['label' => 'Completed', 'bg' => 'bg-green-100', 'text' => 'text-blue-900', 'icon' => 'check_circle'],
                                        'cancelled' => ['label' => 'Cancelled', 'bg' => 'bg-red-100', 'text' => 'text-red-900', 'icon' => 'cancel'],
                                    ];
                                    $status = $purchase->status ?? 'new';
                                    $config = $statusConfig[$status] ?? $statusConfig['new'];
                                @endphp
                                <span class="inline-flex items-center justify-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium whitespace-nowrap {{ $config['bg'] }} {{ $config['text'] }} border border-black/5">
                                    <span class="material-symbols-outlined text-[14px] leading-none shrink-0" aria-hidden="true">{{ $config['icon'] }}</span>
                                    <span>{{ $config['label'] }}</span>
                                </span>
                            </td>
                            <td class="py-4 px-6 text-right">
                                <div class="relative inline-block text-left">
                                    <button type="button" data-admin-fixed-menu-trigger="action-menu-{{ $purchase->id }}" onclick="adminFixedActionMenuToggle(event || window.event, 'action-menu-{{ $purchase->id }}')" class="text-gray-400 hover:text-gray-600 transition-colors" title="More actions">
                                        <span class="material-symbols-outlined text-xl">more_vert</span>
                                    </button>
                                    <div id="action-menu-{{ $purchase->id }}" data-admin-fixed-action-menu class="hidden w-48 overflow-hidden rounded-lg border border-gray-200 bg-white shadow-lg">
                                        <div class="py-1">
                                            <a href="{{ route('admin.purchases.show', $purchase) }}" class="flex items-center gap-2 px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-colors">
                                                <span class="material-symbols-outlined text-base">preview</span>
                                                <span>View</span>
                                            </a>
                                            <a href="{{ route('admin.purchases.edit', $purchase) }}" class="flex items-center gap-2 px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-colors">
                                                <span class="material-symbols-outlined text-base">edit</span>
                                                <span>Edit</span>
                                            </a>
                                            <div class="border-t border-gray-100 my-1"></div>
                                            <button type="button" onclick="openPurchaseDeleteModal({{ $purchase->id }}, @js($purchase->purchase_number))" class="w-full flex items-center gap-2 px-4 py-2 text-sm text-red-600 hover:bg-red-50 transition-colors text-left">
                                                <span class="material-symbols-outlined text-base">delete</span>
                                                <span>Delete</span>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="9" class="py-12 px-6 text-center text-gray-500">
                                <span class="material-symbols-outlined text-4xl mb-2 block">shopping_cart</span>
                                <p>No purchases found</p>
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        @if($purchases->hasPages())
            <div class="px-6 py-4 border-t border-gray-200 flex flex-col sm:flex-row items-center justify-between gap-4">
                <p class="text-sm text-gray-500">
                    Showing <span class="font-medium text-gray-900">{{ $purchases->firstItem() }}</span> to <span class="font-medium text-gray-900">{{ $purchases->lastItem() }}</span> of <span class="font-medium text-gray-900">{{ $purchases->total() }}</span> entries
                </p>
                <div class="flex items-center gap-1">
                    @if($purchases->onFirstPage())
                        <button disabled class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                            <
                        </button>
                    @else
                        <a href="{{ $purchases->previousPageUrl() }}" class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50">
                            <
                        </a>
                    @endif
                    
                    @php
                        $currentPage = $purchases->currentPage();
                        $lastPage = $purchases->lastPage();
                        $startPage = max(1, $currentPage - 1);
                        $endPage = min($lastPage, $currentPage + 1);
                    @endphp
                    
                    @if($startPage > 1)
                        <a href="{{ $purchases->url(1) }}" class="size-8 text-sm font-medium rounded text-gray-600 hover:bg-gray-50 flex items-center justify-center">
                            1
                        </a>
                        @if($startPage > 2)
                            <span class="px-2 text-gray-400">...</span>
                        @endif
                    @endif
                    
                    @for($page = $startPage; $page <= $endPage; $page++)
                        <a href="{{ $purchases->url($page) }}" class="size-8 text-sm font-medium rounded {{ $page == $currentPage ? 'bg-primary text-white' : 'text-gray-600 hover:bg-gray-50' }} flex items-center justify-center">
                            {{ $page }}
                        </a>
                    @endfor
                    
                    @if($endPage < $lastPage)
                        @if($endPage < $lastPage - 1)
                            <span class="px-2 text-gray-400">...</span>
                        @endif
                        <a href="{{ $purchases->url($lastPage) }}" class="size-8 text-sm font-medium rounded text-gray-600 hover:bg-gray-50 flex items-center justify-center">
                            {{ $lastPage }}
                        </a>
                    @endif
                    
                    @if($purchases->hasMorePages())
                        <a href="{{ $purchases->nextPageUrl() }}" class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50">
                            >
                        </a>
                    @else
                        <button disabled class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                            >
                        </button>
                    @endif
                </div>
            </div>
        @endif
    </div>
</div>

<!-- Delete confirmation -->
<div id="purchase-delete-modal" data-admin-modal class="hidden fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm" aria-modal="true" role="dialog">
    <div class="bg-white rounded-xl shadow-xl max-w-md w-full p-6 relative">
        <h3 class="text-lg font-semibold text-gray-900 mb-2">Delete purchase</h3>
        <p class="text-sm text-gray-600 mb-6">Are you sure you want to delete <span id="purchase-delete-number" class="font-medium text-gray-900"></span>? This cannot be undone.</p>
        <form id="purchase-delete-form" method="POST" class="flex flex-col-reverse sm:flex-row justify-end gap-3">
            @csrf
            @method('DELETE')
            <button type="button" onclick="closePurchaseDeleteModal()" class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors">
                Cancel
            </button>
            <button type="submit" class="px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-lg hover:bg-red-700 transition-colors">
                Delete
            </button>
        </form>
    </div>
</div>

<script>
function openPurchaseDeleteModal(id, purchaseNumber) {
    if (typeof window.adminFixedActionMenuCloseAll === 'function') {
        window.adminFixedActionMenuCloseAll();
    }
    document.getElementById('purchase-delete-number').textContent = purchaseNumber;
    document.getElementById('purchase-delete-form').action = '{{ url('/admin/purchases') }}/' + id;
    var modal = document.getElementById('purchase-delete-modal');
    modal.classList.remove('hidden');
    modal.classList.add('flex');
}

function closePurchaseDeleteModal() {
    var modal = document.getElementById('purchase-delete-modal');
    modal.classList.add('hidden');
    modal.classList.remove('flex');
}

document.getElementById('purchase-delete-modal')?.addEventListener('click', function (e) {
    if (e.target === this) {
        closePurchaseDeleteModal();
    }
});
</script>
@endsection
