<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Data Billing Kasir All/Total</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0"></script>
    
    <style>
        /* --- CSS TAMPILAN --- */
        .summary-table-container {
            border: 1px solid #dee2e6;
            border-radius: .25rem;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, .075);
        }

        .summary-table-container table { margin-bottom: 0; }
        
        .summary-table-container thead th {
            position: sticky;
            top: 0;
            background-color: #f8f9fa;
            z-index: 1;
        }

        .summary-table-container .table-title th {
            font-size: 1rem;
            border-bottom: 1px solid #ccc !important;
        }

        .summary-table-container .table td,
        .summary-table-container .table th {
            padding: 0.5rem 1.25rem;
            font-size: 0.875rem;
        }

        .summary-table-container .bank-name-column {
            width: 70%; 
            border-right: 1px solid #dee2e6; 
        }
        
        /* CSS TOTAL PENDAPATAN */
        .total-pendapatan-box {
            background: linear-gradient(45deg, #007bff, #0056b3);
            color: white;
            border-radius: 8px;
            padding: 20px;
            margin-top: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            text-align: center;
        }
        .total-pendapatan-title {
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 5px;
            opacity: 0.9;
            font-weight: 600;
        }
        .total-pendapatan-value {
            font-size: 1.8rem;
            font-weight: bold;
            margin: 0;
        }

        #downloadButton { margin-left: 10px; }

        /* --- CSS CHART --- */
        .chart-section {
            margin-top: 30px;
            margin-bottom: 30px;
            padding: 20px;
            background-color: #fff;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }

        .chart-container {
            position: relative; 
            height: 500px; 
            width: 100%; 
        }

        @media (max-width: 768px) {
            .form-group { margin-bottom: 10px; }
            .chart-container { height: 350px; } 
        }
    </style>
</head>

<body>
    <div id="layoutSidenav_content">
        <main>
            <div class="container-fluid px-4">
                <h1 class="mt-4" id="judulPasien">Data Billing Kasir All</h1>
                <ol class="breadcrumb mb-4">
                    <li class="breadcrumb-item"><a href="#">Dashboard</a></li>
                    <li class="breadcrumb-item active">Tampilkan Data Billing Kasir Total</li>
                </ol>

                <div class="row mb-4 align-items-start">
                    <div class="col-lg-5">
                        <div class="card h-100">
                            <div class="card-body">
                                <form id="filterForm">
                                    <div class="row">
                                        <div class="col-md-9 form-group">
                                            <label for="tanggal_awal" class="mb-1">Tanggal Awal</label>
                                            <input type="date" id="tanggal_awal" name="tanggal_awal" class="form-control" value="<?= $tgl_awal ?? '' ?>" required />
                                        </div>
                                        <div class="col-md-9 form-group">
                                            <label for="tanggal_akhir" class="mb-1">Tanggal Akhir</label>
                                            <input type="date" id="tanggal_akhir" name="tanggal_akhir" class="form-control" value="<?= $tgl_akhir ?? '' ?>" required />
                                        </div>
                                    </div>
                                    <div class="row mt-2">
                                        <div class="col-12 text-left">
                                            <button type="submit" class="btn btn-primary">Filter</button>
                                            <button id="downloadButton" type="button" class="btn btn-success" style="display: none;">Download Excel</button>
                                        </div>
                                    </div>
                                    
                                    <div id="totalPendapatanContainer">
                                        <div class="total-pendapatan-box">
                                            <div class="total-pendapatan-title">TOTAL PENDAPATAN</div>
                                            <div class="total-pendapatan-value" id="totalPendapatanValue">Rp 0</div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-lg-7">
                        <div id="summaryContainer" style="display: none;">
                            </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-12">
                        <div id="chartWrapper" class="chart-section" style="display: none;">
                            <h4 class="text-center font-weight-bold mb-4">Grafik Pendapatan per Bank</h4>
                            <div class="chart-container">
                                <canvas id="myBarChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>

                <div id="result">
                    <div id="loadingIcon" style="display: none; text-align: center; margin-top: 20px;">
                        <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." />
                    </div>
                    <div class="table-responsive mt-4" id="tableContainer" style="display: none;">
                        </div>
                </div>

            </div>
        </main>
        <footer class="py-4 bg-light mt-auto">
            <div class="container-fluid px-4">
                <div class="d-flex align-items-center justify-content-between small">
                    <div class="text-muted">Copyright &copy; By IT RSU Ananda Purwokerto 2024</div>
                    <div>
                        <a href="#">Privacy Policy</a>
                        &middot;
                        <a href="#">Terms &amp; Conditions</a>
                    </div>
                </div>
            </div>
        </footer>
    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
        // Registrasi plugin
        Chart.register(ChartDataLabels);
        
        let myChartInstance = null;

        $(document).ready(function() {
            $('#filterForm').on('submit', function(event) {
                event.preventDefault();
                $('#loadingIcon').show();
                $('#tableContainer').hide();
                $('#summaryContainer').hide();
                $('#chartWrapper').hide(); 
                $('#totalPendapatanValue').text('Loading...'); 

                // 1. AJAX GRAND TOTAL
                $.ajax({
                    url: '<?= base_url("kasirall/datakasirtotalpendapatan") ?>',
                    type: 'POST',
                    data: {
                        TANGGAL_AWAL: $('#tanggal_awal').val(),
                        TANGGAL_AKHIR: $('#tanggal_akhir').val()
                    },
                    dataType: 'json',
                    success: function(response) {
                        let totalValue = 0;
                        if (response.response && Array.isArray(response.response) && response.response.length > 0) {
                            if (response.response[0].sum !== undefined) {
                                totalValue = response.response[0].sum;
                            } else {
                                totalValue = response.response[0].total || 0;
                            }
                        } else if (response.sum !== undefined) {
                            totalValue = response.sum;
                        } else if (response.total !== undefined) {
                            totalValue = response.total;
                        } else if (!isNaN(response)) {
                            totalValue = response;
                        }

                        const grandTotalFormatted = (parseFloat(totalValue) || 0).toLocaleString('id-ID', {
                            style: 'currency', currency: 'IDR', minimumFractionDigits: 0
                        });
                        $('#totalPendapatanValue').text(grandTotalFormatted);
                    },
                    error: function() { $('#totalPendapatanValue').text('Error'); }
                });

                // 2. AJAX DATA UTAMA
                $.ajax({
                    url: '<?= base_url("kasirall/datakasirall") ?>',
                    type: 'POST',
                    data: {
                        TANGGAL_AWAL: $('#tanggal_awal').val(),
                        TANGGAL_AKHIR: $('#tanggal_akhir').val()
                    },
                    dataType: 'json',
                    success: function(data) {
                        $('#loadingIcon').hide();

                        if (data.status === 'error') {
                            Swal.fire('Error', data.message, 'error');
                            return;
                        }

                        // --- RENDER TABLE SUMMARY ---
                        if (data.summary && data.summary.length > 0) {
                            let summaryHtml = '<div class="summary-table-container">' +
                                '<table class="table table-sm table-hover">' +
                                '<thead><tr><th class="bank-name-column">Nama Bank</th><th class="text-right">Total</th></tr></thead><tbody>';

                            let labels = [];
                            let values = [];
                            let colors = [
                                '#4e73df', '#1cc88a', '#36b9cc', '#f6c23e', '#e74a3b', 
                                '#858796', '#5a5c69', '#fd7e14', '#20c997', '#6f42c1',
                                '#007bff', '#6610f2', '#e83e8c', '#dc3545'
                            ];

                            data.summary.forEach(item => {
                                const totalNum = parseFloat(item.sum) || 0;
                                const totalStr = totalNum.toLocaleString('id-ID', {
                                    style: 'currency', currency: 'IDR', minimumFractionDigits: 0
                                });
                                labels.push(item.nm_bank);
                                values.push(totalNum);
                                summaryHtml += `<tr><td class="bank-name-column"><strong>${item.nm_bank}</strong></td><td class="text-right">${totalStr}</td></tr>`;
                            });

                            summaryHtml += '</tbody></table></div>';
                            $('#summaryContainer').html(summaryHtml).show();

                            // --- RENDER CHART BAR ---
                            $('#chartWrapper').fadeIn(1000);

                            if (myChartInstance) { myChartInstance.destroy(); }

                            var ctx = document.getElementById("myBarChart").getContext('2d');
                            myChartInstance = new Chart(ctx, {
                                type: 'bar', // UBAH JADI BAR
                                data: {
                                    labels: labels, // Label Bank otomatis jadi sumbu X
                                    datasets: [{
                                        label: 'Total Pendapatan',
                                        data: values,
                                        backgroundColor: colors.slice(0, labels.length),
                                        borderColor: colors.slice(0, labels.length),
                                        borderWidth: 1
                                    }],
                                },
                                options: {
                                    responsive: true,
                                    maintainAspectRatio: false,
                                    layout: {
                                        padding: {
                                            top: 30 
                                        }
                                    },
                                    scales: {
                                        y: {
                                            beginAtZero: true,
                                            ticks: {
                                                callback: function(value) {
                                                   
                                                    if (value >= 1000000) return 'Rp ' + (value/1000000).toFixed(1) + ' Jt';
                                                    if (value >= 1000) return 'Rp ' + (value/1000).toFixed(0) + ' Rb';
                                                    return value;
                                                }
                                            }
                                        },
                                        x: {
                                            ticks: {
                                                autoSkip: false, // Jangan skip label kalau banyak
                                                maxRotation: 45, // Miringkan teks jika sempit
                                                minRotation: 0
                                            }
                                        }
                                    },
                                    plugins: {
                                        legend: {
                                            display: false // 
                                        },
                                        datalabels: {
                                            anchor: 'end', 
                                            align: 'top',  
                                            color: '#333',
                                            font: {
                                                weight: 'bold',
                                                size: 11
                                            },
                                            formatter: function(value) {
                                                
                                                return value.toLocaleString('id-ID', {
                                                    style: 'currency', 
                                                    currency: 'IDR', 
                                                    minimumFractionDigits: 0
                                                });
                                            }
                                        },
                                        tooltip: {
                                            callbacks: {
                                                label: function(context) {
                                                    let label = context.dataset.label || '';
                                                    if (label) { label += ': '; }
                                                    if (context.parsed.y !== null) {
                                                        label += context.parsed.y.toLocaleString('id-ID', {
                                                            style: 'currency', currency: 'IDR', minimumFractionDigits: 0
                                                        });
                                                    }
                                                    return label;
                                                }
                                            }
                                        }
                                    }
                                }
                            });
                        }

                        // --- RENDER TABLE DETAIL ---
                        if (data.response && data.response.length > 0) {
                            const list = data.response;
                            if ($.fn.DataTable.isDataTable('#datatablesSimple')) {
                                $('#datatablesSimple').DataTable().destroy();
                            }

                            let html = '<table id="datatablesSimple" class="table table-striped table-bordered" style="width:100%"><thead><tr><th>KD Bayar</th><th>No Bayar</th><th>Kd Regist</th><th>Tgl Bayar</th><th>Pencatat</th><th>Jumlah</th><th>Selisih</th><th>Biaya Transaksi</th><th>Keterangan</th></tr></thead><tbody>';
                            list.forEach(item => {
                                const jumlahFormatted = (parseFloat(item.jumlah) || 0).toLocaleString('id-ID');
                                html += `<tr>
                                    <td>${item.kd_bayar}</td>
                                    <td>${item.no_bayar}</td>
                                    <td>${item.kd_registrasi}</td>
                                    <td>${item.tgl_bayar}</td>
                                    <td>${item.pencatat}</td>
                                    <td class="text-right">${jumlahFormatted}</td>
                                    <td>${item.selisih}</td>
                                    <td>${item.biaya_transaksi}</td>
                                    <td>${item.keterangan}</td>
                                </tr>`;
                            });
                            html += '</tbody></table>';
                            $('#tableContainer').html(html).show();

                            $('#datatablesSimple').DataTable({
                                responsive: true,
                                "order": [[ 0, "desc" ]]
                            });
                            $('#downloadButton').show();
                        } else {
                            $('#tableContainer').html('<div class="alert alert-warning text-center">Tidak ada data billing yang ditemukan.</div>').show();
                            $('#downloadButton').hide();
                        }
                    },
                    error: function() {
                        $('#loadingIcon').hide();
                        Swal.fire('Oops...', 'Terjadi kesalahan server.', 'error');
                    }
                });
            });

            $('#downloadButton').on('click', function() {
                const tanggalAwal = $('#tanggal_awal').val();
                const tanggalAkhir = $('#tanggal_akhir').val();
                window.location.href = `<?= base_url("kasirall/unduhdatakasirall") ?>?TANGGAL_AWAL=${tanggalAwal}&TANGGAL_AKHIR=${tanggalAkhir}`;
            });
        });
    </script>
</body>
</html>