@extends('layouts.admin-simple')

@section('title', 'Create Incoming Operation')

@section('content')
<div class="container-fluid">
    <!-- Header Section -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h1 class="h3 mb-0 text-gray-800">
                        <i class="material-icons align-middle mr-2">input</i>
                        Create Incoming Operation
                    </h1>
                    <p class="text-muted mb-0">
                        {{ ucfirst(str_replace('_', ' ', $operationType)) }} - Construction Materials Management
                    </p>
                </div>
                <div>
                    <a href="{{ route('warehouse.incoming-operations.index') }}" class="btn btn-outline-secondary">
                        <i class="material-icons mr-1">arrow_back</i>
                        Back to List
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Operation Type Info Card -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-primary">
                <div class="card-body py-3">
                    <div class="d-flex align-items-center">
                        <div class="mr-3">
                            @switch($operationType)
                                @case('supplier_delivery')
                                    <i class="material-icons text-primary" style="font-size: 32px;">local_shipping</i>
                                    @break
                                @case('site_return')
                                    <i class="material-icons text-warning" style="font-size: 32px;">assignment_return</i>
                                    @break
                                @case('emergency_procurement')
                                    <i class="material-icons text-danger" style="font-size: 32px;">warning</i>
                                    @break
                            @endswitch
                        </div>
                        <div class="flex-grow-1">
                            <h5 class="mb-1">{{ ucfirst(str_replace('_', ' ', $operationType)) }}</h5>
                            @if(in_array($operationType, ['supplier_delivery', 'site_return']))
                                <p class="mb-0 text-success">
                                    <i class="material-icons" style="font-size: 14px;">flash_on</i>
                                    <small><strong>Direct Processing:</strong> This operation will be automatically processed to inventory upon creation.</small>
                                </p>
                            @endif
                            <p class="text-muted mb-0">
                                @switch($operationType)
                                    @case('supplier_delivery')
                                        Record materials delivered from external suppliers with quality control
                                        @break
                                    @case('site_return')
                                        Process materials returned from construction sites
                                        @break
                                    @case('emergency_procurement')
                                        Fast-track urgent material procurement
                                        @break
                                @endswitch
                            </p>
                        </div>
                        <div>
                            <span class="badge badge-outline-primary">{{ strtoupper($operationType) }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Form -->
    <form method="POST" action="{{ route('warehouse.incoming-operations.store') }}" enctype="multipart/form-data" id="operationForm">
        @csrf
        <input type="hidden" name="operation_type" value="{{ $operationType }}">

        <!-- Full-Width Basic Information -->
        <div class="row">
            <div class="col-12">
                <div class="card mb-4">
                    <div class="card-header">
                        <h6 class="card-title mb-0">
                            <i class="material-icons mr-2">info</i>
                            Basic Information
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-3 mb-3">
                                <label for="operation_date" class="form-label">Operation Date <span class="text-danger">*</span></label>
                                <input type="date" class="form-control @error('operation_date') is-invalid @enderror"
                                       id="operation_date" name="operation_date" value="{{ old('operation_date', now()->format('Y-m-d')) }}" required>
                                @error('operation_date')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="col-md-3 mb-3">
                                <label for="division" class="form-label">Division <span class="text-danger">*</span></label>
                                <input type="text" class="form-control @error('division') is-invalid @enderror"
                                       id="division" name="division" value="{{ old('division') }}"
                                       placeholder="Enter division name" required>
                                @error('division')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            @if($operationType === 'supplier_delivery')
                                <div class="col-md-3 mb-3">
                                    @php
                                        $supplierOptions = [['value' => '', 'text' => 'Select Supplier']];
                                        foreach($suppliers as $supplier) {
                                            $supplierOptions[] = [
                                                'value' => $supplier->id,
                                                'text' => $supplier->name
                                            ];
                                        }
                                    @endphp
                                    <x-warehouse.select2-dropdown
                                        name="supplier_id"
                                        id="supplier_id"
                                        label="Supplier"
                                        placeholder="Select Supplier"
                                        :options="$supplierOptions"
                                        :selected="old('supplier_id')"
                                        required="true"
                                        errorField="supplier_id"
                                    />
                                </div>

                                <div class="col-md-3 mb-3">
                                    <x-warehouse.select2-dropdown
                                        name="received_by"
                                        id="received_by"
                                        label="Received By"
                                        placeholder="Select Staff Member"
                                        :options="[
                                            ['value' => '', 'text' => 'Select Staff Member'],
                                            ['value' => auth()->id(), 'text' => auth()->user()->name . ' (Me)']
                                        ]"
                                        :selected="auth()->id()"
                                        required="true"
                                        errorField="received_by"
                                    />
                                </div>

                                <!-- LPO Information -->
                                <div class="col-md-6 mb-3">
                                    <label for="lpo_number" class="form-label">LPO Number</label>
                                    <div class="input-group">
                                        <input type="text" class="form-control @error('lpo_number') is-invalid @enderror"
                                               id="lpo_number" name="lpo_number" value="{{ old('lpo_number') }}"
                                               placeholder="Enter or scan LPO number">
                                        <div class="input-group-append">
                                            <button type="button" class="btn btn-outline-secondary" onclick="loadLpoDetails()">
                                                <i class="material-icons">search</i>
                                            </button>
                                        </div>
                                    </div>
                                    @error('lpo_number')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="col-md-6 mb-3">
                                    <label for="delivery_note_number" class="form-label">Delivery Note Number</label>
                                    <input type="text" class="form-control @error('delivery_note_number') is-invalid @enderror"
                                           id="delivery_note_number" name="delivery_note_number" value="{{ old('delivery_note_number') }}"
                                           placeholder="Supplier's delivery note number">
                                    @error('delivery_note_number')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            @endif

                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Currency & Financial Information -->
        <div class="row">
            <div class="col-lg-6">
                <div class="card mb-4">
                    <div class="card-header">
                        <h6 class="card-title mb-0">
                            <i class="material-icons mr-2">account_balance</i>
                            Currency & Financial
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                @php
                                    $currencyOptions = [];
                                    foreach($exchangeRates as $code => $rate) {
                                        $displayText = $code;
                                        if($code !== 'AED') {
                                            $displayText .= ' (' . number_format($rate, 4) . ' د.إ)';
                                        }
                                        $currencyOptions[] = [
                                            'value' => $code,
                                            'text' => $displayText,
                                            'data' => ['rate' => $rate]
                                        ];
                                    }
                                @endphp
                                <x-warehouse.select2-dropdown
                                    name="currency"
                                    id="currency"
                                    label="Currency"
                                    placeholder="Select Currency"
                                    :options="$currencyOptions"
                                    :selected="old('currency', 'AED')"
                                    required="true"
                                    errorField="currency"
                                    :data="['onchange' => 'updateExchangeRate()']"
                                />
                            </div>

                            <div class="col-md-6 mb-3">
                                <label for="exchange_rate" class="form-label">Exchange Rate to د.إ</label>
                                <input type="number" step="0.0001" class="form-control @error('exchange_rate') is-invalid @enderror"
                                       id="exchange_rate" name="exchange_rate" value="{{ old('exchange_rate', '1.0000') }}"
                                       readonly>
                                @error('exchange_rate')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>

                        <div class="alert alert-info small">
                            <i class="material-icons mr-1" style="font-size: 16px;">info</i>
                            UAE VAT (5%) will be automatically calculated.
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-lg-6">
                <div class="card mb-4">
                    <div class="card-header">
                        <h6 class="card-title mb-0">
                            <i class="material-icons mr-2">note</i>
                            Additional Notes
                        </h6>
                    </div>
                    <div class="card-body">
                        <textarea class="form-control @error('notes') is-invalid @enderror"
                                  id="notes" name="notes" rows="6"
                                  placeholder="Any additional notes about this operation...">{{ old('notes') }}</textarea>
                        @error('notes')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
            </div>
        </div>
                <!-- Currency & Financial -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h6 class="card-title mb-0">
                            <i class="material-icons mr-2">account_balance</i>
                            Currency & Financial
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label for="currency" class="form-label">Currency <span class="text-danger">*</span></label>
                            <select class="form-control @error('currency') is-invalid @enderror"
                                    id="currency" name="currency" required onchange="updateExchangeRate()">
                                @foreach($exchangeRates as $code => $rate)
                                    <option value="{{ $code }}" {{ old('currency', 'AED') === $code ? 'selected' : '' }}
                                            data-rate="{{ $rate }}">
                                        {{ $code }} @if($code !== 'AED') ({{ number_format($rate, 4) }} د.إ) @endif
                                    </option>
                                @endforeach
                            </select>
                            @error('currency')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        <div class="mb-3">
                            <label for="exchange_rate" class="form-label">Exchange Rate to د.إ</label>
                            <input type="number" step="0.0001" class="form-control @error('exchange_rate') is-invalid @enderror"
                                   id="exchange_rate" name="exchange_rate" value="{{ old('exchange_rate', '1.0000') }}"
                                   readonly>
                            @error('exchange_rate')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        <div class="alert alert-info small">
                            <i class="material-icons mr-1" style="font-size: 16px;">info</i>
                            UAE VAT (5%) will be automatically calculated.
                        </div>
                    </div>
                </div>


                <!-- Received By -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h6 class="card-title mb-0">
                            <i class="material-icons mr-2">person</i>
                            Received By
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label for="received_by" class="form-label">Staff Member <span class="text-danger">*</span></label>
                            <select class="form-control @error('received_by') is-invalid @enderror"
                                    id="received_by" name="received_by" required>
                                <option value="">Select Staff Member</option>
                                <option value="{{ auth()->id() }}" selected>{{ auth()->user()->name }} (Me)</option>
                                <!-- Add other warehouse staff here -->
                            </select>
                            @error('received_by')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        <div class="mb-3">
                            <label for="received_by_name" class="form-label">Receiver Name</label>
                            <input type="text" class="form-control @error('received_by_name') is-invalid @enderror"
                                   id="received_by_name" name="received_by_name" value="{{ old('received_by_name', auth()->user()->name) }}"
                                   placeholder="Full name of receiver">
                            @error('received_by_name')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>


                <!-- Notes -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h6 class="card-title mb-0">
                            <i class="material-icons mr-2">note</i>
                            Additional Notes
                        </h6>
                    </div>
                    <div class="card-body">
                        <textarea class="form-control @error('notes') is-invalid @enderror"
                                  id="notes" name="notes" rows="4"
                                  placeholder="Any additional notes about this operation...">{{ old('notes') }}</textarea>
                        @error('notes')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
            </div>
        </div>

        <!-- Full-Width Materials & Items Section -->
        <div class="row">
            <div class="col-12">
                <div class="card mb-4">
                    <div class="card-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <h6 class="card-title mb-0">
                                <i class="material-icons mr-2">inventory_2</i>
                                Materials & Items
                            </h6>
                            <button type="button" class="btn btn-sm btn-primary" onclick="addItemRow()">
                                <i class="material-icons mr-1">add</i>
                                Add Item
                            </button>
                        </div>
                    </div>
                    <div class="card-body p-0" style="overflow: visible; position: relative; z-index: 1;">
                        <div class="table-responsive" style="overflow-x: auto; position: relative; z-index: 1;">
                            <table class="table table-bordered mb-0" id="itemsTable">
                                <thead class="thead-light">
                                    <tr>
                                        <th>Item</th>
                                        <th>Quantity</th>
                                        <th>Unit Price ({{ $exchangeRates ? array_key_first($exchangeRates) : 'د.إ' }})</th>
                                        <th>Total</th>
                                        <th>Batch/Serial</th>
                                        <th>Production Date</th>
                                        <th>Expiry Date</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody id="itemsTableBody">
                                    <!-- Items will be added dynamically -->
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <td colspan="3" class="text-right font-weight-bold">Total Amount:</td>
                                        <td class="font-weight-bold">
                                            <span id="totalAmount">0.00</span>
                                            <span id="totalCurrency">د.إ</span>
                                        </td>
                                        <td colspan="4"></td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Action Buttons -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <a href="{{ route('warehouse.incoming-operations.index') }}" class="btn btn-outline-secondary">
                                <i class="material-icons mr-1">cancel</i>
                                Cancel
                            </a>
                            <div>
                                <button type="submit" name="action" value="draft" class="btn btn-outline-primary mr-2">
                                    <i class="material-icons mr-1">save</i>
                                    Save as Draft
                                </button>
                                <button type="submit" name="action" value="create" class="btn btn-primary">
                                    <i class="material-icons mr-1">check</i>
                                    Create Operation
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

