<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">
                            Invoice</h1>
                        {{ Breadcrumbs::render('invoice.show', $invoice) }}
                    </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>
                        @endif

                        @can('invoice-edit')
                            @if ($invoice->statusID != '2')
                                <x-primary-button onclick="window.location='{{ route('admin.invoice.edit', $invoice->id) }}'"
                                    class="btn btn-bg-warning text-light">
                                    <i class="ki-duotone ki-notepad-edit fs-3 text-light">
                                        <i class="path1"></i>
                                        <i class="path2"></i>
                                    </i>
                                    {{ __('Edit') }}
                                </x-primary-button>

                                <form action="{{ route('admin.invoice.update', $invoice->id) }}" method="POST">
                                    @csrf
                                        <input type="hidden" name="invoiceNo" id="invoiceNo"
                                            value="{{ old('invoice', $invoice->invoiceNo) }}" />
                                        <input type="hidden" id="date" name="date"
                                            value="{{ old('date', $formattedDate) }}" />
                                        <input type="hidden" name="debtorCode" id="debtorCode"
                                            value="{{ old('debtorCode', $invoice->debtorCode) }}">
                                        <input type="hidden" name="debtorName" id="debtorName"
                                            value="{{ old('debtorName', $invoice->debtorName) }}">
                                        <input type="hidden" name="total_amount" id="total_amount"
                                            value="{{ old('total_amount', $invoice->totalAmount) }}">
                                        <input type="hidden" name="total_quantity" id="total_quantity"
                                            value="{{ old('total_quantity', $invoice->totalQuantity) }}">
                                        @foreach ($deposits as $deposit)
                                            <input type="hidden" name="depositNo" id="depositNo"
                                                value="{{ old('depositNo', $deposit->depositNo) }}">
                                            <input type="hidden" name="depositAmount" id="depositAmount"
                                                value="{{ old('depositAmount', $deposit->depositAmount) }}">
                                            <input type="hidden" name="paymentMethod" id="paymentMethod"
                                                value="{{ old('paymentMethod', $deposit->paymentMethod) }}">
                                        @endforeach
                                        @foreach ($payments as $payment)
                                            <input type="hidden" id="invoicePaymentMethod" name="invoicePaymentMethod"
                                                value="{{ old('invoicePaymentMethod', $payment->paymentMethod) }}" />
                                        @endforeach
                                        @foreach ($itemMapper as $item)
                                            <input type="hidden" name="item_code_{{ $item['itemCode'] }}"
                                                value="{{ strtoupper($item['itemCode']) }}">
                                            <input type="hidden" name="{{ $item['itemQty'] }}"
                                                data-item-code="{{ $item['itemCode'] }}" data-price="{{ $item['itemPrice'] }}"
                                                value="{{ $fishtankQuantities[$item['itemCode']] ?? 0 }}"
                                                id="quantity_{{ $item['itemCode'] }}">
                                        @endforeach
                                    <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>
                                </form>
                            @endif
                        @endcan

                        @can('invoice-delete')
                            <!-- Delete Button -->
                            <form action="{{ route('admin.invoice.destroy', $invoice->id) }}" method="POST"
                                class="delete-form">
                                @csrf
                                @method('DELETE')
                                <x-primary-button class="btn btn-danger">
                                    <i class="ki-duotone ki-trash fs-3">
                                        <i class="path1"></i>
                                        <i class="path2"></i>
                                    </i>
                                    {{ __('Delete') }}
                                </x-primary-button>
                            </form>
                        @endcan
                    </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>
                                    <div class="card-body py-20">
                                        <div class="mw-lg-950px mx-auto w-100">

                                            @if ($invoice->statusID == '2')
                                                <div class="badge badge-success badge-lg">Submitted</div>
                                            @elseif ($invoice->statusID == '1')
                                                <div class="badge badge-warning badge-lg">Draft</div>
                                            @endif

                                            <div class="d-flex justify-content-between flex-column flex-sm-row mb-19">
                                                <h4 class="fw-bolder text-gray-800 fs-2qx pe-5 pb-7">INVOICE
                                                    #{{ $invoice->invoiceName }}</h4>

                                                <div class="text-sm-end">
                                                    <a href="#" class="d-block mw-150px ms-sm-auto">
                                                        <img alt="Logo"
                                                            src="{{ asset('assets/media/logos/parvuz-logo.png') }}"
                                                            class="w-100" />
                                                    </a>

                                                    <div class="text-sm-end fw-semibold fs-4 text-muted mt-7">
                                                        <div>Konsortium Pasar Borong</div>
                                                    </div>

                                                </div>
                                            </div>

                                            <div class="pb-12">
                                                <div class="d-flex flex-column gap-7 gap-md-10">
                                                    <div class="fw-bold fs-2">
                                                        Dear {{ $invoice->debtorName }} <span
                                                            class="fs-6">({{ $invoice->debtorCode }})</span>,<br />
                                                        <span class="text-muted fs-5">Here are your order details. We
                                                            thank you
                                                            for
                                                            your purchase.</span>
                                                    </div>

                                                    <div class="separator"></div>

                                                    <span class="text-muted fs-5">Customer Details</span>
                                                    <div class="d-flex flex-row flex-sm-row gap-7 gap-md-10 fw-bold">
                                                        <div class="flex-root d-flex flex-column">
                                                            <span class="text-muted">Date</span>
                                                            <span
                                                                class="fs-5">{{ date('d/m/Y', strtotime($invoice->date)) }}</span>
                                                        </div>
                                                        <div class="flex-root d-flex flex-column">
                                                            <span class="text-muted">ID</span>
                                                            <span class="fs-5">#{{ $invoice->debtorCode }}</span>
                                                        </div>
                                                        <div class="flex-root d-flex flex-column">
                                                            <span class="text-muted">Name</span>
                                                            <span class="fs-5">{{ $invoice->debtorName }}</span>
                                                        </div>
                                                    </div>

                                                    <div class="separator"></div>

                                                    <div
                                                        class="d-flex flex-column flex-sm-row gap-7 gap-md-10 fw-bold">
                                                        <div class="flex-root d-flex flex-column">
                                                            <span class="text-muted fs-5">Deposit Details</span><br>
                                                            @foreach ($deposits as $deposit)
                                                                <span class="fs-5">
                                                                    Deposit Number: # {{ $deposit->depositNo ?: 'N/A' }}<br />
                                                                    Deposit Amount: RM {{ $deposit->depositAmount ?: 'N/A' }}<br />
                                                                    Payment Method: {{ $deposit->paymentMethod ?: 'N/A' }}<br />
                                                                </span>
                                                            @endforeach
                                                        </div>

                                                        <div class="flex-root d-flex flex-column">
                                                            <span class="text-muted">Payment Details</span><br>
                                                            @foreach ($payments as $payment)
                                                                <span class="fs-5">
                                                                    {{-- Payment Number: #{{ $payment->paymentNo }}<br />
                                                                    Payment Amount: RM {{ $payment->paymentAmount }}<br /> --}}
                                                                    Payment Method: {{ $payment->paymentMethod }}<br />
                                                                </span>
                                                            @endforeach
                                                        </div>
                                                    </div>

                                                    <div class="separator"></div>

                                                    <div class="d-flex justify-content-between flex-column">

                                                        <div class="table-responsive border-bottom mb-9">
                                                            <table
                                                                class="table align-middle table-row-dashed fs-6 gy-5 mb-0">
                                                                <thead>
                                                                    <tr class="border-bottom fs-5 fw-bold text-muted">
                                                                        <th class="min-w-175px pb-2">Items</th>
                                                                        <th class="min-w-70px text-end pb-2">Unit Price
                                                                            (RM)
                                                                        </th>
                                                                        <th class="min-w-80px text-end pb-2">Quantity
                                                                        </th>
                                                                        <th class="min-w-100px text-end pb-2">Total
                                                                            (RM)
                                                                        </th>
                                                                    </tr>
                                                                </thead>

                                                                <tbody class="fw-semibold text-gray-800">
                                                                    @foreach ($fishtanks as $fishtank)
                                                                        <tr>
                                                                            <td>
                                                                                <div class="d-flex align-items-center">
                                                                                    <div class="ms-5">
                                                                                        <div class="fw-bold">
                                                                                            {{ strtoupper($fishtank->fishTanks) }}
                                                                                        </div>
                                                                                    </div>
                                                                                </div>
                                                                            </td>
                                                                            <td class="text-end">
                                                                                {{ $fishtank->unitPrice }}
                                                                            </td>
                                                                            <td class="text-end">
                                                                                {{ $fishtank->quantity }}
                                                                            </td>
                                                                            <td class="text-end">
                                                                                {{ number_format($fishtank->unitPrice * $fishtank->quantity, 2) }}
                                                                            </td>
                                                                        </tr>
                                                                    @endforeach

                                                                    <tr>
                                                                        <td>
                                                                            <div
                                                                                class="d-flex align-items-center fs-3 text-dark fw-bold text-end">
                                                                                <div class="ms-5">
                                                                                    <div class="fw-bold">Grand Total
                                                                                    </div>
                                                                                </div>
                                                                            </div>
                                                                        </td>
                                                                        <td class="text-end"></td>
                                                                        <td class="text-end fs-3 text-dark fw-bold">
                                                                            {{ $invoice->totalQuantity }}
                                                                        </td>
                                                                        <td class="text-end fs-3 text-dark fw-bold">
                                                                            {{ $invoice->totalAmount }}
                                                                        </td>
                                                                    </tr>
                                                                </tbody>
                                                            </table>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                            </section>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</x-app-layout>

<script>
    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,
                    confirmButtonColor: '#d33',
                    cancelButtonColor: '#3085d6',
                    confirmButtonText: 'Yes, delete it!'
                }).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>
