<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">
                            Edit Invoice</h1>
                        {{ Breadcrumbs::render('invoice.edit', $invoice) }}
                    </div>
                    <div class="d-flex align-items-center ml-auto gap-2 gap-lg-3">
                        <x-add-back-button onclick="window.location='{{ url()->previous() }}'">
                            <i class="ki-duotone ki-left fs-3"></i>
                            {{ __('Back') }}
                        </x-add-back-button>
                    </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.update', $invoice->id) }}" method="POST"
                                    id="edit-form">
                                    @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('invoice', $invoice->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"
                                            data-bs-toggle="tooltip" data-bs-trigger="hover"
                                            title="Specify invoice date">
                                            <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', $formattedDate) }}" 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">
                                        @foreach ($payments as $payment)
                                            <div
                                                class="d-flex align-items-center justify-content-end flex-equal order-2 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="Invoice Payment Method"
                                                        name="invoicePaymentMethod" id="invoicePaymentMethod"
                                                        data-hide-search="true">
                                                        <option></option>
                                                        @foreach ($paymentMethod['result'] as $method)
                                                            <option value="{{ $method }}"
                                                                {{ $payment->paymentMethod == $method ? 'selected' : '' }}>
                                                                {{ $method }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                    <x-input-error :messages="$errors->get('invoicePaymentMethod')" class="mt-3" />

                                                </div>
                                            </div>
                                        @endforeach
                                    </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">
                                                <div class="col-md-6">
                                                    <div class="mb-5">
                                                        <label
                                                            class="form-label text-gray-600 required form-label">Debtor
                                                            Code</label>
                                                        <input type="text"
                                                            class="form-control  @error('debtorCode') is-invalid @enderror"
                                                            name="debtorCode" id="debtorCode" placeholder="Debtor Code"
                                                            value="{{ old('debtorCode', $invoice->debtorCode) }}"
                                                            readonly required>
                                                        <x-input-error :messages="$errors->get('debtorCode')" class="mt-3" />
                                                    </div>
                                                </div>
                                                <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"
                                                            data-hide-search="true" required>
                                                            <option></option>
                                                            @foreach ($debtorDetail['result'] as $debtor)
                                                                @if ($invoice->debtorCode == $debtor['accNo'])
                                                                    <option value="{{ $debtor['companyName'] }}"
                                                                        selected>
                                                                        {{ $debtor['companyName'] }}
                                                                    </option>
                                                                @endif
                                                            @endforeach
                                                        </select>
                                                        <x-input-error :messages="$errors->get('debtorName')" class="mt-3" />
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

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

                                        @foreach ($deposits as $deposit)
                                            <div class="row gx-10 mb-5">
                                                <div class="fs-5 fw-bold text-dark mb-10">Deposit Details</div>
                                                <div class="row">
                                                    <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', $deposit->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>
                                                    <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 }}"
                                                                        {{ $deposit->paymentMethod == $method ? 'selected' : '' }}>
                                                                        {{ $method }}
                                                                    </option>
                                                                @endforeach
                                                            </select>
                                                            <x-input-error :messages="$errors->get('paymentMethod')" class="mt-3" />
                                                        </div>
                                                    </div>
                                                </div>
                                                <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', $deposit->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>
                                        @endforeach

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

                                        <div class="container mb-5">
                                            <div class="fs-6 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="{{ $fishtankQuantities[$item['itemCode']] ?? 0 }}"
                                                                    id="quantity_{{ $item['itemCode'] }}"
                                                                    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-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-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>
                                </form>
                                @can('invoice-delete')
                                    <form action="{{ route('admin.invoice.destroy', $invoice->id) }}" method="POST"
                                        class="delete-form">
                                        @csrf
                                        @method('DELETE')
                                        <x-primary-button class="btn btn-danger">Delete Invoice</x-primary-button>
                                    </form>
                                @endcan
                            </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",
            autoclose: true
        });

        // auto update the grand total when user input quantity item
        // Retrieve item prices from the JSON data
        var itemPrices = {!! json_encode($itemPrice['result']) !!};

        updateTotal();

        $('#edit-form').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);

        }
    });

    document.addEventListener('DOMContentLoaded', function() {
        const deleteForms = document.querySelectorAll('.delete-form');

        deleteForms.forEach(form => {
            form.addEventListener('submit', function(event) {
                event.preventDefault();

                const invoiceID = this.getAttribute('action').split('/').pop();

                Swal.fire({
                    title: 'Confirm Deletion',
                    text: 'Are you sure you want to delete this invoice?',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, delete it!',
                    cancelButtonText: 'Cancel',
                    reverseButtons: true,
                    customClass: {
                        confirmButton: 'btn btn-success',
                        cancelButton: 'btn btn-danger'
                    },
                }).then((result) => {
                    if (result.isConfirmed) {
                        deleteInvoice(invoiceID);
                    }
                });
            });
        });

        function deleteInvoice(invoiceID) {
            const deleteUrl = `{{ route('admin.invoice.destroy', ['invoice' => ':id']) }}`.replace(':id',
                invoiceID) + '?t=' + Date.now();

            fetch(deleteUrl, {
                    method: 'DELETE',
                    headers: {
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    }
                })
                .then(response => {
                    if (response.ok) {
                        return response.json();
                    } //else {
                    //     throw new Error('Deletion failed');
                    // }
                })
                .then(data => {
                    console.log(data);
                    Swal.fire('Deleted!', 'The item has been deleted.', 'success');
                    setTimeout(() => {
                        window.location.href = '{{ route('admin.invoice.index') }}';
                    }, 1000);
                })
            // .catch(error => {
            //     console.log(error);
            //     Swal.fire('Error', 'An error occurred while deleting the item.', 'error');
            // });
        }
    });
</script>
