<div class="">
    @if ($invoiceNo)
        <livewire:report.modaldetail :datadetail="$datadetail" />
    @endif
    <div class="card-body">
        <div class="form-group row">
            <div class="col-md-3" x-data="dateRange()">
                <label for="startDate">Start Date</label>
                <input type="date" class="form-control" id="startDate" x-bind:min="minDate"
                    x-bind:max="maxDate" wire:model="startDate" style="border-radius: 1rem">
            </div>
            <div class="col-md-3">
                <label for="endDate">End Date</label>
                <input type="date" class="form-control" id="endDate" wire:model="endDate" style="border-radius: 1rem" disabled>
            </div>
            <div x-data="{ open: false, allChecked: false }" class="col-md-2" @click.away="open = false">
                <label for="typeCardCode">Customer</label>

                <button class="form-control" style="border-radius: 1rem" x-on:click="open = ! open"
                    x-text="(allChecked ? 'All Selected' : 'Select Customer')">
                    Select Card Code
                </button>
                <div x-show.important="open" x-transition class="form-control dropdown-menu d-block py-0 w-auto px-2">
                    <div class="mt-2 ms-2 mb-2">
                        <input type="checkbox" id="selectAll" name="selectAll" x-model="allChecked"
                            wire:model="selectAll">
                        <label for="selectAllCheckbox" class="ms-2">Select All</label>
                    </div>
                    @foreach ($cardcode as $index => $crdcd)
                        <div class="ms-4">
                            <input x-bind:checked="allChecked" x-bind:hidden="allChecked" type="checkbox"
                                id="checkbox{{ $index + 1 }}" name="checkbox{{ $index + 1 }}"
                                wire:model="checkboxes.{{ $crdcd->code }}"
                                x-on:change="updateCheckboxes('{{ $crdcd->code }}')">
                            <label x-bind:hidden="allChecked" class="ms-2"
                                for="checkbox{{ $index + 1 }}">{{ $crdcd->name }} - ({{ $crdcd->code }})</label>
                        </div>
                    @endforeach
                </div>

            </div>
            <div class="col-md-2">
                <label for="typeInvoice">Type Invoice</label>
                <select class="form-control" wire:model="type" id="type" style="border-radius: 1rem"
                    wire:click="selectType">
                    <option value="All">All</option>
                    <option value="BJ">Sale</option>
                    <option value="RS">Return Sale</option>
                </select>
            </div>

            <div class="col-md-2 mt-4">
                @if ($selectedType)
                    <button type="button" id="filterBtn" wire:click="filterInvoices"
                        class="custom-button1 mb-2">Filter</button>
                    <button type="button" id="clearBtn" wire:click="clearFilter" class="button-custom-danger mb-2"
                        @if (!$isFilter) disabled @endif>Clear
                        Filter</button>
                @else
                    <button type="button" id="filterBtn" wire:click="filterInvoices" class="custom-button1 mb-2"
                        disabled>Filter</button>
                    <button type="button" id="clearBtn" wire:click="clearFilter" class="button-custom-danger mb-2"
                        disabled>Clear Filter</button>
                @endif

            </div>

        </div>

        <div class="col-md-5 mt-3 mb-3">
            <button type="button" wire:click="exportExcel" class="custom-button1 mb-2">Export Excel</button>
            <button type="button" wire:click="exportARInvoiceDetail" class="custom-button1 mb-2">Export AR</button>
            <button type="button" wire:click="exportARItemDetail" class="custom-button1 mb-2">Export AR
                Detail</button>
            @if ($loadingsap)
                <button type="button"class="custom-button1 mb-2" disabled>
                    <span id="loadingSpinner2" class="spinner-border spinner-border-sm" role="status"
                        aria-hidden="true"></span>
                    <span id="innerSpan">Loading . . .</span>
                </button>
            @else
                <button type="button" data-bs-toggle="modal" data-bs-target="#modalGetSAP"
                    class="custom-button1 mb-2">Get SAP</button>
            @endif

            @if ($syncount >= 1)
                <button type="button" data-bs-toggle="modal" data-bs-target="#modalSyncAll"
                    class="custom-button1 mb-2">Sync All</button>
            @else
                <button type="button" class="custom-button1 mb-2" disabled>Sync All</button>
            @endif
        </div>
        <table>
            <thead>
                <tr></tr>
            </thead>
            <tbody>
                <td></td>
            </tbody>
        </table>
        <div wire:ignore.self>
            <div class="table-responsive">
                <table id="example" class="my-table mt-2" style="width:100%">
                    <thead>
                        <tr>
                            <th style="border-top-left-radius: 1rem">Invoice</th>
                            <th>Tanggal</th>
                            <th>Jam</th>
                            <th>User</th>
                            <th>Staff</th>
                            <th>Qty</th>
                            <th>Sub Total</th>
                            <th>Discount</th>
                            <th>Cashback</th>
                            <th>Grand Total</th>
                            <th>Cash</th>
                            <th>Card</th>
                            <th>Sync</th>
                            <th style="border-top-right-radius: 1rem">#</th>
                        </tr>
                    </thead>
                    <tbody>
                        @php
                            $totalCash = 0;
                            $totalTransfer = 0;
                            $totalSubtotalQrisCash = 0;
                            $totalSubtotalCard = 0;
                        @endphp

                        @foreach ($invoices as $invoice)
                            <tr>
                                <td><button data-bs-toggle="modal" data-bs-target="#exampleModal{{ $invoice->no }}"
                                        class="badge invoice-color border-white">{{ $invoice->no }}</button></td>
                                <td>{{ \Carbon\Carbon::parse($invoice->created_at)->format('d/m/y') }}</td>
                                <td>{{ \Carbon\Carbon::parse($invoice->created_at)->format('H:i') }}</td>
                                <td>{{ $invoice->users_name }}</td>
                                <td>{{ $invoice->sales_name }}</td>
                                <td>{{ $invoice->total_qty }}</td>
                                {{-- <td>Rp. {{ number_format(($invoice->subtotal ?? 0) < 0 ? 0 : $invoice->subtotal ?? 0, 0, ',', '.') }}</td> --}}
                                <td>Rp. {{ number_format($invoice->subtotal ?? 0, 0, ',', '.') }}</td>
                                <td>Rp. {{ number_format($invoice->disc_total, 0, ',', '.') }}</td>
                                @if ($invoice->cashback !== 'N')
                                    <td>Rp. {{ number_format($invoice->value, 0, ',', '.') }}</td>
                                @else
                                    <td>Rp. 0</td>
                                @endif
                                <td>Rp. {{ number_format($invoice->grandtotal, 0, ',', '.') }}</td>

                                @if ($invoice->payment === 'Multi')
                                    @php
                                        $totalCash += $invoice->cash;
                                        $totalSubtotalCard += $invoice->transfer;
                                    @endphp
                                    <td>Rp. {{ number_format($invoice->cash, 0, ',', '.') }}</td>
                                    <td>Rp. {{ number_format($invoice->transfer, 0, ',', '.') }}</td>
                                @elseif ($invoice->payment === 'Cash')
                                    @php
                                        $totalCash += $invoice->grandtotal;
                                    @endphp
                                    <td>Rp. {{ number_format($invoice->grandtotal, 0, ',', '.') }}</td>
                                    <td>Rp. 0</td>
                                @elseif ($invoice->payment === 'Qris')
                                    @php
                                        $totalSubtotalCard += $invoice->grandtotal;
                                    @endphp
                                    <td>Rp. 0</td>
                                    <td>Rp. {{ number_format($invoice->grandtotal, 0, ',', '.') }}</td>
                                @elseif ($invoice->payment === 'Card')
                                    @php
                                        $totalSubtotalCard += $invoice->grandtotal;
                                    @endphp
                                    <td>Rp. 0</td>
                                    <td>Rp. {{ number_format($invoice->grandtotal, 0, ',', '.') }}</td>
                                @else
                                    <td>Rp. 0</td>
                                    <td>Rp. 0</td>
                                @endif


                                <td>
                                    @if ($invoice->sync == 'N')
                                        <button class="button-custom-danger badge" data-bs-toggle="modal"
                                            data-bs-target="#modalSync{{ $invoice->no }}">Not Sync</button>
                                    @else
                                        <button class="button-custom-success badge">Sync</button>
                                    @endif
                                </td>
                                <td>
                                    <button class="custom-button1 badge" data-bs-toggle="modal"
                                        data-bs-target="#modalPrint{{ $invoice->no }}">Print</button>
                                </td>
                            </tr>

                            <div class="modal fade" id="modalPrint{{ $invoice->no }}" tabindex="-1"
                                aria-labelledby="modalPrintLabel" aria-hidden="true">
                                <div class="modal-dialog modal-dialog-centered">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title" id="modalPrintLabel">Print Invoice</h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal"
                                                aria-label="Close"></button>
                                        </div>
                                        <div class="modal-body">
                                            <p>Are you sure want Print Receipt <span class="fw-bold">
                                                    {{ $invoice->no }}
                                                </span> ?</p>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="button-custom-danger"
                                                data-bs-dismiss="modal">Close</button>
                                            {{-- @if ($invoice->no_inv == null)
                                                <button type="button" class="custom-button1" data-bs-dismiss="modal"
                                                    wire:click="print('{{ $invoice->no }}')">Print</button>
                                            @else --}}
                                                {{-- mz --}}
                                                {{-- @if ($invoice->subtotal <= 0)
                                                    <button type="button" class="custom-button1"
                                                        data-bs-dismiss="modal"
                                                        wire:click="printreturn('{{ $invoice->no }}')"
                                                        wire:loading.attr="disabled">Print</button>
                                                @else
                                                    <button type="button" class="custom-button1"
                                                        data-bs-dismiss="modal"
                                                        wire:click="printreturnwithmoney('{{ $invoice->no }}')"
                                                        wire:loading.attr="disabled">Print</button>
                                                @endif
                                            @endif --}}
                                            <button type="button" wire:click="toPrint('{{ $invoice->no }}')"
                                                class="btn btn-primary" data-bs-dismiss="modal">
                                                Print</button>
                                            
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div wire:ignore.self class="modal fade" id="modalSync{{ $invoice->no }}"
                                tabindex="-1" aria-labelledby="modalSyncLabel" aria-hidden="true"
                                data-bs-backdrop="static">
                                <div class="modal-dialog modal-dialog-centered">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title" id="modalSyncLabel">Sync Invoice</h5>
                                        </div>
                                        <div class="modal-body">
                                            <p>Are you sure want Sync the Receipt <span class="fw-bold">
                                                    {{ $invoice->no }} </span> ?</p>
                                        </div>
                                        <div class="modal-footer">
                                            @if ($isloadingsync || $isloadingreturn)
                                                <button type="button" id="closeSync" class="button-custom-danger"
                                                    data-bs-dismiss="modal" disabled>Close</button>
                                            @else
                                                <button type="button" id="closeSync" class="button-custom-danger"
                                                    data-bs-dismiss="modal">Close</button>
                                            @endif
                                            @if ($invoice->no_inv == null)
                                                @if ($isloadingsync && !$isloadingreturn)
                                                    <button type="button" id="syncButton" class="custom-button1"
                                                        disabled>
                                                        <span id="loadingSpinner2"
                                                            class="spinner-border spinner-border-sm" role="status"
                                                            aria-hidden="true"></span>
                                                        <span id="innerSpan">Loading . . .</span>
                                                    </button>
                                                @else
                                                    <button type="button" id="syncButton" class="custom-button1"
                                                        wire:click="clickSync('{{ $invoice->no }}')">Sync</button>
                                                @endif
                                            @else
                                                @if ($isloadingreturn && !$isloadingsync)
                                                    <button type="button" id="syncButton" class="custom-button1"
                                                        disabled>
                                                        <span id="loadingSpinner2"
                                                            class="spinner-border spinner-border-sm" role="status"
                                                            aria-hidden="true"></span>
                                                        <span id="innerSpan">Loading . . .</span>
                                                    </button>
                                                @else
                                                    <button type="button" id="syncButton" class="custom-button1"
                                                        wire:click="clickSyncReturn('{{ $invoice->no }}')">Sync</button>
                                                @endif
                                            @endif
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- Modal -->
                            <div class="modal fade" id="exampleModal{{ $invoice->no }}" tabindex="-1"
                                aria-labelledby="exampleModalLabel" aria-hidden="true">
                                <div class="modal-dialog modal-dialog-centered">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title" id="exampleModalLabel">INVOICE</h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal"
                                                aria-label="Close"></button>
                                        </div>
                                        <div class="modal-body text-center">
                                            {{ $invoice->no }}
                                        </div>
                                        <div class="modal-footer">
                                            <button class="mx-2 button-custom-success" data-bs-dismiss="modal"
                                                @if ($invoice->no_inv) wire:click="exportreturnExcelDetail('{{ $invoice->no }}')"
                                    @else
                                        wire:click="exportExcelDetail('{{ $invoice->no }}')" @endif>
                                                Export
                                            </button>
                                            <button type="button" class="custom-button1" data-bs-dismiss="modal"
                                                wire:click="dispatchToDetail('{{ $invoice->no }}')">Check</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    </tbody>
                </table>
            </div>

        </div>

        <div wire:ignore.self>
            <div class="table-responsive">
                <table id="example" class="table mt-2" style="width:100%">
                    <thead>
                        <tr>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th>Total Struk</th>
                            <th>Qty</th>
                            <th>Cash</th>
                            <th>Card</th>
                            <th>Sub Total</th>
                            <th>Discount</th>
                            <th>Cashback</th>
                            <th>Grand Total</th>
                            <th>Return Sale</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td colspan="5">Total</td>
                            <td></td>
                            <td>{{ $invoices->count() }}</td>
                            <td>{{ $invoices->sum('total_qty') }}</td>
                            <td>Rp. {{ number_format($totalCash, 0, ',', '.') }}</td>
                            <td>Rp. {{ number_format($totalSubtotalCard, 0, ',', '.') }}</td>
                            <td>Rp. {{ number_format($invoices->sum('subtotal'), 0, ',', '.') }}</td>
                            <td>Rp. {{ number_format($invoices->sum('disc_total'), 0, ',', '.') }}</td>
                            <td>Rp. {{ number_format($invoices->sum('value'), 0, ',', '.') }}</td>
                            <td>Rp. {{ number_format($invoices->sum('grandtotal'), 0, ',', '.') }}</td>
                            <td>Rp. {{ number_format($returnsale->sum('price'), 0, ',', '.') }}</td>
                        </tr>

                    </tbody>
                </table>
            </div>

        </div>
    </div>

    @if ($syncount >= 1)
        <livewire:report.syncall />
    @else
    @endif

    <livewire:report.get-s-a-p />

    <div wire:ignore.self class="modal fade" data-bs-backdrop="static" id="modalNotFound" tabindex="-1"
        aria-labelledby="modalNotFoundLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="staticBackdropLabel">Alert</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    There's no data on certain period. <br>
                    The system will all data
                </div>
                <div class="modal-footer">
                    <button type="button" class="custom-button1" id="okButton" data-bs-dismiss="modal">OK</button>
                </div>
            </div>
        </div>
    </div>
    <div wire:ignore.self class="modal fade" data-bs-backdrop="static" id="noDataToday" tabindex="-1"
        aria-labelledby="noDataTodayLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="staticBackdropLabel">Alert</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center">
                    There's no data available for today. <br> The system will show data from the latest available date.
                </div>
                <div class="modal-footer">
                    <button type="button" class="custom-button1" id="okButton" data-bs-dismiss="modal">OK</button>
                </div>
            </div>
        </div>
    </div>
