@extends('layouts.admin-simple')

@section('title', 'New Supplier Delivery')

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item"><a href="{{ route('warehouse.supplier-delivery.index') }}">Supplier Delivery</a></li>
    <li class="breadcrumb-item active">New Delivery</li>
@endsection

@section('page-title')
    <div class="d-flex justify-content-between align-items-center w-100">
        <div class="page-title-left">
            <h3 class="mb-1">New Supplier Delivery</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Create a new supplier delivery operation</p>
        </div>
        <div class="page-actions-right d-flex align-items-center">
            <a href="{{ route('warehouse.supplier-delivery.index') }}" class="btn btn-sm btn-outline-secondary">
                <i class="material-icons mr-1" style="font-size: 16px;">arrow_back</i>
                Back to List
            </a>
        </div>
    </div>
@endsection

@section('content')
    <form id="deliveryForm" action="{{ route('warehouse.incoming-operations.store') }}" method="POST" enctype="multipart/form-data">
        @csrf
        <input type="hidden" name="operation_type" value="supplier_delivery">
        <input type="hidden" name="currency" value="AED">
        <input type="hidden" name="exchange_rate" value="1.0000">
        <input type="hidden" name="vat_rate" value="5.00">
        <input type="hidden" name="delivery_type" id="delivery_type_hidden" value="warehouse">
        <input type="hidden" name="status" id="status" value="pending_delivery">

        <!-- Basic Information Card -->
        <div class="card mb-3">
            <div class="card-header">
                <h6 class="card-title mb-0 d-flex align-items-center">
                    <i class="material-icons mr-2">info</i>
                    Basic Information
                </h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="delivery_note_number">Delivery Note Number <span class="text-danger">*</span></label>
                            <input type="text" name="delivery_note_number" id="delivery_note_number"
                                   class="form-control @error('delivery_note_number') is-invalid @enderror"
                                   placeholder="Enter delivery note number" value="{{ old('delivery_note_number') }}" required>
                            @error('delivery_note_number')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="operation_date">Delivery Date <span class="text-danger">*</span></label>
                            <input type="date" name="operation_date" id="operation_date"
                                   class="form-control @error('operation_date') is-invalid @enderror"
                                   value="{{ old('operation_date', date('Y-m-d')) }}" required>
                            @error('operation_date')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="lpo_number">LPO Number</label>
                            <input type="text" name="lpo_number" id="lpo_number"
                                   class="form-control @error('lpo_number') is-invalid @enderror"
                                   placeholder="Enter LPO Number" value="{{ old('lpo_number') }}">
                            @error('lpo_number')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="supplier_id" class="form-label">Supplier Name <span class="text-danger">*</span></label>
                            <select name="supplier_id" id="supplier_id" class="form-control supplier-select2 @error('supplier_id') is-invalid @enderror" required>
                                <option value="">Select Supplier</option>
                                @foreach($suppliers ?? [] as $supplier)
                                    <option value="{{ $supplier->id }}" {{ old('supplier_id') == $supplier->id ? 'selected' : '' }}>
                                        {{ $supplier->name }} ({{ $supplier->supplier_code }})
                                    </option>
                                @endforeach
                            </select>
                            @error('supplier_id')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="division">Division <span class="text-danger">*</span></label>
                            <select name="division" id="division" class="form-control division-select2 @error('division') is-invalid @enderror" required>
                                <option value="">Select Division</option>
                                @foreach($divisions ?? [] as $division)
                                    <option value="{{ $division->id }}" {{ old('division') == $division->id ? 'selected' : '' }}>
                                        {{ $division->division_name }} ({{ $division->division_code }})
                                    </option>
                                @endforeach
                            </select>
                            @error('division')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label for="delivery_file">Delivery Document</label>
                            <input type="file"
                                   name="delivery_file"
                                   id="delivery_file"
                                   class="form-control @error('delivery_file') is-invalid @enderror"
                                   accept=".pdf,.doc,.docx,.jpg,.jpeg,.png">
                            <small class="form-text text-muted">Upload supporting document (PDF, DOC, DOCX, JPG, PNG - Max: 10MB)</small>
                            @error('delivery_file')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>

            </div>
        </div>

        <!-- Delivery Type & Destination Card -->
        <div class="card mb-3">
            <div class="card-header">
                <h6 class="card-title mb-0 d-flex align-items-center">
                    <i class="material-icons mr-2">place</i>
                    Delivery Destination
                </h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label class="form-label">Delivery Type <span class="text-danger">*</span></label>
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-check">
                                        <input type="radio" class="form-check-input" id="delivery_to_warehouse"
                                               name="delivery_type_radio" value="warehouse" checked onchange="toggleDeliveryType()">
                                        <label class="form-check-label" for="delivery_to_warehouse">
                                            <i class="material-icons align-middle mr-1">warehouse</i>
                                            Deliver to Warehouse
                                        </label>
                                        <small class="form-text text-muted d-block ml-4">Standard delivery to main warehouse inventory</small>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-check">
                                        <input type="radio" class="form-check-input" id="delivery_to_project"
                                               name="delivery_type_radio" value="project_site" onchange="toggleDeliveryType()">
                                        <label class="form-check-label" for="delivery_to_project">
                                            <i class="material-icons align-middle mr-1">construction</i>
                                            Deliver to Project Site
                                        </label>
                                        <small class="form-text text-muted d-block ml-4">Direct delivery to project location</small>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-check">
                                        <input type="radio" class="form-check-input" id="delivery_to_foc"
                                               name="delivery_type_radio" value="foc" onchange="toggleDeliveryType()">
                                        <label class="form-check-label" for="delivery_to_foc">
                                            <i class="material-icons align-middle mr-1">card_giftcard</i>
                                            Deliver to FOC
                                        </label>
                                        <small class="form-text text-muted d-block ml-4">Free of charge / sample items inventory</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Project Selection (Hidden by default) -->
                <div class="row" id="project_selection_section" style="display: none;">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="project_id" class="form-label">Select Project <span class="text-danger">*</span></label>
                            <select name="project_id" id="project_id" class="form-control project-select2 @error('project_id') is-invalid @enderror">
                                <option value="">Select Project</option>
                                @foreach($projects ?? [] as $project)
                                    <option value="{{ $project->id }}" {{ old('project_id') == $project->id ? 'selected' : '' }}>
                                        {{ $project->project_name }} ({{ $project->project_number }})
                                    </option>
                                @endforeach
                            </select>
                            @error('project_id')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Materials & Items Card -->
        <div class="card mb-3">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h6 class="card-title mb-0 d-flex align-items-center">
                    <i class="material-icons mr-2">inventory</i>
                    Materials & Items
                </h6>
                <button type="button" onclick="addItemRow()" class="btn btn-sm btn-primary">
                    <i class="material-icons mr-1" style="font-size: 14px;">add</i>
                    Add Item
                </button>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-sm mb-0" id="items-table">
                        <thead class="bg-light">
                            <tr>
                                <th style="width: 25%">Item</th>
                                <th style="width: 10%">Quantity</th>
                                <th style="width: 8%">Unit</th>
                                <th style="width: 12%" class="price-column">Unit Price</th>
                                <th style="width: 12%" class="price-column">Total Price</th>
                                <th style="width: 12%">Batch Number</th>
                                <th style="width: 10%">Production Date</th>
                                <th style="width: 10%">Expiry Date</th>
                                <th style="width: 8%">Actions</th>
                            </tr>
                        </thead>
                        <tbody id="items-tbody">
                            <!-- Item rows will be added here -->
                        </tbody>
                        <tfoot class="bg-light" id="total-amount-row">
                            <tr>
                                <td colspan="4" class="text-right font-weight-bold">Total Amount (AED):</td>
                                <td class="font-weight-bold text-success">
                                    <span id="total-amount">0.00</span>
                                    <input type="hidden" name="total_amount" id="total_amount_input" value="0">
                                </td>
                                <td colspan="4"></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>

        <!-- Received By & Additional Information Card -->
        <div class="card mb-3">
            <div class="card-header">
                <h6 class="card-title mb-0 d-flex align-items-center">
                    <i class="material-icons mr-2">person</i>
                    Received By & Additional Information
                </h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="received_by" class="form-label">Received By</label>
                            <select name="received_by" id="received_by" class="form-control user-select2 @error('received_by') is-invalid @enderror">
                                <option value="">Select User</option>
                                @foreach($users ?? [] as $user)
                                    <option value="{{ $user->id }}" {{ old('received_by') == $user->id ? 'selected' : '' }}>
                                        {{ $user->name }}
                                    </option>
                                @endforeach
                            </select>
                            @error('received_by')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="received_by_name">Received By Name</label>
                            <input type="text" name="received_by_name" id="received_by_name"
                                   class="form-control @error('received_by_name') is-invalid @enderror"
                                   placeholder="Enter full name" value="{{ old('received_by_name', auth()->user()->name ?? '') }}">
                            @error('received_by_name')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label for="notes">Notes</label>
                    <textarea name="notes" id="notes" class="form-control @error('notes') is-invalid @enderror"
                              rows="3" placeholder="Enter any additional notes or comments">{{ old('notes') }}</textarea>
                    @error('notes')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>

            </div>
        </div>

        <!-- Form Actions -->
        <div class="card">
            <div class="card-body text-center py-3">
                <button type="button" onclick="saveAndComplete()" class="btn btn-success mr-3">
                    <i class="material-icons mr-1" style="font-size: 16px;">check_circle</i>
                    Save & Mark as Delivered
                </button>
                <a href="{{ route('warehouse.supplier-delivery.index') }}" class="btn btn-outline-secondary">
                    <i class="material-icons mr-1" style="font-size: 16px;">cancel</i>
                    Cancel
                </a>
            </div>
        </div>
    </form>