@endsection

@push('styles')
<style>
.badge-outline-primary {
    color: #007bff;
    border: 1px solid #007bff;
    background-color: transparent;
}

#itemsTable {
    margin-bottom: 0;
    border-collapse: separate;
    border-spacing: 0;
}

#itemsTable th {
    background-color: #f8f9fa;
    font-weight: 600;
    font-size: 0.875rem;
    white-space: nowrap;
    border: 1px solid #dee2e6;
    padding: 0.75rem 0.5rem;
}

#itemsTable td {
    vertical-align: middle;
    border: 1px solid #dee2e6;
    padding: 0.5rem;
}

.item-search-input {
    min-width: 300px;
    width: 100%;
}

.quantity-input, .price-input {
    width: 110px;
}

.batch-input {
    width: 150px;
}

.date-input {
    width: 160px;
}

/* Full-width table improvements */
#itemsTable th:nth-child(1) { width: 25%; } /* Item */
#itemsTable th:nth-child(2) { width: 10%; } /* Quantity */
#itemsTable th:nth-child(3) { width: 12%; } /* Unit Price */
#itemsTable th:nth-child(4) { width: 12%; } /* Total */
#itemsTable th:nth-child(5) { width: 15%; } /* Batch/Serial */
#itemsTable th:nth-child(6) { width: 13%; } /* Production Date */
#itemsTable th:nth-child(7) { width: 13%; } /* Expiry Date */
#itemsTable th:nth-child(8) { width: 8%; }  /* Actions */

