@extends('layouts.app')
@section('title', 'Create 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>
.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;
}
</style>
@endpush

@section('content')
<div class="card">
    <div class="card-body">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h6 class="card-title mb-0">Create Gate Pass</h6>
            <a href="{{ route('gatepasses.index') }}" class="btn btn-secondary">Back to List</a>
        </div>

        @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="gatePassForm" action="{{ route('gatepasses.store') }}" method="POST">
            @csrf
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label" for="gp_number">GP Number</label>
                    <input type="text" class="form-control" id="gp_number" name="gp_number" value="{{ $gpNumber }}" readonly>
                    <small class="form-text text-muted">
                        <i class="fas fa-magic"></i> Auto-generated GP number
                    </small>
                </div>
                <div class="col-md-6">
                    <label class="form-label" for="po_id">PO Number</label>
                    <select class="form-select" id="po_id" name="purchase_order_id" required>
                        <option value="">Select PO</option>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label" for="vehicle_no">Vehicle Number</label>
                    <input type="text" class="form-control" id="vehicle_no" name="vehicle_no" required>
                </div>
                <div class="col-md-6">
                    <label class="form-label" for="driver_name">Driver Name</label>
                    <input type="text" class="form-control" id="driver_name" name="driver_name" required>
                </div>
            </div>

            <div class="table-responsive mt-4">
                <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></tbody>
                </table>
            </div>

            <div class="mt-3">
                <button type="submit" class="btn btn-primary" id="submitBtn" disabled>Create Gate Pass</button>
            </div>
        </form>
    </div>
</div>
@endsection

@push('plugin-scripts')
<script src="{{ asset('theme/vendors/jquery/jquery.min.js') }}"></script>
<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: 'approved'
                };
            },
            processResults: function(data) {
                return {
                    results: data.map(po => ({
                        id: po.id,
                        text: po.po_number
                    }))
                };
            },
            cache: true
        }
    });

    poSelect.on('change', function() {
        const poId = $(this).val();
        if (!poId) {
            $('#itemsTable tbody').empty();
            $('#submitBtn').prop('disabled', true);
            return;
        }

        // Load PO items with remaining quantities
        $.get(`{{ url('purchase-orders') }}/${poId}/items`, function(data) {
            const tbody = $('#itemsTable tbody');
            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;
    });
});

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