</div>
{{-- @foreach ($invoices as $invoice)
    <script>
        document.getElementById('invoice-{{ $invoice->no }}').addEventListener('click', function() {
            const data = '{{ $invoice->no }}';
            Livewire.dispatch('getDetailInvoice', {
                data: data
            });
        });
    </script>
@endforeach --}}
@livewireScripts
<script>
    Livewire.on('noDataToday', () => {
        $('#noDataToday').modal('show');
    });

    Livewire.on('dataNotfound', () => {
        $('#modalNotFound').modal('show');
    });
    Livewire.on('syncCompletedBrowser', () => {
        let closeButton = document.getElementById('closeSync');
        if (closeButton) {
            closeButton.click();
        }
    });
    Livewire.on('syncCompletedBrowserAll', () => {
        let closeButton = document.getElementById('closeSyncAll');
        if (closeButton) {
            closeButton.click();
        }
    });

    Livewire.on('refreshBrowser', (params) => {
        window.location.href = '{{ route('report.reportinvoicereturnsale') }}';
    });
    Livewire.on('refreshjs', (params) => {
        $(document).ready(function() {
            $.fn.dataTable.ext.errMode = 'none';
            var table = $('#example').DataTable();

            $(document).keypress(function(e) {
                // Check if the pressed key is '/' (forward slash)
                if (e.which == 47) {
                    e.preventDefault(); // Prevent default action
                    // Focus on the search input field of the DataTable
                    $('.dataTables_filter input').focus();
                }
                // Check if the pressed key is '.' (period) for next page
                else if (e.which == 46) {
                    e.preventDefault(); // Prevent default action
                    table.page('next').draw('page');
                }
                // Check if the pressed key is ',' (comma) for previous page
                else if (e.which == 44) {
                    e.preventDefault(); // Prevent default action
                    table.page('previous').draw('page');
                }
            });
        });
    });

    Livewire.on('downloadFailureTxt', (failureData) => {
        let textContent = '';
        failureData.forEach(item => {
            textContent += JSON.stringify(item) + '\n';
        });

        const currentDate = new Date().toISOString().slice(0, 10); // Get current date in YYYY-MM-DD format
        const filename = `failure_data_${currentDate}.txt`;

        const blob = new Blob([textContent], {
            type: 'text/plain'
        });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        a.click();
        window.URL.revokeObjectURL(url);
    });

    document.addEventListener('livewire:load', function() {
        Livewire.on('refreshjs', (params) => {
            $(document).ready(function() {
                $.fn.dataTable.ext.errMode = 'none';
                new DataTable('#example', {
                    order: [],
                });
            });
        });
    });
    document.addEventListener('livewire:load', function() {
        document.getElementById('syncButton').addEventListener('click', function() {
            this.disabled = true;
            document.getElementById('closeSync').disabled = true; // Disabling closeSync button

        });
    });
    document.getElementById('syncButton').addEventListener('click', function() {
        this.disabled = true;
        document.getElementById('closeSync').disabled = true; // Disabling closeSync button

    });

    document.getElementById('okButton').addEventListener('click', function() {
        document.getElementById('startDate').value = ''; // Clear start date
        document.getElementById('endDate').value = ''; // Clear end date
    });

    Livewire.on('openModal', () => {
        $('#modalDetail').modal('show');
    });
    Livewire.on('closeModalweb', () => {
        $(document).ready(function() {
            $.fn.dataTable.ext.errMode = 'none';
            var table = $('#example').DataTable();

            $(document).keypress(function(e) {
                // Check if the pressed key is '/' (forward slash)
                if (e.which == 47) {
                    e.preventDefault(); // Prevent default action
                    // Focus on the search input field of the DataTable
                    $('.dataTables_filter input').focus();
                }
                // Check if the pressed key is '.' (period) for next page
                else if (e.which == 46) {
                    e.preventDefault(); // Prevent default action
                    table.page('next').draw('page');
                }
                // Check if the pressed key is ',' (comma) for previous page
                else if (e.which == 44) {
                    e.preventDefault(); // Prevent default action
                    table.page('previous').draw('page');
                }
            });
        });

        $('#modalDetail').modal('hide');
    });
    
    function dateRange() {
        let today = new Date();
        let twoDaysAgo = new Date();
        twoDaysAgo.setDate(today.getDate() - 1);

        let formattedToday = today.toISOString().split('T')[0];
        let formattedTwoDaysAgo = twoDaysAgo.toISOString().split('T')[0];

        return {
            startDate: null,
            minDate: formattedTwoDaysAgo,
            maxDate: formattedToday,
        };
    }

    Livewire.on('toPrintBrowser', (params) => {
        var url = '{{ route('report.print', ':params') }}';
        url = url.replace(':params', params);
        window.open(url, '_blank');
    });
</script>
