@extends('layouts.master')

@section('styles')
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <style>
        .table th {
            text-align: center;
        }
        .table td {
            text-align: right;
        }
    </style>
@endsection

@section('content')
<!-- partial -->
    <div class="container-fluid page-body-wrapper">
        <div class="main-panel">
            <div class="content-wrapper">
                <div class="row">
                    <div class="col-md-12 grid-margin stretch-card">
                        <div class="card">
                            <div class="card-header">
                                <div class="col d-flex align-items-center gap-2">
                                    <div class="col-sm-2">
                                        <input type="date" class="form-control" id="tanggalCari" name="tanggal_mulai" required>
                                    </div>
                                    <p class="mb-0 me-2 ms-auto">Harian</p> 
                                    <label class="toggle-switch toggle-switch-success">
                                            <input type="checkbox" id="harianToggle" checked>
                                        <span class="toggle-slider round" checked></span>
                                    </label>
                                    <div class="me-2">
                                        {{-- <button type="button" class="btn btn-sm btn-primary" data-dismiss="modal">Cetak</button>--}}
                                        <div class="btn-list text-right" style="float: right; display: flex; gap: 10px; margin-bottom: 10px; display: block;">
                                            <button type="button" class="btn btn-icon btn-success btn-export-excel"><i class="fa fa-file-excel-o"></i></button>
                                            <button type="button" class="btn btn-icon btn-danger btn-export-pdf"><i class="fa fa-file-pdf-o"></i></button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="card-body" id="cetak">
                                    <h4 class="card-title">
                                        {{ ($locationSettings->namalokasi) ?? '' }} - {{ ($locationSettings->namaperusahaan) ?? '' }}
                                    </h4>
                                    <h5 class="text-center">
                                        <strong>Rekap Transaksi Kendaraan</strong>
                                        <div class="mx-auto mt-1" id="tanggal-trans"></div>
                                    </h5>
                                    <!-- BARIS TANGGAL & BY -->
                                    <div class="d-flex align-items-center">
                                        <div class="ms-auto mb-1" id="harian"></div>
                                    </div>
                                <div class="table-bordered mb-5">
                                    <table class="table table-striped" id="cash">
                                        <thead>
                                            <tr>
                                                <th rowspan="2" colspan="2">Jenis Kend</th>
                                                <th colspan="2">Jenis Transaksi</th>
                                                <th colspan="2">Casual</th>
                                                <th colspan="2">Tiket Hilang</th>
                                                <th colspan="2">Member</th>
                                                <th colspan="2">Manual Input</th>
                                                <th colspan="2">Manual Mix</th>
                                                <th colspan="2">Tiket Masalah</th>
                                                <th rowspan="2">Pendapatan</th>
                                            </tr>
                                            <tr>
                                                <th>Masuk</th>
                                                <th>Keluar</th>
                                                <th>JML</th>
                                                <th>Nilai</th>
                                                <th>JML</th>
                                                <th>Nilai</th>
                                                <th>JML</th>
                                                <th>Nilai</th>
                                                <th>JML</th>
                                                <th>Nilai</th>
                                                <th>JML</th>
                                                <th>Nilai</th>
                                                <th>JML</th>
                                                <th>Nilai</th>
                                            </tr>
                                        </thead>
                                        <tbody id="table-data">
                                           </tbody>
                                    </table>
                                </div>
                                <div class="row">
                                    <div class="col-md-5">
                                        <h5 class="card-title text-center">Kendaraan yang masih menginap (Over Night)</h5>
                                        <div class="table-bordered">
                                            <table class="table table-on" id="cashless">
                                                <thead>
                                                    <tr>
                                                        <th>Jenis Kend</th>
                                                        <th>Menginap</th>
                                                        <th>ON (Expired)</th>
                                                        <th>Total</th>
                                                    </tr>
                                                </thead>
                                                <tbody id="table-overnight">
                                                   </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                                {{-- <h5 class="card-title text-center">Rekap Transaksi Kendaraan (Non Tunai)</h5>
                                <div class="table-bordered">
                                    <table class="table" id="cashless">
                                        <thead>
                                            <tr>
                                                <th rowspan="2">Jenis Kend</th>
                                                <th colspan="2">Jenis Transaksi</th>
                                                <th colspan="2">Casual</th>
                                                <th colspan="2">Tiket Hilang</th>
                                                <th colspan="2">Member</th>
                                                <th colspan="2">Manual Input</th>
                                                <th colspan="2">Manual Mix</th>
                                                <th colspan="2">Tiket Masalah</th>
                                                <th rowspan="2">Pendapatan</th>
                                            </tr>
                                            <tr>
                                                <th>Masuk</th>
                                                <th>Keluar</th>
                                                <th>JML</th>
                                                <th>Nilai</th>
                                                <th>JML</th>
                                                <th>Nilai</th>
                                                <th>JML</th>
                                                <th>Nilai</th>
                                                <th>JML</th>
                                                <th>Nilai</th>
                                                <th>JML</th>
                                                <th>Nilai</th>
                                                <th>JML</th>
                                                <th>Nilai</th>
                                            </tr>
                                        </thead>
                                        <tbody id="table-data">
                                           </tbody>
                                    </table>
                                </div> --}}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- Modal -->
    <div class="modal fade show" id="modaltanggal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="false">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Pilih Tanggal</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="formTanggal">
                        <div class="form-group">
                            <div class="row">
                                <div class="col-sm-6">
                                    <label for="tanggalMulai">Tanggal pencarian</label>
                                </div>
                                <div class="col-sm-6">
                                    <input type="date" class="form-control" id="tanggalCari" name="tanggal_mulai" required>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
                    <button type="button" class="btn btn-primary" id="btnTampilkan">Tampilkan</button>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('javascript')
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <script>
        $(document).ready(function () {
            // $('#modaltanggal').modal('show');
            
            // Set tanggal default ke hari ini
            // realtime trigger
            $('#tanggalCari').on('change', loadData);
            $('#harianToggle').on('change', loadData);

            
            var today = new Date().toISOString().split('T')[0];
            $('#tanggalCari').val(today);
            loadData();
            
            // $('.btn-export-excel').on('click', function () {
            $(document).on('click', '.btn-export-excel', function (e) {
                // e.preventDefault();
                $('#cash td').each(function () {
                    const raw = $(this).data('value');
                    if (raw !== undefined) {
                        $(this).text(raw);
                    }
                });

                const table = document.getElementById('cetak');
                const wb = XLSX.utils.table_to_book(table, { sheet: 'Sheet 1'});
                XLSX.writeFile(wb, `monthlyReport.xlsx`);
                console.log(e);
            });
            
            $('.btn-export-pdf').on('click', async function () {
                // $('.cetak').css('display','block');
                // $('.user').css('display','block');
                const { jsPDF } = window.jspdf;
                const doc = new jsPDF('l', 'pt', 'a4');
                // ambil elemen tabel
                const table = document.getElementById('cetak');
                const canvas = await html2canvas(table, { scale: 2 });
                const imgData = canvas.toDataURL('image/png');
                const imgWidth = doc.internal.pageSize.getWidth();
                const imgHeight = (canvas.height * imgWidth) / canvas.width;
                doc.addImage(imgData, 'PNG', 0, 20, imgWidth, imgHeight);
                doc.save(`Rekap Harian.pdf`);
            });
            console.log(document.getElementById('cetak'));
            console.log(document.getElementById('date-table'));
        
        });
        function loadData(tanggalMulai, tanggalAkhir) {
            let tanggal = $('#tanggalCari').val();
            let harian  = $('#harianToggle').is(':checked') ? 1 : 0;
            if (harian == 1) 
                $('#harian').text('By : Harian');
            else 
                $('#harian').text('By : Shift');
            // console.log(harian);
            // console.log(tanggal);
            $('#tanggal-trans').text('Tanggal : ' + tanggal);

            if (!tanggal) return;

            // Contoh: Load data dengan AJAX
            $.ajax({
                url: '{{ route("getData") }}', // Ganti dengan route Anda
                type: 'GET',
                data: {
                    tanggal: tanggal,
                    harian: harian
                },
                beforeSend: function () {
                    console.log('Loading data...');
                },
                success: function(response) {
                    // Update tabel dengan data yang diterima

                    let html = '';
                    let onData = '';
                    let jmlCashCasual = 0;
                    let incomeCashCasual = 0;

                    let jmlCashlessCasual = 0;
                    let incomeCashlessCasual = 0;

                    let grandTotal = 0;

                    response.tunai.forEach(function (cash) {

                        // cari pasangan non tunai
                        let cashless = response.nontunai.find(
                            nt => String(nt.id_kendaraan) === String(cash.id_kendaraan)
                        );

                        // fallback aman
                        cashless = cashless || {
                            nontunai: 0,
                            nonTunaiOut: 0,
                            keluar: {
                                casual: { jumlah: 0, income: 0 },
                                lost: { jumlah: 0, income: 0 },
                                member: { jumlah: 0, income: 0 }
                            },
                            totalCashless: 0
                        };

                        let casualIn     = cash.total;
                        let tunaiOut     = cash.tunaiOut;
                        // ===== DATA TUNAI =====
                        let tCasual = cash.keluar.casual;
                        let tLost   = cash.keluar.lost;
                        let tMember = cash.keluar.member;
                        let tManual = cash.keluar.manual;

                        // ===== DATA NON TUNAI =====
                        let nonTunaiOut = cashless.nonTunaiOut;

                        let nCasual = cashless.keluar.casual;
                        let nLost   = cashless.keluar.lost;
                        let nMember = cashless.keluar.member;
                        let nManual = cashless.keluar.manual;

                        let totalTunai    = cash.totalCash || 0;
                        let totalNonTunai = cashless.totalCashless || 0;

                        jmlCashCasual += cash.keluar.casual.jumlah;
                        incomeCashCasual += cash.keluar.casual.income;

                        jmlCashlessCasual += cashless.keluar.casual.jumlah;
                        incomeCashlessCasual += cashless.keluar.casual.income;

                        grandTotal += totalTunai + totalNonTunai;
                        // let casualCash   = cash.keluar.casual;
                        // let lostCash     = cash.keluar.lost;
                        // let memberCash   = cash.keluar.member;
                        // let casualIn     = cash.total;

                        // let casualNon    = cashless ? cashless.keluar.casual : { jumlah: 0, income: 0 };
                        // let lostNon      = cashless ? cashless.keluar.lost   : { jumlah: 0, income: 0 };
                        // let memberNon    = cashless ? cashless.keluar.member : { jumlah: 0, income: 0 };

                        // let totalIncome =
                        //     (cash.totalCash || 0);

                        // html += `
                        // <tr>
                        //     <td style="text-align: left;">${cash.jenis_mobil}</td>

                        //     <!-- Jenis Transaksi -->
                        //     <td>${casualIn}</td>
                        //     <td>${cash.tunaiOut}</td>

                        //     <!-- Casual -->
                        //     <td>${casualCash.jumlah}</td>
                        //     <td>${rupiah(casualCash.income)}</td>

                        //     <!-- Tiket Hilang -->
                        //     <td>${lostCash.jumlah}</td>
                        //     <td>${rupiah(lostCash.income)}</td>

                        //     <!-- Member -->
                        //     <td>${memberCash.jumlah}</td>
                        //     <td>${rupiah(memberCash.income)}</td>

                        //     <!-- Manual Input -->
                        //     <td>0</td>
                        //     <td>0</td>

                        //     <!-- Manual Mix -->
                        //     <td>0</td>
                        //     <td>0</td>

                        //     <!-- Tiket Masalah -->
                        //     <td>0</td>
                        //     <td>0</td>

                        //     <!-- Pendapatan -->
                        //     <td><strong>${rupiah(totalIncome)}</strong></td>
                        // </tr>
                        // `;
                        html += `
                        <tr>
                            <td rowspan="2" style="text-align: left;"><strong>${cash.jenis_mobil}</strong></td>
                            <td style="text-align: left;"><span class="badge bg-success">Tunai</span></td>

                            <td>${casualIn}</td>
                            <td>${tunaiOut}</td>

                            <td>${tCasual.jumlah}</td>
                            <td data-value="${tCasual.income}">${rupiah(tCasual.income)}</td>

                            <td>${tLost.jumlah}</td>
                            <td data-value="${tLost.income}">${rupiah(tLost.income)}</td>

                            <td>${tMember.jumlah}</td>
                            <td data-value="${tMember.income}">${rupiah(tMember.income)}</td>

                            <td>${tManual.jumlah}</td>
                            <td data-value="${tManual.income}">${rupiah(tManual.income)}</td>

                            <td>0</td>
                            <td data-value="0}">0</td>
                            
                            <td>0</td>
                            <td data-value="0">0</td>

                            <td data-value="${totalTunai}"><strong>${rupiah(totalTunai)}</strong></td>
                        </tr>

                        <tr>
                            <td style="text-align: left;"><span class="badge bg-warning">Non Tunai</span></td>

                            <td>${casualIn}</td>
                            <td>${nonTunaiOut}</td>

                            <td>${nCasual.jumlah}</td>
                            <td data-value="${nCasual.income}">${rupiah(nCasual.income)}</td>

                            <td>${nLost.jumlah}</td>
                            <td>${rupiah(nLost.income)}</td>

                            <td>${nMember.jumlah}</td>
                            <td>${rupiah(nMember.income)}</td>

                            <td>${nManual.jumlah}</td>
                            <td data-value="${nManual.income}">${rupiah(nManual.income)}</td>

                            <td>0</td>
                            <td data-value="0">0</td>
                            
                            <td>0</td>
                            <td data-value="0">0</td>

                            <td data-value="${totalNonTunai}"><strong>${rupiah(totalNonTunai)}</strong></td>
                        </tr>
                        `;
                    });

                    // ===== FOOTER TOTAL =====
                    html += `
                    <tr class="table">
                        <td rowspan="2" style="text-align: center;"><strong>TOTAL</strong></td>
                        <td style="text-align: left;"><span class="badge bg-success">Tunai</span></td>
                        <td>0</td>
                        <td>0</td>
                        <td data-value="${jmlCashCasual}">${rupiah(jmlCashCasual)}</td>
                        <td data-value="${incomeCashCasual}">${rupiah(incomeCashCasual)}</td>
                        <td colspan="11">0</td>
                    </tr>
                    <tr>
                        <td style="text-align: left;"><span class="badge bg-warning">NON TUNAI</td>
                         <td>0</td>
                        <td>0</td>
                        <td>${jmlCashlessCasual}</td>
                        <td data-value="${incomeCashlessCasual}">${rupiah(incomeCashlessCasual)}</td>
                        <td colspan="11">0</td>
                    </tr>
                    <tr class="table">
                        <td colspan="3" class="text-center"><strong>GRAND TOTAL</strong></td>
                        <td colspan="0"></td>
                        <td colspan="0">${jmlCashCasual+jmlCashlessCasual}</td>
                        <td colspan="0" data-value="${incomeCashCasual+incomeCashlessCasual}">${rupiah(incomeCashCasual+incomeCashlessCasual)}</td>
                        <td colspan="0"></td>
                        <td colspan="0"></td>
                        <td colspan="0"></td>
                        <td colspan="0"></td>
                        <td colspan="0"></td>
                        <td colspan="0"></td>
                        <td colspan="0"></td>
                        <td colspan="0"></td>
                        <td colspan="0"></td>
                        <td colspan="0"></td>
                        <td><strong>${rupiah(grandTotal)}</strong></td>
                    </tr>
                    `;
                    // console.log('TUNAI:', cash.id_kendaraan, cash);
                    // console.log('CASHLESS FOUND:', cashless);

                    $('#table-data').html(html);

                    response.overNight.forEach(function (on) {
                        if (!on.jenis_mobil) return; 

                        let overnight = on.overNight;
                        let onExpired = on.onExpired;

                        onData += `
                            <tr>
                                <td style="text-align: left;">${on.jenis_mobil}</td>
                                <td>${overnight}</td>
                                <td>${onExpired}</td>
                                <td>0</td>
                            </tr>
                        `;
                    });

                    $('#table-overnight').html(onData);
                    console.log(response);
                },
                error: function(xhr) {
                    console.log('Error:', xhr);
                    alert('Terjadi kesalahan saat memuat data');
                }
            });
        }

        function rupiah(angka) {
            return new Intl.NumberFormat('id-ID').format(angka || 0);
        }
        // }
    </script>
@endsection