.btn-remove-item {
    padding: 0.25rem 0.5rem;
    font-size: 0.75rem;
    white-space: nowrap;
}

/* Fix overlapping dropdown */
.item-dropdown {
    position: absolute !important;
    top: 100% !important;
    left: 0 !important;
    background: white;
    border: 1px solid #ccc;
    max-height: 200px;
    overflow-y: auto;
    box-shadow: 0 4px 20px rgba(0,0,0,0.15);
    border-radius: 4px;
    z-index: 9999 !important;
    width: 100%;
    min-width: 250px;
    margin-top: 2px;
}

.item-dropdown .dropdown-item {
    padding: 0.5rem 0.75rem;
    border-bottom: 1px solid #eee;
    cursor: pointer;
    transition: background-color 0.15s ease-in-out;
}

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

.item-dropdown .dropdown-item:last-child {
    border-bottom: none;
}

/* Fix table container positioning */
.table-responsive {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    position: relative;
    z-index: 1;
}

/* Prevent table from being covered */
#itemsTable {
    position: relative;
    z-index: 1;
    width: 100%;
    table-layout: auto;
}

/* Fix card positioning */
.card {
    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    margin-bottom: 1.5rem;
    position: relative;
    z-index: 1;
}

.card-header {
    background-color: #f8f9fa;
    border-bottom: 1px solid #dee2e6;
}

