@php($isEdit = isset($gatePass))
<form id="gatePassForm"  action="{{ $isEdit ? route('gatepasses.update', $gatePass) : route('gatepasses.store') }}" method="POST">
    @csrf
    @if($isEdit)
        @method('PUT')
    @endif

    <input type="hidden" name="type" value="inward">

    <div class="row g-3">
        <!-- <div class="col-md-3">
            <label for="gate_pass_number" class="form-label required">GP Number *</label>
            <input type="text" id="gate_pass_number" name="gate_pass_number" class="form-control @error('gate_pass_number') is-invalid @enderror" value="{{ old('gate_pass_number', $isEdit ? $gatePass->gate_pass_number : ($gpNumber ?? '')) }}" readonly required>
            @if(!$isEdit)
                <small class="form-text text-muted">
                    <i class="fas fa-magic"></i> Auto-generated GP number
                </small>
            @endif
            @error('gate_pass_number')
                <div class="invalid-feedback">{{ $message }}</div>
            @enderror
        </div> -->
        <div class="col-md-3">
    <label for="gate_pass_number" class="form-label required">GP Number *</label>
    <input type="text"
           id="gate_pass_number"
           name="gate_pass_number"
           class="form-control @error('gate_pass_number') is-invalid @enderror"
           value="{{ old('gate_pass_number', $isEdit ? $gatePass->gate_pass_number : ($gpNumber ?? '')) }}"
           readonly required>

    @if(!$isEdit)
        <small class="form-text text-muted">
            <i class="fas fa-magic"></i> Auto-generated GP number
        </small>
    @endif

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


        <div class="col-md-3">
            <label for="po_id" class="form-label required">PO Number *</label>
            <select id="po_id" name="purchase_order_id" class="form-select @error('purchase_order_id') is-invalid @enderror" required {{ $isEdit ? 'disabled' : '' }}>
                <option value="">Select PO</option>
                @if($isEdit && $gatePass->purchaseOrder)
                    <option value="{{ $gatePass->purchase_order_id }}" selected>
                        {{ $gatePass->purchaseOrder->po_number }}
                    </option>
                @endif
            </select>
            @error('purchase_order_id')
                <div class="invalid-feedback">{{ $message }}</div>
            @enderror
        </div>

        <div class="col-md-3">
            <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', $isEdit ? $gatePass->vehicle_no : '') }}" required>
            @error('vehicle_no')
                <div class="invalid-feedback">{{ $message }}</div>
            @enderror
        </div>

        <div class="col-md-3">
            <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', $isEdit ? $gatePass->driver_name : '') }}" required>
            @error('driver_name')
                <div class="invalid-feedback">{{ $message }}</div>
            @enderror
        </div>
    </div>

    <hr class="my-4">
    <h4 class="m-3 text-center">Items</h4>
    <div class="table-responsive">
        <table class="table table-bordered" id="itemsTable">
            <thead class="table-light">
                <tr>
                    <th>Item</th>
                    <th>PO Quantity</th>
                    <th>Remaining Qty</th>
                    <th>DN Quantity</th>
                    <th>Unit</th>
                </tr>
            </thead>
            <tbody>
                @if($isEdit)
                    @foreach($gatePass->items as $item)
                    <tr>
                        <td>{{ optional($item->item)->name }}</td>
                        <td>{{ number_format(optional($item->purchaseOrderItem)->quantity ?? 0, 2) }}</td>
                        <td>{{ number_format((optional($item->purchaseOrderItem)->quantity ?? 0) - ($item->purchaseOrderItem->gatePassItems->sum('dn_quantity') ?? 0), 2) }}</td>
                        <td>
                            <input type="hidden" name="items[{{ $item->id }}][item_id]" value="{{ $item->item_id }}">
                            <input type="hidden" name="items[{{ $item->id }}][po_item_id]" value="{{ $item->purchase_order_item_id }}">
                            <input type="hidden" name="items[{{ $item->id }}][uom_id]" value="{{ $item->uom_id }}">
                            <input type="number"
                                class="form-control dn-quantity @error('items.'.$item->id.'.dn_quantity') is-invalid @enderror"
                                name="items[{{ $item->id }}][dn_quantity]"
                                value="{{ old('items.'.$item->id.'.dn_quantity', $item->dn_quantity) }}"
                                min="0.01"
                                max="{{ (optional($item->purchaseOrderItem)->quantity ?? 0) - ($item->purchaseOrderItem->gatePassItems->where('id', '!=', $item->id)->sum('dn_quantity') ?? 0) }}"
                                step="0.01"
                                {{ $isEdit ? 'readonly' : '' }}
                            >
                            @error('items.'.$item->id.'.dn_quantity')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </td>
                        <td>{{ optional($item->uom)->name }}</td>
                    </tr>
                    @endforeach
                @endif
            </tbody>
        </table>
    </div>

    <div class="d-flex gap-2 mt-4">
        <button type="submit" class="btn btn-primary" id="submitBtn" {{ $isEdit ? 'disabled' : '' }}>
            {{ $isEdit ? 'Update' : 'Create' }}
        </button>
        {{-- <a href="{{ route('gatepasses.index') }}" class="btn btn-secondary">Cancel</a> --}}
    </div>
