@extends('layouts.admin')

@section('title', 'Unbagging')

@section('content')
<div class="container mx-auto px-4 sm:px-6 lg:px-8 py-4">
    <div class="flex justify-between items-center mb-4">
        <h1 class="text-2xl font-bold text-gray-800 flex items-center">
            <i class="fa-regular fa-box-open mr-2"></i> Unbagging
        </h1>
    </div>

    <div class="bg-white p-6 rounded-lg shadow-sm">
        <h2 class="text-lg font-semibold text-gray-900">Scan Bag</h2>
        <p class="mt-1 text-sm text-gray-600">Scan a bag's seal number to view its contents and mark parcels as received.</p>

        <form id="scan-bag-form" class="mt-4 flex items-center space-x-3">
            <div class="relative flex-grow">
                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                     <i class="fa-regular fa-barcode-read text-gray-400"></i>
                </div>
                <input type="text" id="bag_seal_number" name="bag_seal_number" class="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md leading-5 bg-white placeholder-gray-500 focus:outline-none focus:placeholder-gray-400 focus:ring-1 focus:ring-blue-500 focus:border-blue-500 sm:text-sm" placeholder="Scan or enter bag seal number..." autocomplete="off">
            </div>
            <button type="submit" class="inline-flex items-center justify-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                <i class="fa-regular fa-magnifying-glass mr-2"></i> Find Bag
            </button>
        </form>
    </div>

    <div id="unbagging-details-container" class="mt-6 bg-white p-6 rounded-lg shadow-sm hidden">
        <!-- Bag and parcel details will be injected here -->
    </div>

</div>
@endsection

@push('scripts')
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const form = document.getElementById('scan-bag-form');
        const bagInput = document.getElementById('bag_seal_number');
        const unbaggingDetailsContainer = document.getElementById('unbagging-details-container');

        form.addEventListener('submit', function (e) {
            e.preventDefault();
            const sealNumber = bagInput.value;

            if (sealNumber) {
                fetch('{{ route("branch.unbagging.find-bag") }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '{{ csrf_token() }}'
                    },
                    body: JSON.stringify({ 
                        bag_seal_number: sealNumber 
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        bagInput.value = ''; // Clear input
                        renderBagDetails(data.bag);
                    } else {
                        // Handle error
                        alert(data.message || 'An error occurred.');
                    }
                })
                .catch(error => console.error('Error:', error));
            }
        });

        function renderBagDetails(bag) {
            unbaggingDetailsContainer.innerHTML = `
                <div class="flex justify-between items-center mb-4">
                    <div>
                        <h3 class="text-lg font-semibold text-gray-900">Bag ID: ${bag.bag_number}</h3>
                        <p class="text-sm text-gray-600">Origin: ${bag.origin_branch.name}</p>
                    </div>
                    <button id="receive-bag-btn" data-bag-id="${bag.id}" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-green-600 hover:bg-green-700">Mark as Received</button>
                </div>
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tracking ID</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Recipient</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        ${bag.parcels.map(parcel => `
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${parcel.tracking_id}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${parcel.recipient_name}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${parcel.status}</td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            `;
            unbaggingDetailsContainer.classList.remove('hidden');

            const receiveBagBtn = document.getElementById('receive-bag-btn');
            receiveBagBtn.addEventListener('click', function () {
                const bagId = this.dataset.bagId;
                fetch(`/branch/unbagging/${bagId}/receive`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '{{ csrf_token() }}'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        unbaggingDetailsContainer.innerHTML = '<p class="text-green-600">Bag marked as received.</p>';
                        setTimeout(() => location.reload(), 2000);
                    } else {
                        alert('Failed to mark the bag as received.');
                    }
                })
                .catch(error => console.error('Error:', error));
            });
        }
    });
</script>
@endpush