/* Fix any potential overlay issues */
.col-lg-8, .col-lg-4 {
    position: relative;
    z-index: 1;
}

/* Ensure proper item search positioning */
.item-search-input {
    position: relative;
    z-index: 2;
}

/* Fix any Bootstrap modal or overlay conflicts */
.modal-backdrop {
    z-index: 1040;
}

.modal {
    z-index: 1050;
}
</style>
@endpush

@push('scripts')
<script>
let itemRowIndex = 0;

// Exchange rates from server
const exchangeRates = @json($exchangeRates);

function updateExchangeRate() {
    const currencySelect = document.getElementById('currency');
    const exchangeRateInput = document.getElementById('exchange_rate');
    const selectedCurrency = currencySelect.value;
    const rate = exchangeRates[selectedCurrency] || 1.0000;

    exchangeRateInput.value = rate.toFixed(4);

    // Update total currency display
    document.getElementById('totalCurrency').textContent = selectedCurrency;

    // Recalculate totals
    calculateTotal();
}

function addItemRow() {
    const tbody = document.getElementById('itemsTableBody');
    const row = document.createElement('tr');
    row.innerHTML = `
        <td style="position: relative;">
            <input type="hidden" name="items[${itemRowIndex}][item_id]" class="item-id-input">
            <input type="text" class="form-control item-search-input" placeholder="Search items..."
                   onkeyup="searchItems(this)" autocomplete="off" style="position: relative; z-index: 2;">
            <div class="item-dropdown" style="display: none;"></div>
        </td>
        <td>
            <input type="number" step="0.01" min="0.01" class="form-control quantity-input"
                   name="items[${itemRowIndex}][quantity_delivered]" placeholder="0.00"
                   onchange="calculateRowTotal(this)" required>
        </td>
        <td>
            <input type="number" step="0.01" min="0" class="form-control price-input"
                   name="items[${itemRowIndex}][unit_price]" placeholder="0.00"
                   onchange="calculateRowTotal(this)" required>
        </td>
        <td>
            <span class="row-total font-weight-medium">0.00</span>
        </td>
        <td>
            <input type="text" class="form-control batch-input" name="items[${itemRowIndex}][batch_number]" placeholder="Optional">
        </td>
        <td>
            <input type="date" class="form-control date-input" name="items[${itemRowIndex}][production_date]">
        </td>
        <td>
            <input type="date" class="form-control date-input" name="items[${itemRowIndex}][expiry_date]">
        </td>
        <td>
            <button type="button" class="btn btn-outline-danger btn-sm btn-remove-item" onclick="removeItemRow(this)">
                <i class="material-icons" style="font-size: 16px;">delete</i>
            </button>
        </td>
    `;

    tbody.appendChild(row);
    itemRowIndex++;
}

