@extends('layouts.admin')

@section('title', 'Purchase Orders')

@section('page-title', 'Purchase Orders')

@section('content')
<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">Purchase Orders</h1>
        <div class="flex items-center gap-3">
            <form method="GET" action="{{ route('admin.purchase-orders.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>
            <a href="{{ route('admin.purchase-orders.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 Order</span>
            </a>
        </div>
    </div>

    <!-- Search Bar -->
    <div class="mb-4">
        <form method="GET" action="{{ route('admin.purchase-orders.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.purchase-orders.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>

    <!-- Purchase Orders Table -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="overflow-x-auto">
            <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-xs font-semibold uppercase tracking-wider text-gray-500 min-w-[150px]">ORDER NUMBER</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 min-w-[150px]">ORDER 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-[120px]">PAYMENT MODE</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 min-w-[120px]">CREATED ON</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 min-w-[100px]">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($purchaseOrders as $index => $purchaseOrder)
                        <tr class="group hover:bg-gray-50/50 transition-colors">
                            <td class="py-4 px-6 text-sm text-gray-600">{{ ($purchaseOrders->currentPage() - 1) * $purchaseOrders->perPage() + $index + 1 }}</td>
                            <td class="py-4 px-6">
                                <a href="{{ route('admin.purchase-orders.show', $purchaseOrder) }}" class="text-sm font-medium text-primary hover:text-blue-600 transition-colors">
                                    {{ $purchaseOrder->order_number }}
                                </a>
                            </td>
                            <td class="py-4 px-6 text-sm text-gray-600 whitespace-nowrap">
                                {{ $purchaseOrder->order_date ? $purchaseOrder->order_date->format('d-m-Y') : '-' }}
                            </td>
                            <td class="py-4 px-6">
                                @if($purchaseOrder->supplier)
                                    <div class="flex items-center gap-2">
                                        <div class="size-8 rounded-full bg-primary flex items-center justify-center text-white font-bold text-xs shrink-0">
                                            @if($purchaseOrder->supplier->image && Storage::disk('public')->exists($purchaseOrder->supplier->image))
                                                <img src="{{ Storage::disk('public')->url($purchaseOrder->supplier->image) }}" alt="{{ $purchaseOrder->supplier->name }}" class="w-full h-full rounded-full object-cover">
                                            @else
                                                {{ strtoupper(substr($purchaseOrder->supplier->name ?? 'N', 0, 1)) }}
                                            @endif
                                        </div>
                                        <span class="text-sm text-gray-900">{{ $purchaseOrder->supplier->name }}</span>
                                    </div>
                                @else
                                    <span class="text-gray-400">-</span>
                                @endif
                            </td>
                            <td class="py-4 px-6 text-sm font-medium text-gray-900 text-right">
                                {{ \App\Models\Currency::formatAmount($purchaseOrder->total, $purchaseOrder->currency ?? null) }}
                            </td>
                            <td class="py-4 px-6">
                                @php
                                    $paymentMode = str_replace('_', ' ', $purchaseOrder->payment_method ?? 'cash');
                                    $paymentColors = [
                                        'cash' => 'bg-green-100 text-green-700',
                                        'bank transfer' => 'bg-blue-100 text-blue-700',
                                        'credit card' => 'bg-purple-100 text-purple-700',
                                        'cheque' => 'bg-yellow-100 text-yellow-700',
                                    ];
                                    $paymentColor = $paymentColors[strtolower($paymentMode)] ?? 'bg-gray-100 text-gray-700';
                                @endphp
                                <span class="px-2 py-1 text-xs font-medium rounded-full {{ $paymentColor }} capitalize">
                                    {{ $paymentMode }}
                                </span>
                            </td>
                            <td class="py-4 px-6 text-sm text-gray-600 whitespace-nowrap">
                                {{ $purchaseOrder->created_at ? $purchaseOrder->created_at->format('d-m-Y') : '-' }}
                            </td>
                            <td class="py-4 px-6">
                                @php
                                    $statusColors = [
                                        'new' => 'bg-blue-100 text-blue-700',
                                        'pending' => 'bg-yellow-100 text-yellow-700',
                                        'approved' => 'bg-green-100 text-green-700',
                                        'rejected' => 'bg-red-100 text-red-700',
                                        'completed' => 'bg-green-100 text-green-700',
                                        'cancelled' => 'bg-gray-100 text-gray-700',
                                    ];
                                    $statusColor = $statusColors[$purchaseOrder->status] ?? 'bg-gray-100 text-gray-700';
                                    $statusIcons = [
                                        'new' => 'add',
                                        'pending' => 'schedule',
                                        'approved' => 'check_circle',
                                        'rejected' => 'cancel',
                                        'completed' => 'check_circle',
                                        'cancelled' => 'close',
                                    ];
                                    $statusIcon = $statusIcons[$purchaseOrder->status] ?? 'circle';
                                @endphp
                                <span class="px-2 py-1 text-xs font-medium rounded-full {{ $statusColor }} flex items-center gap-1 w-fit">
                                    <span class="material-symbols-outlined text-sm">{{ $statusIcon }}</span>
                                    {{ ucfirst($purchaseOrder->status) }}
                                </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-{{ $purchaseOrder->id }}" onclick="adminFixedActionMenuToggle(event || window.event, 'action-menu-{{ $purchaseOrder->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-{{ $purchaseOrder->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.purchase-orders.show', $purchaseOrder) }}" 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">visibility</span>
                                                <span>View</span>
                                            </a>
                                            <a href="{{ route('admin.purchase-orders.edit', $purchaseOrder) }}" 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="openDeleteModal({{ $purchaseOrder->id }}, @js($purchaseOrder->order_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 border-t border-gray-100">
                                                <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_bag</span>
                                <p>No purchase orders found</p>
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        @if($purchaseOrders->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">{{ $purchaseOrders->firstItem() }}</span> to <span class="font-medium text-gray-900">{{ $purchaseOrders->lastItem() }}</span> of <span class="font-medium text-gray-900">{{ $purchaseOrders->total() }}</span> entries
                </p>
                <div class="flex items-center gap-1">
                    @if($purchaseOrders->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="{{ $purchaseOrders->previousPageUrl() }}" class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50">
                            <
                        </a>
                    @endif
                    
                    @php
                        $currentPage = $purchaseOrders->currentPage();
                        $lastPage = $purchaseOrders->lastPage();
                        $startPage = max(1, $currentPage - 1);
                        $endPage = min($lastPage, $currentPage + 1);
                    @endphp
                    
                    @if($startPage > 1)
                        <a href="{{ $purchaseOrders->url(1) }}" class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50">1</a>
                        @if($startPage > 2)
                            <span class="px-3 py-1 text-sm text-gray-500">...</span>
                        @endif
                    @endif
                    
                    @for($page = $startPage; $page <= $endPage; $page++)
                        <a href="{{ $purchaseOrders->url($page) }}" class="px-3 py-1 text-sm rounded {{ $page == $currentPage ? 'bg-primary text-white' : 'text-gray-500 hover:bg-gray-50' }}">
                            {{ $page }}
                        </a>
                    @endfor
                    
                    @if($endPage < $lastPage)
                        @if($endPage < $lastPage - 1)
                            <span class="px-3 py-1 text-sm text-gray-500">...</span>
                        @endif
                        <a href="{{ $purchaseOrders->url($lastPage) }}" class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50">{{ $lastPage }}</a>
                    @endif
                    
                    @if($purchaseOrders->hasMorePages())
                        <a href="{{ $purchaseOrders->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>
        @else
            <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">0</span> to <span class="font-medium text-gray-900">0</span> of <span class="font-medium text-gray-900">0</span> entries
                </p>
            </div>
        @endif
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div id="deleteModal" data-admin-modal class="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 hidden items-center justify-center">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-md m-4">
        <div class="p-6">
            <h3 class="text-lg font-semibold text-gray-900 mb-2">Delete Purchase Order</h3>
            <p class="text-sm text-gray-600 mb-6">Are you sure you want to delete purchase order <span id="delete-order-number" class="font-medium"></span>? This action cannot be undone.</p>
            <div class="flex items-center justify-end gap-3">
                <button onclick="closeDeleteModal()" class="px-4 py-2 text-sm text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">
                    Cancel
                </button>
                <form id="delete-form" method="POST" class="inline">
                    @csrf
                    @method('DELETE')
                    <button type="submit" class="px-4 py-2 text-sm text-white bg-red-600 rounded-lg hover:bg-red-700 transition-colors">
                        Delete
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
function openDeleteModal(id, orderNumber) {
    if (typeof window.adminFixedActionMenuCloseAll === 'function') {
        window.adminFixedActionMenuCloseAll();
    }
    document.getElementById('delete-order-number').textContent = orderNumber;
    document.getElementById('delete-form').action = `{{ route('admin.purchase-orders.index') }}/${id}`;
    document.getElementById('deleteModal').classList.remove('hidden');
    document.getElementById('deleteModal').classList.add('flex');
}

function closeDeleteModal() {
    document.getElementById('deleteModal').classList.add('hidden');
    document.getElementById('deleteModal').classList.remove('flex');
}
</script>
@endpush
@endsection
