<x-app-layout>
    <div class="app-main flex-column flex-row-fluid">
        <div class="d-flex flex-column flex-column-fluid">
            <!-- Breadcrumb -->
            <div class="app-toolbar py-3 py-lg-6">
                <div class="app-container container-xxl d-flex flex-stack">
                    <div class="page-title d-flex flex-column justify-content-center flex-wrap me-3">
                        <h1 class="page-heading d-flex text-dark fw-bold fs-3 flex-column justify-content-center my-0">
                            Create Gerai Invoice</h1>
                        {{ Breadcrumbs::render('gerai.create') }}
                    </div>
                    <div class="d-flex align-items-center ml-auto gap-2 gap-lg-3">
                        @if ($url = Session::get('backUrl'))
                            <x-add-back-button onclick="window.location='{{ $url }}'">
                                <i class="ki-duotone ki-left fs-3"></i>
                                {{ __('Back') }}
                            </x-add-back-button>
                        @else
                            <x-add-back-button onclick="window.location='{{ url()->previous() }}'">
                                <i class="ki-duotone ki-left fs-3"></i>
                                {{ __('Back') }}
                            </x-add-back-button>
                        @endif
                    </div>
                </div>
            </div>

            <!-- Content -->
            <div class="app-content flex-column-fluid">
                <div class="app-container container-xxl">
                    <div class="app-content flex-column-fluid p-12 sm:p-8 bg-white shadow sm:rounded-lg">
                        <div class="max-w-8xl">
                            <form action="{{ route('admin.gerai.store') }}" method="POST" id="geraiForm">
                                @csrf
                                <!-- Prevent implicit submission -->
                                <button type="submit" disabled style="display: none" aria-hidden="true"></button>

                                <!-- Invoice Header -->
                                <div class="d-flex flex-column align-items-start flex-xxl-row mb-5">
                                    <!-- Invoice Number -->
                                    <div class="d-flex align-items-start fw-row text-nowrap order-1 order-xxl-2 me-4 mb-3">
                                        {{-- Label (left) --}}
                                        <span class="fs-2x fw-bold text-gray-800 required form-label me-5">
                                            Gerai Invoice
                                        </span>

                                        {{-- Right side: input + error stacked --}}
                                        <div class="d-flex flex-column">
                                            <div class="d-flex align-items-center">
                                                <span class="input-group-text fs-3">#KPBIV-</span>

                                                <input
                                                    type="text"
                                                    class="form-control fs-3 @error('parentInvoiceNo') is-invalid @enderror"
                                                    name="parentInvoiceNo"
                                                    id="parentInvoiceNo"
                                                    value="{{ old('parentInvoiceNo') }}"
                                                    minlength="6"
                                                    required
                                                />
                                            </div>

                                            {{-- Error under the input group --}}
                                            <x-input-error :messages="$errors->get('parentInvoiceNo')" class="mt-2 d-block" />
                                        </div>
                                    </div>

                                    <!-- Date -->
                                    <div class="d-flex align-items-center justify-content-end flex-equal order-3 fw-row mb-3">
                                        <div class="fs-6 fw-bold text-gray-700 text-nowrap required form-label me-3">Date:</div>
                                        <div class="position-relative align-items-center w-250px">
                                            <input class="form-control @error('date') is-invalid @enderror"
                                                placeholder="Pick a date" id="kt_datepicker_2" name="date"
                                                value="{{ old('date', date('d/m/Y')) }}" required />
                                        </div>
                                        <x-input-error :messages="$errors->get('date')" class="mt-3" />
                                    </div>
                                </div>

                                <!-- Payment Method -->
                                <div class="d-flex flex-column align-items-start flex-xxl-row mb-5">
                                    <div class="d-flex align-items-center justify-content-end flex-equal order-3 fw-row mb-3">
                                        <div class="fs-6 fw-bold text-gray-700 text-nowrap required form-label me-3">Payment Method:</div>
                                        <div class="position-relative align-items-center w-250px">
                                            <select class="form-select @error('paymentMethod') is-invalid @enderror"
                                                data-control="select2" data-placeholder="Select Payment Method"
                                                name="paymentMethod" id="paymentMethod" data-hide-search="true" required>
                                                <option></option>
                                                @foreach ($paymentMethod['result'] as $method)
                                                    <option value="{{ $method }}"
                                                        @if (old('paymentMethod') == $method) selected @endif>
                                                        {{ $method }}
                                                    </option>
                                                @endforeach
                                            </select>
                                            <x-input-error :messages="$errors->get('paymentMethod')" class="mt-3" />
                                        </div>
                                    </div>
                                </div>

                                <div class="separator separator-dashed my-10"></div>

                                <!-- Transporter Details -->
                                <div class="mb-5">
                                    <div class="fs-5 fw-bold text-dark mb-5">Transporter Details</div>
                                    <div class="row gx-10 mb-5">
                                        <!-- Transporter Code -->
                                        <div class="col-md-6">
                                            <div class="mb-5">
                                                <x-input-label class="required" for="transporterCode" :value="__('Transporter Code')" />
                                                <select class="form-select @error('transporterCode') is-invalid @enderror"
                                                    name="transporterCode" data-control="select2"
                                                    data-placeholder="Select Transporter Code" id="codeSelect"
                                                    data-allow-clear="true" required>
                                                    <option></option>
                                                    @foreach ($transporterMethod['transporters'] as $transporter)
                                                        <option value="{{ $transporter['transporterCode'] }}"
                                                            data-transporter-name="{{ $transporter['transporterName'] }}"
                                                            @if (old('transporterCode') == $transporter['transporterCode']) selected @endif>
                                                            {{ $transporter['transporterCode'] }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                                <x-input-error :messages="$errors->get('transporterCode')" class="mt-3" />
                                            </div>
                                        </div>

                                        <!-- Transporter Name -->
                                        <div class="col-md-6">
                                            <div class="mb-5">
                                                <x-input-label class="required" for="transporterName" :value="__('Transporter Name')" />
                                                <select class="form-select @error('transporterName') is-invalid @enderror"
                                                    name="transporterName" data-control="select2"
                                                    data-placeholder="Select Transporter Name" id="nameSelect"
                                                    data-allow-clear="true" required>
                                                    <option></option>
                                                    @foreach ($transporterMethod['transporters'] as $transporter)
                                                        <option value="{{ $transporter['transporterName'] }}"
                                                            data-transporter-code="{{ $transporter['transporterCode'] }}"
                                                            @if (old('transporterName') == $transporter['transporterName']) selected @endif>
                                                            {{ $transporter['transporterName'] }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                                <x-input-error :messages="$errors->get('transporterName')" class="mt-3" />
                                            </div>
                                        </div>

                                        <!-- Vehicle Number -->
                                        <div class="col-md-6">
                                            <div class="mb-5">
                                                <x-input-label class="required" for="vehicleNo" :value="__('Vehicle No')" />
                                                <input type="text" class="form-control @error('vehicleNo') is-invalid @enderror"
                                                    name="vehicleNo" id="vehicleNo" value="{{ old('vehicleNo') }}"
                                                    placeholder="Vehicle No" autocomplete="on" required>
                                                <x-input-error :messages="$errors->get('vehicleNo')" class="mt-3" />
                                            </div>
                                        </div>

                                        <!-- Phone Number -->
                                        <div class="col-md-6">
                                            <div class="mb-5">
                                                <x-input-label class="required" for="phoneNo" :value="__('Phone No')" />
                                                <input type="text" class="form-control @error('phoneNo') is-invalid @enderror"
                                                    name="phoneNo" id="phoneNo" value="{{ old('phoneNo') }}"
                                                    placeholder="Phone No" required>
                                                <x-input-error :messages="$errors->get('phoneNo')" class="mt-3" />
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="separator separator-dashed my-10"></div>

                                <div class="mb-5">
                                    <div class="fs-5 fw-bold text-dark mb-5">Gerai Details</div>

                                    <!-- Header Row -->
                                    <div class="grid gap-6 px-3 mb-3 md:grid-cols-8 labelStall">
                                        <div class="fv-row form-control col-span-1">
                                            <x-input-label for="name" :value="__('No')" />
                                        </div>
                                        <div class="fv-row form-control col-span-2">
                                            <x-input-label class="required" for="name" :value="__('Gerai / Stall')" />
                                        </div>
                                        <div class="fv-row form-control col-span-2">
                                            <x-input-label for="name" :value="__('Tong')" />
                                        </div>
                                        <div class="fv-row form-control col-span-2">
                                            <x-input-label for="name" :value="__('Total (RM)')" />
                                        </div>
                                        <div class="fv-row form-control col-span-1">
                                            <span class="flex justify-end">
                                                <x-input-label for="name" :value="__('Action')" />
                                            </span>
                                        </div>
                                    </div>

                                    <!-- Stall Details Section -->
                                    <div id="stallContainer">

                                        <!-- Stall Rows with Deposit Details -->
                                        @php
                                            $iterationCount = 0;
                                        @endphp
                                        @foreach (old('stall', [[]]) as $index => $stallData)
                                            <!-- Stall Group Container -->
                                            {{-- <div class="border border-gray-300 p-5"> --}}
                                            <div class="border border-gray-300 p-3 stall-group" data-stall-index="{{ $index }}">
                                                <!-- First Row: Stall Details -->
                                                <div class="grid gap-6 mb-2 md:grid-cols-8 py-3 stallRow">
                                                    <!-- Row Number -->
                                                    <div class="fv-row col-span-1">
                                                        <x-input-label class="labelStallSmol d-md-none" for="name" :value="__('No')" />
                                                        <input type="text" class="form-control form-control-solid row-number"
                                                            value="{{ $index + 1 }}" readonly tabindex="-1">
                                                    </div>

                                                    <!-- Stall Select -->
                                                    <div class="fv-row col-span-2">
                                                        <x-input-label class="labelStallSmol d-md-none" for="name" :value="__('Stall')" />
                                                        <select class="form-select @error('stall.' . $index . '.stallId') is-invalid @enderror"
                                                            data-placeholder="Select Stall" name="stall[{{ $index }}][stallId]"
                                                            id="stallSelect_{{ $index }}" data-allow-clear="true"
                                                            data-control="select2" required>
                                                            <option></option>
                                                            @foreach ($stallMethod['stalls'] as $stall)
                                                                <option value="{{ $stall['stallCode'] }}"
                                                                    data-stall-code="{{ $stall['stallCode'] }}"
                                                                    @if (isset($stallData['stallId']) && $stallData['stallId'] == $stall['stallCode']) selected @endif>
                                                                    {{ $stall['stallCode'] }}
                                                                </option>
                                                            @endforeach
                                                        </select>
                                                        @error('stall.' . $index . '.stallId')
                                                            <div class="invalid-feedback">{{ $message }}</div>
                                                        @enderror
                                                    </div>

                                                    <!-- Tong Quantity -->
                                                    <div class="fv-row col-span-2">
                                                        <x-input-label class="labelStallSmol d-md-none" for="name" :value="__('Tong')" />
                                                        <input type="number"
                                                            class="form-control tank-quantity-input w-100"
                                                            name="stall[{{ $index }}][quantityTong]"
                                                            data-price="{{ $stockItemMethod['items'][0]['price'] }}"
                                                            data-price2="{{ $stockItemMethod['items'][0]['priceTransporter'] }}"
                                                            value="{{ old("stall.$index.quantityTong", 0) }}" 
                                                            min="0" required/>
                                                        @error('stall.' . $index . '.quantityTong')
                                                            <div class="invalid-feedback d-block">{{ $message }}</div>
                                                        @enderror
                                                    </div>

                                                    <!-- Total -->
                                                    <div class="fv-row col-span-2">
                                                        <x-input-label class="labelStallSmol d-md-none" for="name" :value="__('Total')" />
                                                        <input type="text"
                                                            class="form-control form-control-solid total-amount-input"
                                                            name="stall[{{ $index }}][unitPrice]"
                                                            id="unitPrice_{{ $index }}" readonly tabindex="-1">
                                                        <input type="hidden" class="total-transporter-input">
                                                    </div>

                                                    <!-- Action -->
                                                    <div class="fv-row col-span-1">
                                                        <x-input-label class="labelStallSmol d-md-none" for="name" :value="__('Action')" />
                                                        <span class="flex justify-end">
                                                            @if ($iterationCount > 0)
                                                                <button type="button" class="btn btn-danger removeStallBtn">
                                                                    <span class="indicator-label">-</span>
                                                                </button>
                                                            @endif
                                                        </span>
                                                    </div>
                                                </div>
                                                
                                                <!-- Second Row: Deposit Details -->
                                                <div class="grid gap-6 mb-3 md:grid-cols-8 depositRow bg-light-primary rounded py-5">
                                                    <!-- Label Column -->
                                                    <div class="fv-row col-span-1 d-flex align-items-center justify-content-center">
                                                        <span class="text-muted fw-semibold fs-7">Deposit Detail</span>
                                                    </div>

                                                    <!-- Deposit Payment Method -->
                                                    <div class="fv-row col-span-2">
                                                        <div class="mb-3">
                                                            <x-input-label for="name" :value="__('Payment Method')" />
                                                        </div>
                                                        <select class="form-select @error('stall.' . $index . '.depositPaymentMethod') is-invalid @enderror"
                                                            data-control="select2"
                                                            data-placeholder="Deposit Payment Method"
                                                            name="stall[{{ $index }}][depositPaymentMethod]" 
                                                            id="depositPaymentMethod_{{ $index }}"
                                                            data-hide-search="true">
                                                            <option></option>
                                                            @foreach ($paymentMethod['result'] as $method)
                                                                <option value="{{ $method }}"
                                                                    @if (old("stall.$index.depositPaymentMethod") == $method) selected @endif>
                                                                    {{ $method }}
                                                                </option>
                                                            @endforeach
                                                        </select>
                                                        @error('stall.' . $index . '.depositPaymentMethod')
                                                            <div class="invalid-feedback">{{ $message }}</div>
                                                        @enderror
                                                    </div>

                                                    <!-- Deposit Amount -->
                                                    <div class="fv-row col-span-2">
                                                        <div class="mb-3">
                                                            <x-input-label for="name" :value="__('Amount (RM)')" />
                                                        </div>
                                                        <input type="number" min="0" step="0.01"
                                                            value="{{ old("stall.$index.depositAmount") }}"
                                                            class="form-control @error('stall.' . $index . '.depositAmount') is-invalid @enderror"
                                                            name="stall[{{ $index }}][depositAmount]" 
                                                            id="depositAmount_{{ $index }}"
                                                            placeholder="0.00">
                                                        @error('stall.' . $index . '.depositAmount')
                                                            <div class="invalid-feedback">{{ $message }}</div>
                                                        @enderror
                                                    </div>

                                                    <!-- Empty Column for alignment -->
                                                    <div class="fv-row col-span-1"></div>
                                                </div>

                                                <!-- Hidden Price Fields -->
                                                <input type="hidden" name="tongPrice" value="{{ $stockItemMethod['items'][0]['price'] }}" />
                                                <input type="hidden" name="tongTransporterPrice" value="{{ $stockItemMethod['items'][0]['priceTransporter'] }}" />
                                            </div>
                                            @php
                                                $iterationCount++;
                                            @endphp
                                        @endforeach
                                    </div>
                                </div>

                                <!-- Add Stall Button -->
                                <div class="grid gap-6 mb-5 md:grid-cols-8">
                                    <div class="fv-row col-span-2">
                                        <button class="btn btn-primary form-control" type="button" id="addStallBtn">
                                            <i class="ki-duotone ki-plus fs-3"></i>
                                            <span class="indicator-label">Add Stall</span>
                                        </button>
                                    </div>
                                </div>

                                <div class="separator separator-dashed my-10"></div>

                                <!-- Totals -->
                                <div class="container mb-5">
                                    <div class="row mt-3">
                                        <div class="col-md-9">
                                            <div class="form-control form-control-transparent fs-4 text-dark text-end">
                                                Total Quantity
                                            </div>
                                        </div>
                                        <div class="col-md-3 ms-auto">
                                            <input class="form-control form-control-solid fs-4 text-center"
                                                type="number" name="GrandQuantity" id="total_quantity"
                                                value="{{ old('total_quantity', 0) }}" readonly tabindex="-1">
                                        </div>
                                    </div>

                                    <div class="row mt-3">
                                        <div class="col-md-9">
                                            <div class="form-control form-control-transparent fs-4 text-dark text-end">
                                                Grand Total (RM)
                                            </div>
                                        </div>
                                        <div class="col-md-3 ms-auto">
                                            <input class="form-control form-control-solid fs-4 text-center"
                                                type="number" name="GrandTotal" id="total_amount"
                                                value="{{ old('total_amount', 0) }}" readonly tabindex="-1">
                                        </div>
                                    </div>
                                </div>

                                <div class="separator separator-dashed my-10"></div>

                                <!-- Submit Buttons -->
                                <div class="d-flex justify-content-end gap-2">
                                    <x-primary-button class="btn btn-warning" name="statusID" value="1">
                                        <i class="ki-duotone ki-archive-tick fs-3">
                                            <i class="path1"></i>
                                            <i class="path2"></i>
                                        </i>
                                        Save Draft
                                    </x-primary-button>

                                    <x-primary-button class="btn btn-primary" name="statusID" value="2">
                                        <i class="ki-duotone ki-triangle fs-3">
                                            <span class="path1"></span>
                                            <span class="path2"></span>
                                            <span class="path3"></span>
                                        </i>
                                        Submit
                                    </x-primary-button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <x-slot name="scripts">
        <script>
            // @if($message = session('message'))
            //     Swal.fire({
            //         title: 'Error',
            //         html: '{!! $message !!}',
            //         icon: '{{ session("alertType") }}'
            //     })
            // @endif

            $(document).ready(function() {
                $('button[name="statusID"]').on('click', function(e) {
                    e.preventDefault();
                    
                    const form = document.getElementById('geraiForm');
                    const statusValue = $(this).val();
                    
                    // Check form validity
                    if (!form.checkValidity()) {
                        // Find first invalid element
                        const firstInvalid = form.querySelector(':invalid');

                        if (firstInvalid) {
                            // Calculate position
                            const navbarHeight = 200; // Adjust this value
                            const elementTop = $(firstInvalid).offset().top;
                            const scrollPosition = elementTop - navbarHeight;
                            
                            // Scroll to element
                            $('html, body').animate({
                                scrollTop: scrollPosition
                            }, 400, function() {
                                
                                // Show validation message
                                if ($(firstInvalid).hasClass('select2-hidden-accessible')) {
                                    $(firstInvalid).select2('open');
                                }
                                firstInvalid.reportValidity();
                            });
                        }
                        
                        return false;
                    } else {
                        // Create hidden input for statusID if it doesn't exist
                        let statusInput = form.querySelector('input[name="statusID"]');
                        if (!statusInput) {
                            statusInput = document.createElement('input');
                            statusInput.type = 'hidden';
                            statusInput.name = 'statusID';
                            form.appendChild(statusInput);
                        }
                        statusInput.value = statusValue;
                        
                        // Submit the form
                        form.submit();
                    }
                });

                // Initialize Flatpickr
                $('#kt_datepicker_2').flatpickr({
                    dateFormat: "d/m/Y",
                    defaultDate: "today",
                    autoclose: true
                });

                // Initialize Select2
                $('#codeSelect, #nameSelect, #paymentMethod').select2();

                // Transporter Code/Name synchronization
                $('#codeSelect').on('change', function() {
                    var selectedOption = $(this).find(':selected');
                    var transporterName = selectedOption.data('transporter-name');
                    $('#nameSelect').val(transporterName).trigger('change.select2');
                });

                $('#nameSelect').on('change', function() {
                    var selectedOption = $(this).find(':selected');
                    var transporterCode = selectedOption.data('transporter-code');
                    $('#codeSelect').val(transporterCode).trigger('change.select2');
                });

                // Stall Management
                var stallCount = {{ $iterationCount }};
                const maxStall = 150;
                const tongPrice = parseFloat('{{ $stockItemMethod['items'][0]['price'] }}');
                const tongTransporterPrice = parseFloat('{{ $stockItemMethod['items'][0]['priceTransporter'] }}');

                // Calculate row total
                function calculateRowTotal(row) {
                    var inputQuantity = parseFloat(row.find('.tank-quantity-input').val()) || 0;
                    var price = parseFloat(row.find('.tank-quantity-input').data('price')) || 0;
                    var priceTransporter = parseFloat(row.find('.tank-quantity-input').data('price2')) || 0;

                    var rowTotal = inputQuantity * price;
                    var rowTransporterTotal = inputQuantity * priceTransporter;

                    row.find('.total-amount-input').val(rowTotal.toFixed(2));
                    row.closest('.stall-group').find('.total-transporter-input').val(rowTransporterTotal.toFixed(2));
                }

                // Calculate grand total
                function calculateGrandTotal() {
                    var totalQuantity = 0;
                    var grandTotal = 0;

                    $('.stall-group').each(function() {
                        var quantity = parseFloat($(this).find('.tank-quantity-input').val()) || 0;
                        var rowTotal = parseFloat($(this).find('.total-amount-input').val()) || 0;

                        totalQuantity += quantity;
                        grandTotal += rowTotal;
                    });

                    $('#total_quantity').val(totalQuantity);
                    $('#total_amount').val(grandTotal.toFixed(2));
                }

                // Update all calculations
                function updateAllCalculations() {
                    $('.stallRow').each(function() {
                        calculateRowTotal($(this));
                    });
                    calculateGrandTotal();
                }

                // Bind input events
                $(document).on('input', '.tank-quantity-input', function() {
                    calculateRowTotal($(this).closest('.stallRow'));
                    calculateGrandTotal();
                });

                // Update row numbers
                function updateRowNumbers() {
                    $('.stall-group').each(function(index) {
                        $(this).find('.row-number').val(index + 1);
                        $(this).attr('data-stall-index', index);
                    });
                }

                // Add stall button
                $('#addStallBtn').click(function() {
                    if (stallCount >= maxStall) {
                        Swal.fire({
                            title: 'Maximum Reached',
                            text: 'You have reached the maximum number of stalls (150).',
                            icon: 'warning'
                        });
                        return;
                    }

                    const newStallGroup = `
                        <div class="border border-gray-300 p-3 stall-group" data-stall-index="${stallCount}">
                            <!-- First Row: Stall Details -->
                            <div class="grid gap-6 mb-2 md:grid-cols-8 py-3 stallRow">
                                <div class="fv-row col-span-1">
                                    <x-input-label class="labelStallSmol d-md-none" for="name" :value="__('No')" />
                                    <input type="text" class="form-control form-control-solid row-number" value="${stallCount + 1}" readonly tabindex="-1">
                                </div>
                                <div class="fv-row col-span-2">
                                    <x-input-label class="labelStallSmol d-md-none" for="name" :value="__('Stall')" />
                                    <select class="form-select" data-placeholder="Select Stall" name="stall[${stallCount}][stallId]"
                                        id="stallSelect_${stallCount}" data-allow-clear="true" data-control="select2" required>
                                        <option></option>
                                        @foreach ($stallMethod['stalls'] as $stall)
                                            <option value="{{ $stall['stallCode'] }}" data-stall-code="{{ $stall['stallCode'] }}">
                                                {{ $stall['stallCode'] }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="fv-row col-span-2">
                                    <x-input-label class="labelStallSmol d-md-none" for="name" :value="__('Tong')" />
                                    <input type="number" class="form-control tank-quantity-input w-100"
                                        name="stall[${stallCount}][quantityTong]"
                                        data-price="${tongPrice}" data-price2="${tongTransporterPrice}"
                                        value="0" min="0" required />
                                </div>
                                <div class="fv-row col-span-2">
                                    <x-input-label class="labelStallSmol d-md-none" for="name" :value="__('Total')" />
                                    <input type="text" class="form-control form-control-solid total-amount-input"
                                        name="stall[${stallCount}][unitPrice]" id="unitPrice_${stallCount}" readonly tabindex="-1">
                                    <input type="hidden" class="total-transporter-input">
                                </div>
                                <div class="fv-row col-span-1">
                                    <x-input-label class="labelStallSmol d-md-none" for="name" :value="__('Action')" />
                                    <span class="flex justify-end">
                                        <button type="button" class="btn btn-danger removeStallBtn">
                                            <span class="indicator-label">-</span>
                                        </button>
                                    </span>
                                </div>
                            </div>
                            <!-- Second Row: Deposit Details -->
                            <div class="grid gap-6 mb-3 md:grid-cols-8 depositRow bg-light-primary rounded py-5">
                                <div class="fv-row col-span-1 d-flex align-items-center justify-content-center">
                                    <span class="text-muted fw-semibold fs-7">Deposit Detail</span>
                                </div>
                                <div class="fv-row col-span-2">
                                    <div class="mb-3">
                                        <x-input-label for="name" :value="__('Payment Method')" />
                                    </div>
                                    <select class="form-select" data-control="select2"
                                        data-placeholder="Deposit Payment Method"
                                        name="stall[${stallCount}][depositPaymentMethod]" 
                                        id="depositPaymentMethod_${stallCount}"
                                        data-hide-search="true">
                                        <option></option>
                                        @foreach ($paymentMethod['result'] as $method)
                                            <option value="{{ $method }}">{{ $method }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="fv-row col-span-2">
                                    <div class="mb-3">
                                        <x-input-label for="name" :value="__('Amount (RM)')" />
                                    </div>
                                    <input type="number" min="0" step="0.01" class="form-control"
                                        name="stall[${stallCount}][depositAmount]" 
                                        id="depositAmount_${stallCount}" placeholder="0.00">
                                </div>
                                <div class="fv-row col-span-1"></div>
                            </div>
                            <input type="hidden" name="tongPrice" value="${tongPrice}" />
                            <input type="hidden" name="tongTransporterPrice" value="${tongTransporterPrice}" />
                        </div>
                    `;

                    $('#stallContainer').append(newStallGroup);
                    
                    // Initialize Select2 for new selects
                    $(`#stallSelect_${stallCount}`).select2();
                    $(`#depositPaymentMethod_${stallCount}`).select2();
                    
                    stallCount++;
                    updateAllCalculations();
                });

                // Remove stall button
                $(document).on('click', '.removeStallBtn', function() {
                    $(this).closest('.stall-group').remove();
                    stallCount--;
                    updateRowNumbers();
                    updateAllCalculations();
                });

                // Initial calculations
                updateAllCalculations();

                // Initialize all existing Select2 dropdowns
                $('[data-control="select2"]').each(function() {
                    if (!$(this).hasClass('select2-hidden-accessible')) {
                        $(this).select2();
                    }
                });
            });
        </script>
    </x-slot>
</x-app-layout>