<section class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h3>Soal UTS SI-B 2025</h3>
            </div>
        </div>
    </div>
</section>

<section class="content">
    <div class="container-fluid">
        <div class="card card-primary">
            <div class="card-body">

                <!-- Filter -->
                <div class="row mb-3">
                    <div class="col-md-3">
                        <label>Mulai Tanggal</label>
                        <input type="date" id="tglmulai" class="form-control">
                    </div>
                    <div class="col-md-3">
                        <label>Sampai Tanggal</label>
                        <input type="date" id="tglsampai" class="form-control">
                    </div>
                    <div class="col-md-3">
                        <label>Metode Pembayaran</label>
                        <select class="form-control" id="cbometode">
                            <option value="">Semua Metode</option>
                        </select>
                    </div>
                    <div class="col-md-3 d-flex align-items-end">
                        <button class="btn btn-primary w-100" id="btnCari">
                            <i class="fas fa-search"></i> Cari Data
                        </button>
                    </div>
                </div>

                <!-- Tabel -->
                <table id="dtx" class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Tanggal</th>
                            <th>Pelanggan</th>
                            <th>Produk</th>
                            <th>Kategori</th>
                            <th>Jumlah</th>
                            <th>Harga Satuan</th>
                            <th>Total</th>
                            <th>Status</th>
                            <th>Metode</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>

                <!-- Grafik Donut -->
                <div class="mt-4">
                    <h5 class="text-center mb-3">Grafik Penjualan per 2 Bulan</h5>
                    <div id="grafikDonut" style="height: 400px;"></div>
                </div>

            </div>
        </div>
    </div>
</section>

<!-- Highcharts -->
<script src="assets/plugins/highcharts/highcharts.js"></script>
<script src="assets/plugins/highcharts/highcharts-more.js"></script>
<script src="assets/plugins/highcharts/modules/exporting.js"></script>
<script src="assets/plugins/highcharts/modules/accessibility.js"></script>


<script>
$("#mndata").addClass("active");

$(document).ready(function () {
    // === Inisialisasi DataTable ===
    let tabelku = $("#dtx").DataTable({
        ajax: {
            // 🔹 ubah ke sumber data online
            url: "https://drive.crazycode.my.id/datajson/transaksi2024",
            dataSrc: ""
        },
        columns: [
            { data: "id" },
            { data: "tanggal" },
            { data: "pelanggan" },
            { data: "produk" },
            { data: "kategori" },
            { data: "jumlah" },
            { data: "harga_satuan" },
            { data: "total" },
            { data: "status" },
            { data: "metode" },
        ],
        responsive: true,
        language: {
            emptyTable: "Tidak ada data yang ditemukan",
        },
    });

    // === Ambil metode pembayaran (online) ===
    $.getJSON("https://drive.crazycode.my.id/datajson/transaksi2024", function (result) {
        let dt = "<option value=''>Semua Metode</option>";
        let metodeList = [];
        $.each(result, function (i, kolom) {
            if (!metodeList.includes(kolom.metode)) {
                metodeList.push(kolom.metode);
                dt += `<option value='${kolom.metode}'>${kolom.metode}</option>`;
            }
        });
        $("#cbometode").html(dt);
    });

    // === Inisialisasi Grafik Donut ===
    const chart = Highcharts.chart("grafikDonut", {
        chart: {
            type: "pie",
            backgroundColor: "transparent",
            custom: {},
            events: {
                render() {
                    const chart = this,
                        series = chart.series[0];
                    let customLabel = chart.options.chart.custom.label;

                    if (!customLabel) {
                        customLabel = chart.options.chart.custom.label = chart.renderer
                            .label("Total<br/><b>0 Data</b>")
                            .css({
                                color: "#000",
                                textAnchor: "middle",
                                fontWeight: "bold",
                            })
                            .add();
                    }

                    const x = series.center[0] + chart.plotLeft,
                        y = series.center[1] + chart.plotTop - customLabel.attr("height") / 2;

                    customLabel.attr({ x, y });
                    customLabel.css({ fontSize: `${series.center[2] / 12}px` });
                },
            },
        },
        title: { text: undefined },
        credits: { enabled: false },
        exporting: { enabled: false },
        tooltip: {
            pointFormat: "{point.name}: <b>{point.percentage:.1f}%</b><br/>Total: <b>{point.y}</b>",
        },
        legend: { enabled: false },
        plotOptions: {
            pie: {
                innerSize: "75%",
                borderRadius: 8,
                allowPointSelect: true,
                cursor: "pointer",
                dataLabels: [
                    { enabled: true, distance: 20, format: "{point.name}" },
                    { enabled: true, distance: -20, format: "{point.percentage:.0f}%" },
                ],
            },
        },
        series: [{ name: "Total Penjualan", colorByPoint: true, data: [] }],
    });

    // === Fungsi Update Chart ===
    function updateChart(data) {
        const monthMap = {
            "Jan-Feb": 0, "Mar-Apr": 0, "Mei-Jun": 0,
            "Jul-Agu": 0, "Sep-Okt": 0, "Nov-Des": 0,
        };

        data.forEach((item) => {
            const month = new Date(item.tanggal).getMonth() + 1;
            if (month <= 2) monthMap["Jan-Feb"]++;
            else if (month <= 4) monthMap["Mar-Apr"]++;
            else if (month <= 6) monthMap["Mei-Jun"]++;
            else if (month <= 8) monthMap["Jul-Agu"]++;
            else if (month <= 10) monthMap["Sep-Okt"]++;
            else monthMap["Nov-Des"]++;
        });

        const chartData = Object.entries(monthMap)
            .filter(([_, val]) => val > 0)
            .map(([key, val]) => ({ name: key, y: val }));

        chart.series[0].setData(chartData);

        const totalEntries = data.length;
        if (chart.options.chart.custom.label) {
            chart.options.chart.custom.label.attr({
                text: `Total<br/><b>${totalEntries} Data</b>`,
            });
        }
    }

    // === Load data awal dari server online ===
    $.getJSON("https://drive.crazycode.my.id/datajson/transaksi2024", function (result) {
        updateChart(result);
    });

    // === Tombol Cari Data ===
    $("#btnCari").on("click", function () {
        const metode = $("#cbometode").val();
        const tglMulai = $("#tglmulai").val();
        const tglSampai = $("#tglsampai").val();

        if (tglMulai === "" || tglSampai === "") {
            Swal.fire({
                toast: true,
                position: "top",
                icon: "warning",
                title: "Isi tanggal mulai dan sampai terlebih dahulu!",
                showConfirmButton: false,
                timer: 2500,
            });
            return;
        }

        $.getJSON("https://drive.crazycode.my.id/datajson/transaksi2024", function (result) {
            const filtered = result.filter(function (item) {
                const tgl = new Date(item.tanggal);
                const mulai = new Date(tglMulai);
                const sampai = new Date(tglSampai);
                const cocokMetode = metode ? item.metode === metode : true;
                return cocokMetode && tgl >= mulai && tgl <= sampai;
            });

            tabelku.clear().rows.add(filtered).draw();
            updateChart(filtered);
        });
    });
});

</script>