<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">
                            Gerai Management</h1>
                        {{ Breadcrumbs::render('gerai.index') }}
                    </div>
                    @can('invoice-add')
                    <div class="d-flex align-items-center ml-auto gap-2 gap-lg-3">
                        <x-add-back-button onclick="window.location='{{route('admin.gerai.create')}}'">
                            <i class="ki-duotone ki-plus fs-2"></i>
                            <span class="indicator-label">{{ __('Add Gerai') }}</span>
                        </x-add-back-button>
                    </div>
                    @endcan
                </div>
            </div>
            <div class="app-content flex-column-fluid">
                <div class="app-container  container-xxl ">
                    <div class="pb-0 sm:p-8 bg-white shadow sm:rounded-lg">
                        @livewire('gerai-invoice-table')
                    </div>
                </div>
            </div>
        </div>
    </div>
    <x-slot name="scripts">
        <script>
        $(document).ready(function () {
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            // IMPORTANT: Use event delegation on document or a parent element
            // Because Livewire re-renders the table dynamically
            $(document).on('click', '.delete-gerai', function (e) {
                e.preventDefault(); // Prevent default action
                
                var geraiId = $(this).data('id');
                var parentInvoiceNo = $(this).data('parent');

                console.log('Delete clicked:', { geraiId, parentInvoiceNo }); // Debug log

                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',
                    reverseButtons: true,
                    customClass: {
                        confirmButton: 'btn btn-danger',
                        cancelButton: 'btn btn-secondary'
                    },
                }).then((result) => {
                    if (result.isConfirmed) {
                        var url = '{{ route("admin.gerai.destroy", ":id") }}';
                        url = url.replace(':id', geraiId);
                        
                        $.ajax({
                            url: url,
                            type: 'DELETE',
                            dataType: 'json',
                            success: function(data) {
                                Swal.fire({
                                    title: 'Deleted!',
                                    text: data.message,
                                    icon: data['alert-type'],
                                    customClass: {
                                        confirmButton: 'btn btn-success'
                                    }
                                }).then(function() {
                                    // Refresh Livewire table
                                    window.livewire.emit('refreshTable');
                                    // Or reload page
                                    location.reload();
                                });
                            },
                            error: function(xhr) {
                                var errorMessage = 'An error occurred';
                                if (xhr.responseJSON && xhr.responseJSON.message) {
                                    errorMessage = xhr.responseJSON.message;
                                }
                                Swal.fire({
                                    title: 'Error!',
                                    html: 'Report to admin with the following message <br/>' + errorMessage,
                                    icon: 'error',
                                    customClass: {
                                        confirmButton: 'btn btn-danger'
                                    }
                                });
                            }
                        });
                    }
                });
            });
        });
        </script>
    </x-slot>
</x-app-layout>