function removeItemRow(button) {
    button.closest('tr').remove();
    calculateTotal();
}

function calculateRowTotal(input) {
    const row = input.closest('tr');
    const quantity = parseFloat(row.querySelector('.quantity-input').value) || 0;
    const price = parseFloat(row.querySelector('.price-input').value) || 0;
    const total = quantity * price;

    row.querySelector('.row-total').textContent = total.toFixed(2);
    calculateTotal();
}

function calculateTotal() {
    const rowTotals = document.querySelectorAll('.row-total');
    let total = 0;

    rowTotals.forEach(element => {
        total += parseFloat(element.textContent) || 0;
    });

    document.getElementById('totalAmount').textContent = total.toFixed(2);
}

function searchItems(input) {
    const searchTerm = input.value;
    if (searchTerm.length < 2) {
        hideItemDropdown(input);
        return;
    }

    // Make AJAX request to search items
    fetch(`{{ route('warehouse.incoming-operations.api.items') }}?search=${encodeURIComponent(searchTerm)}`)
        .then(response => response.json())
        .then(data => {
            showItemDropdown(input, data);
        })
        .catch(error => {
            console.error('Error searching items:', error);
        });
}

function showItemDropdown(input, items) {
    const dropdown = input.parentElement.querySelector('.item-dropdown');
    dropdown.innerHTML = '';

    if (items.length === 0) {
        dropdown.innerHTML = '<div class="dropdown-item-text text-muted p-3">No items found</div>';
    } else {
        items.forEach(item => {
            const dropdownItem = document.createElement('a');
            dropdownItem.className = 'dropdown-item';
            dropdownItem.href = '#';
            dropdownItem.innerHTML = `
                <div>
                    <strong>${item.item_code}</strong> - ${item.item_description}
                    <br><small class="text-muted">${item.category ? item.category.name : 'No category'}</small>
                </div>
            `;
            dropdownItem.onclick = (e) => {
                e.preventDefault();
                selectItem(input, item);
            };
            dropdown.appendChild(dropdownItem);
        });
    }

    // Ensure proper positioning and visibility
    dropdown.style.display = 'block';
    dropdown.style.position = 'absolute';
    dropdown.style.top = '100%';
    dropdown.style.left = '0';
    dropdown.style.right = '0';
    dropdown.style.zIndex = '9999';
}

