@extends('layouts.app')

@section('title', 'Create Outward Gate Pass')

@push('plugin-styles')
<link rel="stylesheet" href="{{ asset('theme/vendors/select2/select2.min.css') }}">
<link rel="stylesheet" href="{{ asset('theme/vendors/select2-bootstrap-5-theme/select2-bootstrap-5-theme.min.css') }}">
<style>
    .required:after {
        content: ' *';
        color: red;
    }
    .invoice-card {
        border: 1px solid #dee2e6;
        border-radius: 0.375rem;
        margin-bottom: 1rem;
    }
    .invoice-header {
        background-color: #f8f9fa;
        padding: 0.75rem 1rem;
        border-bottom: 1px solid #dee2e6;
        border-radius: 0.375rem 0.375rem 0 0;
    }
    .invoice-body {
        padding: 1rem;
    }
    .item-row {
        border: 1px solid #e9ecef;
        border-radius: 0.25rem;
        padding: 0.5rem;
        margin-bottom: 0.5rem;
        background-color: #f8f9fa;
    }
    .select2-container--bootstrap-5 .select2-selection {
        border: 1px solid #dee2e6;
        border-radius: 0.375rem;
        min-height: 38px;
    }
    .select2-container--bootstrap-5 .select2-selection__rendered {
        padding: 0.375rem 0.75rem;
        font-size: 0.875rem;
        line-height: 1.5;
    }
    .select2-container--bootstrap-5 .select2-selection__choice {
        background-color: #e9ecef;
        border: 1px solid #adb5bd;
        border-radius: 0.25rem;
        padding: 0.125rem 0.5rem;
        margin: 0.125rem 0.25rem 0.125rem 0;
        font-size: 0.75rem;
    }
    .select2-container--bootstrap-5 .select2-selection__choice__remove {
        color: #6c757d;
        margin-right: 0.25rem;
    }


    .dd-item:hover { background: #f8f9fa; }
.dd-item.selected { background: #E6F1FB; }
.dd-item.selected .dd-chk { background: #378ADD !important; border-color: #378ADD !important; }
.dd-item.selected .dd-chk i { display: block !important; }

</style>
@endpush

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">Create Outward Gate Pass</h5>
                </div>
                <div class="card-body">
                    @if($errors->any())
                        <div class="alert alert-danger">
                            <ul class="mb-0">
                                @foreach($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    @endif

                    <form id="outwardGatePassForm" action="{{ route('outward-gate-passes.store') }}" method="POST">
                        @csrf

                        <!-- Factory Invoice Selection -->
                        {{-- <div class="row g-3 mb-4">
                            <div class="col-md-12">
                                <label for="factory_invoice_ids" class="form-label required">Factory Invoices</label>
                                <select id="factory_invoice_ids" name="factory_invoice_ids[]" class="form-select @error('factory_invoice_ids') is-invalid @enderror" multiple required>
                                    @foreach($factoryInvoices as $invoice)
                                        <option value="{{ $invoice->id }}"
                                                data-invoice-number="{{ $invoice->invoice_number }}"
                                                data-customer-name="{{ $invoice->customer->name ?? 'N/A' }}"
                                                data-items="{{ $invoice->items->toJson() }}">
                                            Invoice #{{ $invoice->invoice_number }} | {{ $invoice->customer->name ?? 'N/A' }} | {{ $invoice->items->count() }} items | {{ $invoice->invoice_date->format('M d, Y') }}
                                        </option>
                                    @endforeach
                                </select>
                                <small class="form-text text-muted">You can select multiple invoices for this gatepass</small>
                                @error('factory_invoice_ids')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div> --}}

                        {{-- Factory Invoice Selection --}}
                        <div class="row g-3 mb-4">
                            <div class="col-md-12">

                                <label class="form-label required">
                                    <i class="ti ti-file-invoice me-1"></i> Factory Invoices
                                </label>

                                {{-- Bootstrap Dropdown --}}
                                <div class="dropdown w-100">

                                    {{-- Trigger --}}
                                    <button class="form-control dropdown-toggle text-start d-flex align-items-center justify-content-between"
                                            type="button"
                                            data-bs-toggle="dropdown"
                                            aria-expanded="false">

                                        <span id="dd-text" class="text-muted" style="font-size:14px">
                                            Select invoices…
                                        </span>

                                    </button>

                                    {{-- Dropdown Panel --}}
                                    <div class="dropdown-menu w-100 p-0 shadow-sm"
                                        style="max-height:260px;overflow-y:auto;">

                                        @foreach($factoryInvoices as $invoice)
                                        <div class="dropdown-item d-flex justify-content-between align-items-center px-3 py-2 dd-item"
                                            data-id="{{ $invoice->id }}"
                                            data-number="{{ $invoice->invoice_number }}"
                                            data-customer="{{ $invoice->customer->name ?? 'N/A' }}"
                                            data-items='@json($invoice->items)'
                                            data-date="{{ $invoice->invoice_date->format('M d, Y') }}"
                                            style="cursor:pointer;">

                                            {{-- LEFT SIDE --}}
                                            <div class="d-flex align-items-center gap-2">

                                                <input type="checkbox" class="form-check-input m-0 dd-check">

                                                <div>
                                                    <div class="fw-semibold" style="font-size:13px">
                                                        #{{ $invoice->invoice_number }}
                                                    </div>
                                                    <div class="text-muted" style="font-size:11px">
                                                        {{ $invoice->customer->name ?? 'N/A' }}
                                                    </div>
                                                </div>

                                            </div>

                                            {{-- RIGHT SIDE --}}
                                            <div class="text-end">
                                                <span class="badge bg-light text-primary">
                                                    {{ $invoice->items->count() }}
                                                </span>
                                                <div class="text-muted" style="font-size:11px">
                                                    {{ $invoice->invoice_date->format('M d, Y') }}
                                                </div>
                                            </div>

                                        </div>
                                        @endforeach

                                    </div>
                                </div>

                                {{-- Helper text --}}
                                <small class="text-muted d-flex align-items-center gap-1 mt-1">
                                    <i class="ti ti-info-circle" style="font-size:12px"></i>
                                    Click to open and select one or more invoices
                                </small>

                                @error('factory_invoice_ids')
                                    <div class="invalid-feedback d-block">{{ $message }}</div>
                                @enderror

                            </div>
                        </div>

                        <!-- Selected Invoices Display -->
                        <div id="selectedInvoicesContainer" class="mb-4">
                            <!-- Invoices will be displayed here -->
                        </div>

                        <!-- Vehicle and Driver Information -->
                        <div class="row g-3 mb-4">
                            <div class="col-md-4">
                                <label for="vehicle_no" class="form-label required">Vehicle Number</label>
                                <input type="text" id="vehicle_no" name="vehicle_no" class="form-control @error('vehicle_no') is-invalid @enderror" value="{{ old('vehicle_no') }}" required>
                                @error('vehicle_no')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                            <div class="col-md-4">
                                <label for="driver_name" class="form-label required">Driver Name</label>
                                <input type="text" id="driver_name" name="driver_name" class="form-control @error('driver_name') is-invalid @enderror" value="{{ old('driver_name') }}" required>
                                @error('driver_name')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                            <div class="col-md-4">
                                <label for="other_persons" class="form-label">Other Persons</label>
                                <input type="text" id="other_persons" name="other_persons" class="form-control" value="{{ old('other_persons') }}" placeholder="Other persons accompanying">
                            </div>
                        </div>

                        <div class="row g-3 mb-4">
                            <div class="col-12">
                                <label for="remarks" class="form-label">Remarks</label>
                                <textarea id="remarks" name="remarks" class="form-control" rows="2" placeholder="Any additional remarks">{{ old('remarks') }}</textarea>
                            </div>
                        </div>

                        <div class="d-flex gap-2 mt-4">
                            <button type="submit" class="btn btn-primary" id="submitBtn">
                                <i class="fas fa-save me-2"></i>Create Gate Pass
                            </button>
                            <a href="{{ route('outward-gate-passes.index') }}" class="btn btn-secondary">
                                <i class="fas fa-times me-2"></i>Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('plugin-scripts')
<script src="{{ asset('theme/vendors/select2/select2.min.js') }}"></script>
<script>

// document.addEventListener('DOMContentLoaded', function() {
//     // Initialize select2 for factory invoices (multiple selection)
//     $('#factory_invoice_ids').select2({
//         theme: 'bootstrap-5',
//         placeholder: 'Select Factory Invoices',
//         allowClear: true,
//         multiple: true
//     });

//     // Handle invoice selection
//     $('#factory_invoice_ids').on('change', function() {
//         const selectedOptions = $(this).find('option:selected');
//         const container = $('#selectedInvoicesContainer');

//         container.empty();

//         if (selectedOptions.length > 0) {
//             selectedOptions.each(function(index) {
//                 const invoiceId = $(this).val();
//                 const invoiceNumber = $(this).data('invoice-number');
//                 const customerName = $(this).data('customer-name');
//                 const items = $(this).data('items');

//                 addInvoiceToContainer(invoiceId, invoiceNumber, customerName, items, index);
//             });
//         }
//     });

//     function addInvoiceToContainer(invoiceId, invoiceNumber, customerName, items, invoiceIndex) {
//         const container = $('#selectedInvoicesContainer');

//         const invoiceCard = `
//             <div class="invoice-card" data-invoice-id="${invoiceId}">
//                 <div class="invoice-header">
//                     <div class="d-flex justify-content-between align-items-center">
//                         <h6 class="mb-0">Invoice #${invoiceNumber} - ${customerName}</h6>
//                         <button type="button" class="btn btn-sm btn-outline-danger remove-invoice" data-invoice-id="${invoiceId}">
//                             <i class="fas fa-times"></i> Remove
//                         </button>
//                     </div>
//                 </div>
//                 <div class="invoice-body">
//                     <div class="table-responsive">
//                         <table class="table table-sm">
//                             <thead>
//                                 <tr>
//                                     <th>Item</th>
//                                     <th>Ordered Qty</th>
//                                     <th>Picked Qty</th>
//                                     {{-- <th>Quantity to Dispatch</th> --}}
//                                 </tr>
//                             </thead>
//                             <tbody>
//                                 ${items.map((item, itemIndex) => `
//                                     <tr>
//                                         <td>${item.item?.name || 'Unknown Item'}</td>
//                                         <td>${item.ordered_quantity}</td>
//                                         <td>${item.picked_quantity || item.ordered_quantity}</td>
//                                         {{-- <td>
//                                             <input type="hidden" name="invoices[${invoiceIndex}][id]" value="${invoiceId}">
//                                             <input type="hidden" name="invoices[${invoiceIndex}][items][${itemIndex}][item_id]" value="${item.id}">
//                                             <input type="number" class="form-control form-control-sm"
//                                                    name="invoices[${invoiceIndex}][items][${itemIndex}][quantity]"
//                                                    min="0.01" max="${item.picked_quantity || item.ordered_quantity}"
//                                                    step="0.01" required>
//                                         </td> --}}
//                                         <td>
//                                             <input type="hidden" name="invoices[${invoiceIndex}][id]" value="${invoiceId}">
//                                             <input type="hidden" name="invoices[${invoiceIndex}][items][${itemIndex}][item_id]" value="${item.id}">
//                                             <input type="hidden" name="invoices[${invoiceIndex}][items][${itemIndex}][quantity]" value="${item.picked_quantity || item.ordered_quantity}">
//                                         </td>
//                                     </tr>
//                                 `).join('')}
//                             </tbody>
//                         </table>
//                     </div>
//                 </div>
//             </div>
//         `;

//         container.append(invoiceCard);

//         // Handle remove invoice
//         $('.remove-invoice[data-invoice-id="' + invoiceId + '"]').on('click', function() {
//             $(this).closest('.invoice-card').remove();
//             // Remove from select2
//             const option = $('#factory_invoice_ids option[value="' + invoiceId + '"]');
//             option.prop('selected', false);
//             $('#factory_invoice_ids').trigger('change');
//         });
//     }

//     // Form validation
//     $('#outwardGatePassForm').on('submit', function(e) {
//         const selectedInvoices = $('#factory_invoice_ids').val();
//         if (!selectedInvoices || selectedInvoices.length === 0) {
//             e.preventDefault();
//             alert('Please select at least one factory invoice');
//             return false;
//         }

//         // Check if at least one item has quantity
//         const quantityInputs = $('input[name*="[quantity]"]');
//         let hasQuantity = false;
//         quantityInputs.each(function() {
//             if (parseFloat($(this).val()) > 0) {
//                 hasQuantity = true;
//                 return false;
//             }
//         });

//         if (!hasQuantity) {
//             e.preventDefault();
//             alert('Please enter quantity for at least one item');
//             return false;
//         }
//     });
// });


// document.addEventListener('DOMContentLoaded', function () {

//     const selectedMap = new Map();

//     // =========================
//     // COUNTER UPDATE
//     // =========================
//     function updateDropdownCounter() {
//         const count = selectedMap.size;
//         const ddText = document.getElementById('dd-text');

//         ddText.innerText = count > 0
//             ? `${count} invoice(s) selected`
//             : 'Select invoices…';
//     }

//     // =========================
//     // ADD INVOICE CARD (same design)
//     // =========================
//     function addInvoiceToContainer(invoiceId, invoiceNumber, customerName, items, invoiceIndex) {

//         const container = $('#selectedInvoicesContainer');

//         const invoiceCard = `
//             <div class="invoice-card" data-invoice-id="${invoiceId}">
//                 <div class="invoice-header">
//                     <div class="d-flex justify-content-between align-items-center">
//                         <h6 class="mb-0">Invoice #${invoiceNumber} - ${customerName}</h6>
//                         <button type="button" class="btn btn-sm btn-outline-danger remove-invoice" data-invoice-id="${invoiceId}">
//                             <i class="fas fa-times"></i> Remove
//                         </button>
//                     </div>
//                 </div>

//                 <div class="invoice-body">
//                     <div class="table-responsive">
//                         <table class="table table-sm">
//                             <thead>
//                                 <tr>
//                                     <th>Item</th>
//                                     <th>Ordered Qty</th>
//                                     <th>Picked Qty</th>
//                                 </tr>
//                             </thead>
//                             <tbody>
//                                 ${items.map((item, itemIndex) => `
//                                     <tr>
//                                         <td>${item.item?.name || 'Unknown Item'}</td>
//                                         <td>${item.ordered_quantity}</td>
//                                         <td>${item.picked_quantity || item.ordered_quantity}</td>

//                                         <td>
//                                             <input type="hidden" name="invoices[${invoiceIndex}][id]" value="${invoiceId}">
//                                             <input type="hidden" name="invoices[${invoiceIndex}][items][${itemIndex}][item_id]" value="${item.id}">
//                                             <input type="hidden" name="invoices[${invoiceIndex}][items][${itemIndex}][quantity]" value="${item.picked_quantity || item.ordered_quantity}">
//                                         </td>
//                                     </tr>
//                                 `).join('')}
//                             </tbody>
//                         </table>
//                     </div>
//                 </div>
//             </div>
//         `;

//         container.append(invoiceCard);
//     }

//     // =========================
//     // HANDLE DROPDOWN CLICK
//     // =========================
//     document.querySelectorAll('.dd-item').forEach(item => {

//         item.addEventListener('click', function () {

//             const id = String(this.dataset.id);
//             const number = this.dataset.number;
//             const customer = this.dataset.customer;
//             const items = JSON.parse(this.dataset.items || '[]');

//             const checkbox = this.querySelector('.dd-check');

//             if (selectedMap.has(id)) {

//                 // REMOVE SELECTION
//                 selectedMap.delete(id);
//                 checkbox.checked = false;

//                 // REMOVE CARD (Select2-style behavior)
//                 document.querySelector(`.invoice-card[data-invoice-id="${id}"]`)?.remove();

//             } else {

//                 // ADD SELECTION
//                 selectedMap.set(id, {
//                     id,
//                     number,
//                     customer,
//                     items
//                 });

//                 checkbox.checked = true;

//                 addInvoiceToContainer(
//                     id,
//                     number,
//                     customer,
//                     items,
//                     selectedMap.size
//                 );
//             }

//             updateDropdownCounter();
//         });
//     });

//     // =========================
//     // REMOVE BUTTON 
//     // =========================
//     $(document).on('click', '.remove-invoice', function () {

//         const id = String($(this).data('invoice-id'));

//         // remove from state
//         selectedMap.delete(id);

//         // remove DOM (same as your old working code)
//         $(this).closest('.invoice-card').remove();

//         // uncheck dropdown checkbox
//         const checkbox = document.querySelector(`.dd-item[data-id="${id}"] .dd-check`);
//         if (checkbox) checkbox.checked = false;

//         updateDropdownCounter();
//     });

// });


document.addEventListener('DOMContentLoaded', function () {

    const selectedMap = new Map();

    function updateDropdownCounter() {
        const count = selectedMap.size;
        document.getElementById('dd-text').innerText = count > 0
            ? `${count} invoice(s) selected`
            : 'Select invoices…';
    }

    function addInvoiceToContainer(invoiceId, invoiceNumber, customerName, items, invoiceIndex) {
        const container = $('#selectedInvoicesContainer');
        const invoiceCard = `
            <div class="invoice-card" data-invoice-id="${invoiceId}">
                <div class="invoice-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <h6 class="mb-0">Invoice #${invoiceNumber} - ${customerName}</h6>
                        <button type="button" class="btn btn-sm btn-outline-danger remove-invoice"
                                data-invoice-id="${invoiceId}">
                            <i class="fas fa-times"></i> Remove
                        </button>
                    </div>
                </div>
                <div class="invoice-body">
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>Item</th>
                                    <th>Ordered Qty</th>
                                    <th>Picked Qty</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${items.map((item, itemIndex) => `
                                    <tr>
                                        <td>${item.item?.name || 'Unknown Item'}</td>
                                        <td>${item.ordered_quantity}</td>
                                        <td>${item.picked_quantity || item.ordered_quantity}</td>
                                        <td>
                                            <input type="hidden" name="invoices[${invoiceIndex}][id]" value="${invoiceId}">
                                            <input type="hidden" name="invoices[${invoiceIndex}][items][${itemIndex}][item_id]" value="${item.id}">
                                            <input type="hidden" name="invoices[${invoiceIndex}][items][${itemIndex}][quantity]" value="${item.picked_quantity || item.ordered_quantity}">
                                        </td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        `;
        container.append(invoiceCard);
    }

    function addHiddenInput(id) {
        const input = document.createElement('input');
        input.type  = 'hidden';
        input.name  = 'factory_invoice_ids[]';
        input.value = id;
        input.id    = `factory_invoice_hidden_${id}`;
        document.getElementById('outwardGatePassForm').appendChild(input);
    }

    // After every add OR remove, reindex all cards
    function reindexCards() {
        document.querySelectorAll('.invoice-card').forEach(function (card, index) {
            card.querySelectorAll('input[type="hidden"]').forEach(function (input) {
                input.name = input.name.replace(/invoices\[\d+\]/, `invoices[${index}]`);
            });
        });
    }


    function removeHiddenInput(id) {
        document.getElementById(`factory_invoice_hidden_${id}`)?.remove();
    }

    document.querySelectorAll('.dd-item').forEach(function (item) {
        item.addEventListener('click', function (e) {
            e.stopPropagation();

            const id       = String(this.dataset.id);
            const number   = this.dataset.number;
            const customer = this.dataset.customer;
            const items    = JSON.parse(this.dataset.items || '[]');
            const checkbox = this.querySelector('.dd-check');

            if (selectedMap.has(id)) {
                selectedMap.delete(id);
                checkbox.checked = false;
                document.querySelector(`.invoice-card[data-invoice-id="${id}"]`)?.remove();
                removeHiddenInput(id);
            } else {
                selectedMap.set(id, { id, number, customer, items });
                checkbox.checked = true;
                addHiddenInput(id);
                addInvoiceToContainer(id, number, customer, items, selectedMap.size - 1);
                reindexCards(); 
            }

            updateDropdownCounter();
        });
    });

    $(document).on('click', '.remove-invoice', function () {
        const id = String($(this).data('invoice-id'));
        selectedMap.delete(id);
        $(this).closest('.invoice-card').remove();
        removeHiddenInput(id);
        const checkbox = document.querySelector(`.dd-item[data-id="${id}"] .dd-check`);
        if (checkbox) checkbox.checked = false;
        updateDropdownCounter();
        $(this).closest('.invoice-card').remove();
        reindexCards(); // ← add this
    });

});


</script>
@endpush