</form>

@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;
}
.select2-container {
    width: 100% !important;
}
.select2-container--bootstrap-5 .select2-selection {
    min-height: 45px;
    padding: 0.375rem 0.75rem;
    font-size: 1rem;
    border: 1px solid #dee2e6;
    border-radius: 4px;
}
.select2-container--bootstrap-5 .select2-selection--single .select2-selection__rendered {
    padding: 0;
    line-height: 1.5;
}
input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}
input[type="number"] {
    -moz-appearance: textfield;
}
</style>
@endpush

@push('plugin-scripts')
<script src="{{ asset('theme/vendors/select2/select2.min.js') }}"></script>
<script>
window.SKIP_ERROR_HANDLING = true;
document.addEventListener('DOMContentLoaded', function () {
    const poSelect = $('#po_id');
    poSelect.select2({
        theme: 'bootstrap-5',
        placeholder: 'Select PO',
        allowClear: true,
        ajax: {
            url: '{{ route("purchase-orders.search") }}',
            dataType: 'json',
            delay: 250,
            data: function(params) {
                return {
                    q: params.term || '',
                    status: 'open,partial'
                };
            },
            processResults: function(data) {
                return {
                    results: data.map(po => ({
                        id: po.id,
                        text: po.po_number
                    }))
                };
            },
            cache: true
        }
    });

    @if(!$isEdit)
    poSelect.on('select2:select select2:unselect', function(e) {
        const poId = $(this).val();
        const tbody = $('#itemsTable tbody');

        // Clear table and disable submit button
        tbody.empty();
        $('#submitBtn').prop('disabled', true);

        if (!poId) {
            return;
        }

        // Load PO items with remaining quantities
        $.get(`{{ route('purchase-orders.items', ':id') }}`.replace(':id', poId), function(data) {
            tbody.empty();

            data.forEach(item => {
                const remainingQty = item.quantity - (item.received_quantity || 0);
                tbody.append(`
                    <tr>
                        <td>${item.item_name}</td>
                        <td>${item.quantity}</td>
                        <td>${remainingQty}</td>
                        <td>
                            <input type="hidden" name="items[${item.id}][item_id]" value="${item.item_id}">
                            <input type="hidden" name="items[${item.id}][po_item_id]" value="${item.id}">
                            <input type="hidden" name="items[${item.id}][uom_id]" value="${item.uom_id}">
                            <input type="number"
                                class="form-control dn-quantity"
                                name="items[${item.id}][dn_quantity]"
                                min="0.01"
                                max="${remainingQty}"
                                step="0.01"
                                onchange="validateQuantity(this, ${remainingQty})"
                            >
                        </td>
                        <td>${item.uom_name}</td>
                    </tr>
                `);
            });
        });
    });

    // Form validation before submit
    $('#gatePassForm').on('submit', function(e) {
        const hasValidQuantity = $('.dn-quantity').toArray().some(input =>
            parseFloat(input.value) > 0
        );

        if (!hasValidQuantity) {
            e.preventDefault();
            alert('Please enter at least one DN quantity');
            return false;
        }
        return true;
    });
    @endif
});

function validateQuantity(input, max) {
    const value = parseFloat(input.value);
    if (value <= 0) {
        input.value = '';
    } else if (value > max) {
        input.value = max;
    }

    // Enable submit button if any quantity is entered
    const hasQuantity = $('.dn-quantity').toArray().some(input =>
        parseFloat(input.value) > 0
    );
    $('#submitBtn').prop('disabled', !hasQuantity);
}
</script>
@endpush