@endsection

@push('styles')
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css">
    <style>
        .form-group label {
            font-weight: 600;
            color: #495057;
            font-size: 14px;
        }

        .card-title {
            font-size: 16px;
            font-weight: 600;
            color: #495057;
        }

        .table th {
            border-top: none;
            font-weight: 600;
            color: #495057;
            background-color: #f8f9fa;
            font-size: 13px;
        }

        .table td {
            vertical-align: middle;
            font-size: 13px;
        }

        .btn-sm {
            padding: 6px 12px;
            font-size: 12px;
            line-height: 1.5;
        }

        .btn-sm .material-icons {
            font-size: 16px !important;
        }

        .form-control-sm {
            height: calc(1.5em + 0.5rem + 2px);
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
        }

        .item-row {
            border-bottom: 1px solid #dee2e6;
        }

        .item-row:hover {
            background-color: #f8f9fa;
        }

        .form-control {
            height: 38px;
            border: 1px solid #ced4da;
            border-radius: 0.375rem;
        }

        .form-control:focus {
            border-color: #80bdff;
            outline: 0;
            box-shadow: 0 0 0 0.2rem rgba(0,123,255,0.25);
        }

        .text-danger {
            color: #dc3545 !important;
        }

        .text-success {
            color: #28a745 !important;
        }

        .invalid-feedback {
            display: block;
        }

        /* Form styling improvements */
        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-label {
            font-weight: 600;
            margin-bottom: 0.5rem;
        }

        /* Select2 styling for form dropdowns */
        .select2-container--default .select2-selection--single {
            height: 38px;
            border: 1px solid #ced4da;
            border-radius: 0.375rem;
            line-height: 36px;
        }

        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 36px;
            padding-left: 12px;
            color: #495057;
        }

        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 36px;
            right: 10px;
        }

        .select2-container {
            width: 100% !important;
        }

        .select2-container--default .select2-selection--single:focus {
            border-color: #80bdff;
            outline: 0;
            box-shadow: 0 0 0 0.2rem rgba(0,123,255,0.25);
        }

        .select2-dropdown {
            border: 1px solid #ced4da;
            border-radius: 0.375rem;
        }

        .select2-container--default .select2-search--dropdown .select2-search__field {
            border: 1px solid #ced4da;
            border-radius: 0.375rem;
            padding: 8px 12px;
        }

        /* Table Select2 styling for items table only */
        #items-table .select2-container {
            width: 90% !important;
            max-width: 300px !important;
            min-width: 200px !important;
        }

        /* Force Select2 dropdown to appear below for table items */
        #items-table .select2-container--open .select2-dropdown {
            top: 100% !important;
            bottom: auto !important;
            margin-top: 1px !important;
        }

        #items-table .select2-container--open .select2-dropdown--below {
            top: 100% !important;
            border-top: none !important;
            border-top-left-radius: 0 !important;
            border-top-right-radius: 0 !important;
        }

        #items-table .select2-container--open .select2-dropdown--above {
            display: none !important;
        }

        /* Ensure table dropdown doesn't get cut off */
        .table-responsive {
            overflow: visible !important;
        }

        #items-table {
            overflow: visible !important;
        }

        /* Specific positioning for item dropdowns in table */
        #items-tbody .select2-container {
            position: relative !important;
        }

        #items-tbody .select2-dropdown {
            position: absolute !important;
            top: 100% !important;
            z-index: 9999 !important;
            width: 100% !important;
        }
    </style>
