<x-app-layout>
    <!-- all page -->
    <div class="app-main flex-column flex-row-fluid">
        <!-- 2 div -->
        <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">
                            Show Gerai Invoice</h1>
                        {{ Breadcrumbs::render('gerai.show', $geraiInvoice) }}
                    </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 ($geraiInvoice->statusID != '2')
                        <x-primary-button onclick="window.location='{{ route('admin.gerai.edit', $geraiInvoice->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>

                        <x-primary-button class="btn btn-primary" name="statusID" value="2" onclick="document.getElementById('gerai_show_submit').click();">
                            <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>
                        @endif
                        @endcan

                        @can('invoice-delete')
                            <x-primary-button class="btn btn-danger delete" data-id="{{$geraiInvoice->id}}" data-parent="{{$geraiInvoice->parentInvoiceNo}}">
                                <i class="ki-duotone ki-trash fs-3">
                                    <i class="path1"></i>
                                    <i class="path2"></i>
                                </i>Delete
                            </x-primary-button>
                        @endcan
                    </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.update', $geraiInvoice->id) }}" method="POST">
                                @csrf
                                <section>
                                    <!-- begin::Body-->
                                    <div class="card-body py-20">
                                        <!-- begin::Wrapper-->
                                        <div class="mw-lg-950px mx-auto w-100">
                                            <!-- begin::Header-->
                                            <!--begin::Badges-->
                                            @if ($geraiInvoice->statusID == '2')
                                                <div class="badge badge-success badge-lg">Submitted</div>
                                            @elseif ($geraiInvoice->statusID == '1')
                                                <div class="badge badge-warning badge-lg">Draft</div>
                                            @endif
                                            <!--end::Badges-->
                                            <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">GERAI INVOICE
                                                    #KPBIV-{{ $InvoiceNumber = $geraiInvoice->parentInvoiceNo }}</h4>
                                                <input type="hidden" name="parentInvoiceNo" id="parentInvoiceNo" value="{{ old('parentInvoiceNo', $geraiInvoice->parentInvoiceNo) }}" required>
                                                <!--end::Logo-->
                                                <div class="text-sm-end">
                                                    <!--begin::Logo-->
                                                    <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>
                                                    <!--end::Logo-->

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

                                            <!--begin::Body-->
                                            <div class="pb-12">
                                                <!--begin::Wrapper-->
                                                <div class="d-flex flex-column gap-7 gap-md-10 mb-5">
                                                    <!--begin::Message-->
                                                    <div class="fw-bold fs-2">
                                                        Dear {{ $geraiInvoice->transporterName }} <span
                                                            class="fs-6">({{ $geraiInvoice->transporterCode }})</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 fw-bold">Customer Details</span>
                                                    
                                                    @php
                                                        $arPayment = $geraiInvoice->arPayment->first();
                                                    @endphp
                                                    <div class="grid gap-6 mb-3 md:grid-cols-4">
                                                        <!-- Date (Left) -->
                                                        <div class="fv-row fw-bold">
                                                            <x-input-label class="mb-3" for="date" :value="__('Date')" />
                                                            <span class="fs-5 fw-bold">
                                                                {{ date('d/m/Y', strtotime($geraiInvoice->date)) }}
                                                            </span>
                                                            <input
                                                                type="hidden"
                                                                name="date"
                                                                value="{{ old('date', $formattedDate) }}"
                                                            />
                                                        </div>

                                                        <!-- Empty columns for spacing -->
                                                        <div></div>
                                                        <div></div>

                                                        <!-- Invoice Payment Method (Right) -->
                                                        <div class="fv-row fw-bold">
                                                            <x-input-label class="mb-3" for="payment_method" :value="__('Invoice Payment Method')" />
                                                            <span class="fs-5 fw-bold">
                                                                {{ $arPayment?->paymentMethod }}
                                                            </span>
                                                            <input type="hidden" name="paymentMethod" value="{{ old('paymentMethod', $arPayment?->paymentMethod) }}" required>
                                                        </div>
                                                    </div>

                                                    <div class="grid gap-6 mb-3 md:grid-cols-4 fw-bold">
                                                        <div class="fv-row">
                                                            <x-input-label class="mb-3" for="name" :value="__('Transporter')" />
                                                            <span class="fs-5 fw-bold">#{{ $geraiInvoice->transporterCode }}</span>
                                                            <input type="hidden" name="transporterCode" id="transporterCode"
                                                            value="{{ old('transporterCode', $geraiInvoice->transporterCode) }}" required>
                                                        </div>
                                                        <div class="fv-row">
                                                            <x-input-label class="mb-3" for="name" :value="__('Transporter Name')" />
                                                            <span class="fs-5 fw-bold">{{ $geraiInvoice->transporterName }}</span>
                                                            <input type="hidden" name="transporterName" id="transporterName"
                                                            value="{{ old('transporterName', $geraiInvoice->transporterName) }}" required>
                                                        </div>
                                                        <div class="fv-row">
                                                            <x-input-label class="mb-3" for="name" :value="__('Vehicle Number')" />
                                                            <span class="fs-5 fw-bold">{{ $geraiInvoice->vehicleNo }}</span>
                                                            <input type="hidden" name="vehicleNo" id="vehicleNo" 
                                                            value="{{ old('vehicleNo', $geraiInvoice->vehicleNo) }}" required>
                                                        </div>
                                                        <div class="fv-row">
                                                            <x-input-label class="mb-3" for="name" :value="__('Phone Number')" />
                                                            <span class="fs-5 fw-bold">{{ $geraiInvoice->phoneNo }}</span>
                                                            <input type="hidden" name="phoneNo" id="phoneNo"
                                                            value="{{ old('phoneNo', $geraiInvoice->phoneNo) }}" required>
                                                        </div>
                                                    </div>
                                                </div>

                                                <div class="d-flex flex-column">

                                                    @php
                                                        // Get all gerais with the same parentInvoiceNo
                                                        $allGerais = App\Models\gerai\GeraiInvoice::with(['items', 'deposit', 'arPayment'])
                                                            ->where('parentInvoiceNo', $geraiInvoice->parentInvoiceNo)
                                                            ->orderBy('invoiceNo', 'asc')
                                                            ->get();
                                                    @endphp

                                                    <!--begin::Gerai Items Loop-->
                                                    @foreach($allGerais as $index => $gerai)
                                                        @php
                                                            $item = $gerai->items->first();
                                                            $deposit = $gerai->deposit->first();
                                                        @endphp

                                                        <div class="border border-gray-300 p-5">
                                                            <div class="px-4 py-2">
                                                                <div class="grid gap-6 md:grid-cols-4">
                                                                    <div class="fv-row form-control">
                                                                        <x-input-label for="name" :value="__('No')" />
                                                                    </div>
                                                                    <div class="fv-row form-control">
                                                                        <x-input-label for="name" :value="__('Stall')" />
                                                                    </div>
                                                                    <div class="fv-row form-control">
                                                                        <x-input-label for="name" :value="__('Tong Quantity')" />
                                                                    </div>
                                                                    <div class="fv-row form-control">
                                                                        <x-input-label for="name" :value="__('Total (RM)')" />
                                                                    </div>
                                                                </div>

                                                                <div class="grid gap-6 mb-3 md:grid-cols-4">
                                                                    <!-- Label Column -->
                                                                    <div class="fv-row">
                                                                        <span class="">{{ $index + 1 }}</span>
                                                                    </div>

                                                                    <!-- Deposit Reference No -->
                                                                    <div class="fv-row">
                                                                        {{ $gerai->debtorCode }}
                                                                        <input type="hidden" name="stall[{{ $index }}][stallId]" value="{{ $gerai->debtorCode }}">
                                                                    </div>

                                                                    <!-- Deposit Payment Method -->
                                                                    <div class="fv-row">
                                                                        {{ $item->quantity ?? 0 }}
                                                                        <input type="hidden" name="stall[{{ $index }}][quantityTong]" value="{{ $item->quantity ?? 0 }}">
                                                                    </div>

                                                                    <!-- Deposit Amount -->
                                                                    <div class="fv-row">
                                                                        <span class="">{{ number_format($gerai->totalAmount, 2) }}</span>
                                                                    </div>
                                                                </div>
                                                            </div>

                                                            @if($deposit)
                                                            <div class="bg-light-primary rounded p-4">
                                                                <div class="grid gap-6 md:grid-cols-4">
                                                                    <div class="fv-row"></div>
                                                                    <div class="fv-row">
                                                                        <x-input-label for="name" :value="__('Payment Method')" />
                                                                    </div>
                                                                    <div class="fv-row">
                                                                        <x-input-label for="name" :value="__('Deposit Amount (RM)')" />
                                                                    </div>
                                                                </div>
                                                                <div class="grid gap-6 mb-3 md:grid-cols-4 depositRow">
                                                                    <!-- Label Column -->
                                                                    <div class="fv-row d-flex align-items-center">
                                                                        <x-input-label for="name" :value="__('Deposit Detail')" />
                                                                    </div>

                                                                    <!-- Deposit Payment Method -->
                                                                    <div class="fv-row">
                                                                        <span class="">{{ $deposit->paymentMethod ?? 'Unknown' }}</span>
                                                                        <input type="hidden" name="stall[{{ $index }}][depositPaymentMethod]" value="{{ $deposit->paymentMethod }}">
                                                                    </div>

                                                                    <!-- Deposit Amount -->
                                                                    <div class="fv-row">
                                                                        <span class="">{{ number_format($deposit->depositAmount, 2) }}</span>
                                                                        <input type="hidden" name="stall[{{ $index }}][depositAmount]" value="{{ $deposit->depositAmount }}">
                                                                    </div>
                                                                </div>
                                                            </div>
                                                             @else
                                                                <!-- Hidden fields for stalls without deposits -->
                                                                <input type="hidden" name="stall[{{ $index }}][depositNo]" value="">
                                                                <input type="hidden" name="stall[{{ $index }}][depositPaymentMethod]" value="">
                                                                <input type="hidden" name="stall[{{ $index }}][depositAmount]" value="">
                                                            @endif
                                                        </div>
                                                    @endforeach
                                                </div>

                                                @php
                                                    // Calculate totals
                                                    $grandQuantity = $allGerais->sum(function($gerai) {
                                                        return $gerai->items->first()?->quantity ?? 0;
                                                    });
                                                    $grandTotal = $allGerais->sum('totalAmount');
                                                @endphp
                                                <div class="d-flex flex-column gap-7 gap-md-10 mt-10">
                                                    <div class="grid gap-6 mb-3 md:grid-cols-5">
                                                        <div class=""></div>
                                                        <div class="">
                                                            <div class="form-control form-control-transparent fs-4 text-dark text-end">
                                                                Total Quantity
                                                            </div>
                                                        </div>
                                                        <div class="">
                                                            <span>
                                                                <input class="form-control form-control-solid fs-4 text-center"
                                                                type="number" name="GrandQuantity" id="total_amount"
                                                                value="{{ $geraiInvoice->GrandQuantity }}" readonly>
                                                            </span>
                                                        </div>
                                                        <div class="">
                                                            <div class="form-control form-control-transparent fs-4 text-dark text-end">
                                                                Grand Total (RM)
                                                            </div>
                                                        </div>
                                                        <div class="">
                                                            <span>
                                                                <input class="form-control form-control-solid fs-4 text-center"
                                                                type="number" name="GrandTotal" id="grand_total"
                                                                value="{{ number_format($grandTotal, 2, '.', '') }}" readonly>
                                                            </span>
                                                        </div>
                                                    </div>
                                                    
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    @if ($geraiInvoice->statusID != '2')
                                    <div class="d-flex justify-content-end gap-2 pt-5">
                                        <x-primary-button class="btn btn-primary d-none"
                                        name="statusID" value="2" id="gerai_show_submit">
                                            <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>
                                    @endif
                                </form>
                            </section>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
