<x-app-layout>
    <div class="app-main flex-column flex-row-fluid">
        <div class="d-flex flex-column flex-column-fluid">
            <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 Invoice</h1>
                        {{ Breadcrumbs::render('invoice.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>
            <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">
                            <section>
                                <form action="{{ route('admin.invoice.store') }}" method="POST" id="invoiceForm" >
                                    @csrf
                                    <!-- Prevent implicit submission of the form -->
                                    <button type="submit" disabled style="display: none" aria-hidden="true"></button>
                                    <div class="d-flex flex-column align-items-start flex-xxl-row">
                                        <div class="d-flex flex-center fw-row text-nowrap order-1 order-xxl-2 me-4 mb-3">
                                            <span
                                                class="fs-2x fw-bold text-gray-800 required form-label me-5">Invoice</span>
                                            <span class=" input-group-text fs-3"
                                                id="inputGroup-sizing-lg">#KPBIV-</span>
                                            <input type="text"
                                                class="form-control fs-3 @error('invoiceNo') is-invalid @enderror"
                                                name="invoiceNo" id="invoiceNo" value="{{ old('invoiceNo') }}"
                                                minlength="6" required />
                                            <x-input-error :messages="$errors->get('invoiceNo')" class="mt-3" />
                                        </div>
                                        <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') ? old('date') : date('Y-m-d') }}" required/>
                                            </div>
                                            <x-input-error :messages="$errors->get('date')" class="mt-3" />
                                        </div>
                                    </div>

                                    <div class="d-flex flex-column align-items-start flex-xxl-row">
                                        <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">Invoice Payment Method:</div>
                                            <div class="position-relative align-items-center w-250px">
                                                <select
                                                    class="form-select @error('invoicePaymentMethod') is-invalid @enderror"
                                                    data-control="select2" data-placeholder="Select Option"
                                                    name="invoicePaymentMethod" id="invoicePaymentMethod" data-hide-search="true">
                                                    <option></option>
                                                    @foreach ($paymentMethod['result'] as $method)
                                                        <option value="{{ $method }}"
                                                            @if (old('invoicePaymentMethod') == $method) selected @endif>
                                                            {{ $method }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                                <x-input-error :messages="$errors->get('invoicePaymentMethod')" class="mt-3" />

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

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

                                    <div class="mb-0">
                                        <div class="row gx-10 mb-5">
                                            <div class="fs-5 fw-bold text-dark mb-10">Debtor Details</div>
                                            <div class="row">
                                                <!-- Debtor Code -->
                                                <div class="col-md-6">
                                                    <div class="mb-5">
                                                        <label
                                                            class="form-label text-gray-600 required form-label">Debtor
                                                            Code</label>
                                                        <select
                                                            class="form-select @error('debtorCode') is-invalid @enderror"
                                                            name="debtorCode" data-control="select2"
                                                            data-placeholder="Select Debtor Code"
                                                            data-allow-clear="true" id="codeSelect" required>
                                                            <option></option>
                                                            @foreach ($debtorDetail['result'] as $debtor)
                                                                <option value="{{ $debtor['accNo'] }}"
                                                                    data-debtor-name="{{ $debtor['companyName'] }}"
                                                                    @if (old('debtorCode') == $debtor['accNo']) selected @endif>
                                                                    {{ $debtor['accNo'] }}
                                                                </option>
                                                            @endforeach
                                                        </select>
                                                        <x-input-error :messages="$errors->get('debtorCode')" class="mt-3" />

                                                    </div>
                                                </div>
                                                <!-- Debtor Name -->
                                                <div class="col-md-6">
                                                    <div class="mb-5">
                                                        <label
                                                            class="form-label text-gray-600 required form-label">Debtor
                                                            Name</label>
                                                        <select
                                                            class="form-select @error('debtorName') is-invalid @enderror"
                                                            name="debtorName" data-control="select2"
                                                            data-placeholder="Select Debtor Name"
                                                            data-allow-clear="true" id="nameSelect" required>
                                                            <option></option>
                                                            @foreach ($debtorDetail['result'] as $debtor)
                                                                <option value="{{ $debtor['companyName'] }}"
                                                                    data-debtor-code="{{ $debtor['accNo'] }}"
                                                                    @if (old('debtorName') == $debtor['companyName']) selected @endif>
                                                                    {{ $debtor['companyName'] }}
                                                                </option>
                                                            @endforeach
                                                        </select>
                                                        <x-input-error :messages="$errors->get('debtorName')" class="mt-3" />

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

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

                                        <div class="row gx-10 mb-5">
                                            <div class="fs-5 fw-bold text-dark mb-10">Deposit Details</div>
                                            <div class="row">
                                                <!-- Deposit Reference No -->
                                                <div class="col-md-6">
                                                    <div class="mb-5">
                                                        <label class="form-label text-gray-600">Deposit
                                                            Reference
                                                            No</label>
                                                        <input type="text" value="{{ old('depositNo') }}"
                                                            class="form-control @error('depositNo') is-invalid @enderror"
                                                            name="depositNo" id="depositNo"
                                                            placeholder="Deposit Reference No">
                                                            <x-input-error :messages="$errors->get('depositNo')" class="mt-3" />

                                                    </div>
                                                </div>
                                                <!-- Deposit Payment Method -->
                                                <div class="col-md-6">
                                                    <div class="mb-5">
                                                        <label class="form-label text-gray-600">Deposit Payment
                                                            Method</label>
                                                        <select
                                                            class="form-select @error('paymentMethod') is-invalid @enderror"
                                                            data-control="select2"
                                                            data-placeholder="Deposit Payment Method"
                                                            name="paymentMethod" id="paymentMethod"
                                                            data-hide-search="true">
                                                            <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>
                                            <!-- Row for Deposit Amount -->
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <div class="mb-5">
                                                        <label class="form-label text-gray-600">Deposit Amount
                                                            (RM)</label>
                                                        <input type="number" min="0"
                                                            value="{{ old('depositAmount') }}"
                                                            class="form-control @error('depositAmount') is-invalid @enderror"
                                                            name="depositAmount" id="depositAmount"
                                                            placeholder="Deposit Amount">
                                                            <x-input-error :messages="$errors->get('depositAmount')" class="mt-3" />
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

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

                                        <div class="container mb-5">
                                            <div class="fs-5 fw-bold text-dark mb-10">Item Details</div>
                                            <div class="row">
                                                @php
                                                    $itemIndex = 0;
                                                @endphp

                                                @foreach ($itemMapper as $item)
                                                    @if ($itemIndex % 3 == 0 && $itemIndex != 0)
                                                        <div class="border w-100 my-3"></div>
                                                        <!-- Insert line after every 3 items -->
                                                    @endif
                                                    <div class="col-md-4 mb-3">
                                                        <div class="d-flex">
                                                            <div class="flex-grow-1">
                                                                <input type="text"
                                                                    class="form-control form-control-transparent text-end"
                                                                    name="item_code_{{ $item['itemCode'] }}"
                                                                    value="{{ strtoupper($item['itemCode']) }}"
                                                                    readonly
                                                                    tabindex="-1">
                                                            </div>
                                                            <div class="flex-grow-1">
                                                                <input type="number" min="0"
                                                                    class="form-control @error($item['itemQty']) is-invalid @enderror"
                                                                    name="{{ $item['itemQty'] }}"
                                                                    data-item-code="{{ $item['itemCode'] }}"
                                                                    data-price="{{ $item['itemPrice'] }}"
                                                                    value="{{ old($item['itemQty'], 0) }}"
                                                                    onclick="this.select()">
                                                                    <x-input-error :messages="$errors->get($item['itemQty'])" class="mt-3" />
                                                            </div>
                                                        </div>
                                                    </div>

                                                    @php
                                                        $itemIndex++;
                                                    @endphp
                                                @endforeach

                                            </div>

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

                                            <div class="container">
                                                <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" min="0" name="total_quantity"
                                                            id="total_quantity"
                                                            value="{{ old('total_quantity', 0) }}" readonly>
                                                    </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" min="0" name="total_amount"
                                                            id="total_amount" value="{{ old('total_amount', 0) }}"
                                                            readonly>
                                                    </div>
                                                </div>
                                            </div>

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

                                            <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>
                                        </div>
                                </form>
                            </section>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</x-app-layout>

<script>
    @if($message = session('message'))
    Swal.fire({
        title: 'Error',
        html: '{!! $message !!}',
        icon: '{{ session("alertType") }}'
    })
    @endif
    $(document).ready(function() {
        $('#kt_datepicker_2').flatpickr({
            dateFormat: "d/m/Y",
            defaultDate: "today",
            autoclose: true
        });

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

        // Event handler for dropdown changes
        $('#codeSelect, #nameSelect').on('change', function() {
            var selectedOption = $(this).find(':selected');
            var debtorCode = selectedOption.data('debtor-code');
            var debtorName = selectedOption.data('debtor-name');

            // Update the values for the other dropdown
            if ($(this).attr('id') === 'codeSelect') {
                // If codeSelect is changed, update nameSelect
                $('#nameSelect').val(debtorName).trigger('change.select2');
            } else if ($(this).attr('id') === 'nameSelect') {
                // If nameSelect is changed, update codeSelect
                $('#codeSelect').val(debtorCode).trigger('change.select2');
            }

            var debtorCodePlaceholder = debtorCode ? 'Debtor Code for ' + debtorName : 'Select Debtor';
            var debtorNamePlaceholder = debtorName ? 'Debtor Name for ' + debtorCode : 'Debtor Name';

            // Update the placeholders
            $('#codeSelect').attr('data-placeholder', debtorCodePlaceholder).trigger(
                'change.select2');
            $('#nameSelect').attr('data-placeholder', debtorNamePlaceholder).trigger('change.select2');
        });

        // auto update the grand total when user input quantity item

        $('#invoiceForm').on('input', 'input[name^="quantity"]', function() {
            updateTotal();
        });

        function updateTotal() {
            var total = 0;
            var quantity = 0;
            var itemData = [];

            $('input[name^="quantity"]').each(function() {
                var itemCode = $(this).attr('data-item-code');
                var inputQuantity = parseFloat($(this).val()); // Parse input quantity as a number
                var price = parseFloat($(this).attr('data-price'));

                if (!isNaN(inputQuantity) && !isNaN(price)) {
                    total += inputQuantity * price;
                    quantity += inputQuantity;
                }
            });

            if (!isNaN(total)) {
                $('#total_amount').val(total.toFixed(2));
                $('#total_quantity').val(quantity);
            }

            // Update the displayed values in the form
            $('#displayed_total_amount').text(total.toFixed(2));
            $('#displayed_total_quantity').text(quantity);

        }
    });
</script>