@endpush

@push('scripts')
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

    <script>
        let itemRowCounter = 0;
        let availableItems = @json($items ?? []);
        let availableIndirectGoods = @json($indirectGoods ?? []);
        let availableMixedItems = [
            ...availableItems.map(item => ({
                key: `direct:${item.id}`,
                label: `${item.item_description} (${item.item_code}) - Direct`,
                unit: item.unit_of_measure,
                searchText: `${item.item_description || ''} ${item.item_code || ''} ${item.notes || ''}`
            })),
            ...availableIndirectGoods.map(item => ({
                key: `indirect:${item.id}`,
                label: `${item.ig_description} (${item.ig_code}) - Indirect`,
                unit: item.unit_of_measure,
                searchText: `${item.ig_description || ''} ${item.ig_code || ''} ${item.notes || ''}`
            }))
        ];

        function escapeHtml(value) {
            return String(value || '').replace(/[&<>"']/g, function(match) {
                return {
                    '&': '&amp;',
                    '<': '&lt;',
                    '>': '&gt;',
                    '"': '&quot;',
                    "'": '&#039;'
                }[match];
            });
        }

        function itemSearchMatcher(params, data) {
            if ($.trim(params.term) === '') {
                return data;
            }

            if (!data.element) {
                return null;
            }

            const term = params.term.toLowerCase();
            const visibleText = (data.text || '').toLowerCase();
            const hiddenSearchText = ($(data.element).data('search') || '').toString().toLowerCase();

            return visibleText.indexOf(term) > -1 || hiddenSearchText.indexOf(term) > -1 ? data : null;
        }

        $(document).ready(function() {
            // Initialize Select2 for supplier dropdown
            $('#supplier_id').select2({
                placeholder: 'Select Supplier',
                allowClear: true,
                width: '100%',
                language: {
                    noResults: function() {
                        return 'No suppliers found';
                    },
                    searching: function() {
                        return 'Searching suppliers...';
                    }
                }
            });

            // Initialize Select2 for user dropdown
            $('#received_by').select2({
                placeholder: 'Select User',
                allowClear: true,
                width: '100%',
                language: {
                    noResults: function() {
                        return 'No users found';
                    },
                    searching: function() {
                        return 'Searching users...';
                    }
                }
            });

            // Initialize Select2 for project dropdown
            $('#project_id').select2({
                placeholder: 'Select Project',
                allowClear: true,
                width: '100%',
                language: {
                    noResults: function() {
                        return 'No projects found';
                    },
                    searching: function() {
                        return 'Searching projects...';
                    }
                }
            });

            // Initialize Select2 for division dropdown
            $('#division').select2({
                placeholder: 'Select Division',
                allowClear: true,
                width: '100%',
                language: {
                    noResults: function() {
                        return 'No divisions found';
                    },
                    searching: function() {
                        return 'Searching divisions...';
                    }
                }
            });

            // Auto-fill received by name when user is selected
            $('#received_by').change(function() {
                const selectedOption = $(this).find('option:selected');
                if (selectedOption.val()) {
                    $('#received_by_name').val(selectedOption.text());
                }
            });

            // Users can add direct and indirect goods as needed.
        });



        function addItemRow() {
            itemRowCounter++;
            const isFocDelivery = $('#delivery_type_hidden').val() === 'foc';
            const priceColumnStyle = isFocDelivery ? 'display: none;' : '';
            const priceRequired = isFocDelivery ? '' : 'required';

            const rowHtml = `
                <tr class="item-row" data-row="${itemRowCounter}">
                    <td>
                        <select name="mixed_items[${itemRowCounter}][item_key]" id="item_select_${itemRowCounter}" class="form-control form-control-sm item-select select2-dropdown" required>
                            <option value="">Select Item</option>
                            ${availableMixedItems.map(item => `<option value="${escapeHtml(item.key)}" data-unit="${escapeHtml(item.unit)}" data-search="${escapeHtml(item.searchText)}">${escapeHtml(item.label)}</option>`).join('')}
                        </select>
                    </td>
                    <td>
                        <input type="number" name="mixed_items[${itemRowCounter}][quantity_delivered]" class="form-control form-control-sm quantity"
                               placeholder="0" step="0.01" min="0" required>
                    </td>
                    <td>
                        <input type="text" name="mixed_items[${itemRowCounter}][unit]" class="form-control form-control-sm unit-field"
                               placeholder="Unit" readonly>
                    </td>
                    <td class="price-column" style="${priceColumnStyle}">
                        <input type="number" name="mixed_items[${itemRowCounter}][unit_price]" class="form-control form-control-sm unit-price"
                               placeholder="0.00" step="0.01" min="0" ${priceRequired} value="${isFocDelivery ? '0' : ''}">
                    </td>
                    <td class="price-column" style="${priceColumnStyle}">
                        <input type="number" name="mixed_items[${itemRowCounter}][total_price]" class="form-control form-control-sm total-price"
                               placeholder="0.00" step="0.01" min="0" readonly value="${isFocDelivery ? '0' : ''}">
                    </td>
                    <td>
                        <input type="text" name="mixed_items[${itemRowCounter}][batch_number]" class="form-control form-control-sm"
                               placeholder="Batch">
                    </td>
                    <td>
                        <input type="date" name="mixed_items[${itemRowCounter}][production_date]" class="form-control form-control-sm">
                    </td>
                    <td>
                        <input type="date" name="mixed_items[${itemRowCounter}][expiry_date]" class="form-control form-control-sm">
                    </td>
                    <td>
                        <button type="button" onclick="removeItemRow(${itemRowCounter})" class="btn btn-sm btn-outline-danger">
                            <i class="material-icons" style="font-size: 14px;">delete</i>
                        </button>
                    </td>
                </tr>
            `;

            $('#items-tbody').append(rowHtml);

            // Bind events to new row
            bindRowEvents(itemRowCounter);

            // Initialize Select2 for the new item dropdown
            initializeSelect2ForRow(itemRowCounter);
        }

        // Initialize Select2 for a specific row
        function initializeSelect2ForRow(rowIndex) {
            const selectId = `#item_select_${rowIndex}`;

            // Initialize Select2
            $(selectId).select2({
                placeholder: 'Select Item',
                allowClear: true,
                theme: 'default',
                width: '90%',
                dropdownAutoWidth: false,
                matcher: itemSearchMatcher,
                language: {
                    noResults: function() {
                        return 'No results found';
                    },
                    searching: function() {
                        return 'Searching...';
                    }
                },
                dropdownCssClass: 'select2-dropdown-below',
                adaptDropdownCssClass: function(cssClass) {
                    return 'select2-dropdown-below';
                }
            });

            // Force dropdown to open below
            $(selectId).on('select2:open', function() {
                const dropdown = $('.select2-dropdown');
                dropdown.removeClass('select2-dropdown--above').addClass('select2-dropdown--below');
                dropdown.css({
                    'top': '100%',
                    'bottom': 'auto'
                });
            });

            // Prevent Select2 events from interfering with Bootstrap dropdowns
            $(selectId).on('select2:open select2:close', function(e) {
                e.stopPropagation();
            });

            // Handle dropdown clicks to prevent Bootstrap dropdown interference
            $(selectId).next('.select2-container').on('click', function(e) {
                e.stopPropagation();
            });
        }

        function bindRowEvents(rowCounter) {
            const row = $(`.item-row[data-row="${rowCounter}"]`);

            // Store the previously selected item for reselection warning
            let previousItemId = row.find('.item-select').val();

            // Update unit when item is selected
            row.find('.item-select').change(function() {
                const selectedItemId = $(this).val();
                const currentRow = $(this).closest('.item-row');
                const currentRowId = currentRow.data('row');
                const $selectElement = $(this);

                // Check if user is selecting the same item again (reselection of same item)
                if (previousItemId && previousItemId === selectedItemId) {
                    const itemText = row.find('.item-select option:selected').text();

                    Swal.fire({
                        icon: 'info',
                        title: 'Item Already Selected',
                        html: `<p>The item <strong>"${itemText}"</strong> is already selected in this row.</p>`,
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#3085d6'
                    });
                    return; // Do nothing, item is already selected
                }

                // Check for duplicate items in other rows and update unit
                if (selectedItemId) {
                    checkDuplicatesAndUpdateUnit(selectedItemId, currentRowId, $selectElement, row);
                    previousItemId = selectedItemId;
                }
            });

            // Helper function to check duplicates and update unit
            function checkDuplicatesAndUpdateUnit(selectedItemId, currentRowId, $selectElement, row) {
                let isDuplicate = false;
                $('.item-row').each(function() {
                    const rowId = $(this).data('row');
                    if (rowId !== currentRowId) {
                        const existingItemId = $(this).find('.item-select').val();
                        if (existingItemId === selectedItemId) {
                            isDuplicate = true;
                            return false; // Break the loop
                        }
                    }
                });

                if (isDuplicate) {
                    // Show error message
                    Swal.fire({
                        icon: 'warning',
                        title: 'Duplicate Item',
                        html: '<p>This item has already been added to the delivery.</p><p class="mb-0 text-muted small">Each item can only be added once. Please update the quantity on the existing row if needed.</p>',
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#3085d6'
                    });

                    // Reset the select2 dropdown to empty
                    $selectElement.val('').trigger('change');
                    row.find('.unit-field').val('');
                    previousItemId = null;
                    return;
                }

                // If not duplicate, update the unit field
                const selectedOption = $selectElement.find('option:selected');
                const unit = selectedOption.data('unit');
                row.find('.unit-field').val(unit || '');
            }

            // Calculate line total when quantity or price changes
            row.find('.quantity, .unit-price').on('input', function() {
                const quantity = parseFloat(row.find('.quantity').val()) || 0;
                let unitPrice = parseFloat(row.find('.unit-price').val()) || 0;

                // Allow unit price to be 0 or greater
                if ($(this).hasClass('unit-price') && unitPrice < 0) {
                    $(this).val('0.00');
                    unitPrice = 0;
                }

                const total = quantity * unitPrice;

                row.find('.total-price').val(total.toFixed(2));
                calculateTotals();
            });

            // Additional validation on blur for unit price
            row.find('.unit-price').on('blur', function() {
                const unitPrice = parseFloat($(this).val()) || 0;
                const isFocDelivery = $('#delivery_type_hidden').val() === 'foc';

                // For FOC delivery, any price >= 0 is valid
                // For warehouse/project site delivery, price must be > 0
                if (!isFocDelivery && unitPrice <= 0) {
                    $(this).addClass('is-invalid');
                    if ($(this).next('.invalid-feedback').length === 0) {
                        $(this).after('<div class="invalid-feedback">Unit price must be greater than 0</div>');
                    }
                } else if (unitPrice < 0) {
                    $(this).addClass('is-invalid');
                    if ($(this).next('.invalid-feedback').length === 0) {
                        $(this).after('<div class="invalid-feedback">Unit price cannot be negative</div>');
                    }
                } else {
                    $(this).removeClass('is-invalid');
                    $(this).next('.invalid-feedback').remove();
                }
            });
        }

        function removeItemRow(rowCounter) {
            // Destroy Select2 instance before removing the row
            const selectElement = $(`#item_select_${rowCounter}`);
            if (selectElement.length && selectElement.hasClass('select2-hidden-accessible')) {
                selectElement.select2('destroy');
            }

            $(`.item-row[data-row="${rowCounter}"]`).remove();
            calculateTotals();
        }

        function calculateTotals() {
            let total = 0;

            $('.total-price').each(function() {
                const value = parseFloat($(this).val()) || 0;
                total += value;
            });

            $('#total-amount').text(total.toFixed(2));
            $('#total_amount_input').val(total);
        }

        function saveAndComplete() {
            $('#status').val('delivered');
            $('#deliveryForm').submit();
        }

        // Toggle delivery type sections
        function toggleDeliveryType() {
            const deliveryTypeRadio = $('input[name="delivery_type_radio"]:checked').val();

            // Update the hidden delivery_type field
            $('#delivery_type_hidden').val(deliveryTypeRadio);

            if (deliveryTypeRadio === 'project_site') {
                $('#project_selection_section').slideDown(300);

                // Make project selection required
                $('#project_id').prop('required', true);

                // Division is still required for project delivery
                $('#division').prop('required', true);

                // Show price columns for project site delivery
                togglePriceColumns(true);
            } else if (deliveryTypeRadio === 'foc') {
                // FOC delivery - no project selection needed
                $('#project_selection_section').slideUp(300);

                // Remove project requirements
                $('#project_id').prop('required', false);
                $('#project_id').val('').trigger('change');

                // Division is still required for FOC delivery
                $('#division').prop('required', true);

                // Hide price columns for FOC delivery
                togglePriceColumns(false);
            } else {
                // Warehouse delivery
                $('#project_selection_section').slideUp(300);

                // Remove project requirements
                $('#project_id').prop('required', false);
                $('#project_id').val('').trigger('change');

                // Make division required for warehouse delivery
                $('#division').prop('required', true);

                // Show price columns for warehouse delivery
                togglePriceColumns(true);
            }
        }

        // Toggle price columns visibility
        function togglePriceColumns(show) {
            if (show) {
                // Show price columns
                $('.price-column').show();
                $('#total-amount-row').show();

                // Make price fields required and clear FOC values
                $('.unit-price').prop('required', true);
            } else {
                // Hide price columns
                $('.price-column').hide();
                $('#total-amount-row').hide();

                // Remove required from price fields and set to 0 for FOC
                $('.unit-price').prop('required', false).val(0);
                $('.total-price').val(0);
                $('#total-amount').text('0.00');
                $('#total_amount_input').val(0);
            }
        }



        // Form validation
        $('#deliveryForm').on('submit', function(e) {
            // Debug: Log form data
            console.log('Form submission - Delivery Type:', $('#delivery_type_hidden').val());
            console.log('Division value:', $('#division').val());
            console.log('Project ID:', $('#project_id').val());

            // Check delivery type validation
            const deliveryType = $('#delivery_type_hidden').val();
            if (deliveryType === 'project_site') {
                const projectSelected = $('#project_id').val();
                if (!projectSelected) {
                    e.preventDefault();
                    alert('Please select a project for project site delivery.');
                    return false;
                }
            }

            const directRows = $('#items-tbody tr');
            let hasDirectItem = false;

            directRows.each(function() {
                const itemId = $(this).find('.item-select').val();
                const quantity = parseFloat($(this).find('.quantity').val()) || 0;
                if (itemId && quantity > 0) {
                    hasDirectItem = true;
                    return false;
                }
            });

            if (!hasDirectItem) {
                e.preventDefault();
                alert('Please add at least one item to the delivery.');
                return false;
            }

            // Validate that all items have required data
            let hasErrors = false;
            const isFocDelivery = deliveryType === 'foc';

            // Check for duplicate items before validating other fields
            const selectedItems = [];
            let hasDuplicates = false;
            let duplicateItemName = '';

            $('#items-tbody tr').each(function() {
                const itemId = $(this).find('.item-select').val();
                if (itemId) {
                    if (selectedItems.includes(itemId)) {
                        hasDuplicates = true;
                        const itemText = $(this).find('.item-select option:selected').text();
                        duplicateItemName = itemText;
                        return false; // Break the loop
                    }
                    selectedItems.push(itemId);
                }
            });

            if (hasDuplicates) {
                e.preventDefault();
                Swal.fire({
                    icon: 'error',
                    title: 'Duplicate Items Found',
                    html: `<p>The item "${duplicateItemName}" appears multiple times in the delivery.</p><p class="mb-0 text-muted small">Please remove duplicate entries. Each item can only be added once per delivery.</p>`,
                    confirmButtonText: 'OK',
                    confirmButtonColor: '#d33'
                });
                return false;
            }

            $('#items-tbody tr').each(function() {
                const row = $(this);
                const itemSelected = row.find('.item-select').val();
                const quantity = parseFloat(row.find('.quantity').val()) || 0;
                const unitPrice = parseFloat(row.find('.unit-price').val()) || 0;

                if (!itemSelected && quantity <= 0) {
                    return true;
                }

                if (!itemSelected) {
                    hasErrors = true;
                    alert('Please select an item for all rows.');
                    return false;
                }

                if (quantity <= 0) {
                    hasErrors = true;
                    alert('Please enter a valid quantity for all items.');
                    return false;
                }

                // For warehouse and project site delivery, unit price must be greater than 0
                if (!isFocDelivery && unitPrice <= 0) {
                    hasErrors = true;
                    const itemName = row.find('.item-select option:selected').text() || 'Item';
                    alert('Unit price must be greater than 0 for warehouse and project site deliveries.\n\nPlease enter a valid unit price for: ' + itemName);
                    row.find('.unit-price').addClass('is-invalid').focus();
                    return false;
                }
            });

            if (hasErrors) {
                e.preventDefault();
                return false;
            }

            // Skip total amount validation for FOC delivery
            if (!isFocDelivery) {
                // Calculate and show final total
                calculateTotals();
                const finalTotal = parseFloat($('#total_amount_input').val()) || 0;
                if (finalTotal < 0) {
                    e.preventDefault();
                    alert('Total amount cannot be negative. Please check item quantities and prices.');
                    return false;
                }
            }
        });
    </script>
@endpush