<x-slot name="scripts">
    <script>
        $(document).ready(function () {

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            $('.delete').on('click', function () {
                var geraiId = $(this).data('id');
                var parentInvoiceNo = $(this).data('parent');

                Swal.fire({
                    title: 'Confirm Deletion',
                    text: 'Are you sure you want to delete ALL gerai invoices for "KPBIV-' + parentInvoiceNo + '"? This will delete all sub-invoices.',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, delete it!',
                    cancelButtonText: 'Cancel',
                    customClass: {
                        confirmButton: 'btn btn-danger',
                        cancelButton: 'btn btn-secondary'
                    }
                }).then(function (result) {
                    if (result.isConfirmed) {
                        $.ajax({
                            type: "DELETE",
                            url: "{{ url('admin/gerai') }}/" + geraiId,
                            dataType: 'json',
                            success: function (res) {
                                Swal.fire({
                                    title: 'Deleted!',
                                    text: res.message,
                                    icon: res['alert-type'],
                                    customClass: {
                                        confirmButton: 'btn btn-success'
                                    }
                                }).then(function() {
                                    // Redirect to gerai index
                                    window.location.href = "{{ route('admin.gerai.index') }}";
                                });
                            },
                            error: function (xhr) {
                                var errorMessage = 'An error occurred';
                                if (xhr.responseJSON && xhr.responseJSON.message) {
                                    errorMessage = xhr.responseJSON.message;
                                }
                                Swal.fire({
                                    title: 'Error!',
                                    text: errorMessage,
                                    icon: 'error',
                                    customClass: {
                                        confirmButton: 'btn btn-danger'
                                    }
                                });
                            }
                        });
                    }
                });
            });
        });
    </script>
</x-slot>
</x-app-layout>