function hideItemDropdown(input) {
    const dropdown = input.parentElement.querySelector('.item-dropdown');
    setTimeout(() => {
        dropdown.style.display = 'none';
    }, 200);
}

function selectItem(input, item) {
    const row = input.closest('tr');
    const itemIdInput = row.querySelector('.item-id-input');

    input.value = `${item.item_code} - ${item.item_description}`;
    itemIdInput.value = item.id;

    hideItemDropdown(input);
}

function loadLpoDetails() {
    const lpoNumber = document.getElementById('lpo_number').value;
    if (!lpoNumber) {
        alert('Please enter an LPO number first');
        return;
    }

    // Make AJAX request to get LPO details
    fetch(`{{ route('warehouse.incoming-operations.api.lpo-details') }}?lpo_number=${encodeURIComponent(lpoNumber)}`)
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                alert(data.error);
                return;
            }

            // Populate form with LPO data
            if (data.supplier_id) {
                document.getElementById('supplier_id').value = data.supplier_id;
            }
            if (data.project_id) {
                document.getElementById('project_id').value = data.project_id;
            }

            // Add LPO items to the table
            if (data.items && data.items.length > 0) {
                // Clear existing items
                document.getElementById('itemsTableBody').innerHTML = '';
                itemRowIndex = 0;

                data.items.forEach(lpoItem => {
                    addItemRow();
                    const lastRow = document.getElementById('itemsTableBody').lastElementChild;

                    // Populate item data
                    const itemIdInput = lastRow.querySelector('.item-id-input');
                    const itemSearchInput = lastRow.querySelector('.item-search-input');
                    const quantityInput = lastRow.querySelector('.quantity-input');
                    const priceInput = lastRow.querySelector('.price-input');

                    itemIdInput.value = lpoItem.item_id;
                    itemSearchInput.value = `${lpoItem.item.item_code} - ${lpoItem.item.item_description}`;
                    quantityInput.value = lpoItem.quantity_ordered;
                    priceInput.value = lpoItem.unit_price;

                    calculateRowTotal(quantityInput);
                });
            }
        })
        .catch(error => {
            console.error('Error loading LPO details:', error);
            alert('Failed to load LPO details');
        });
}

// Initialize form
document.addEventListener('DOMContentLoaded', function() {
    // Add initial item row
    addItemRow();

    // Update exchange rate on page load
    updateExchangeRate();


    // Hide item dropdowns when clicking outside
    document.addEventListener('click', function(e) {
        if (!e.target.closest('.item-dropdown') && !e.target.classList.contains('item-search-input')) {
            document.querySelectorAll('.item-dropdown').forEach(dropdown => {
                dropdown.style.display = 'none';
            });
        }
    });
});
</script>
@endpush