        <script>
            function formatNumber(number) {
        return number.toLocaleString('id-ID');
            }
        </script>
        <script>
            document.addEventListener("DOMContentLoaded", function() {
                const flotData = <?= isset($flotData) ? json_encode($flotData) : '[]' ?>;

                // **FlotChart**
                $.plot("#flotChart1", [{
                    data: flotData,
                    lines: {
                        show: true
                    }
                }], {
                    xaxis: {
                        mode: "time",
                        timeformat: "%Y-%m-%d %H:%M"
                    },
                    yaxis: {
                        min: 0
                    },
                    grid: {
                        borderWidth: 1,
                        borderColor: "#ccc"
                    },
                });
            });
        </script>
        <script>
            document.addEventListener("DOMContentLoaded", function() {
                const editAgentIdentifier = document.getElementById("editAgentIdentifier");
                const editAgentName = document.getElementById("editAgentName");
                const editAgentLevel = document.getElementById("editAgentLevel");
                const editAgentBalance = document.getElementById("editAgentBalance");
                const editAgentStatus = document.getElementById("editAgentStatus");

                if (!editAgentIdentifier || !editAgentName || !editAgentLevel || !editAgentBalance || !editAgentStatus) {
                    return;
                }

                document.querySelectorAll(".edit-btn").forEach(button => {
                    button.addEventListener("click", function() {
                        editAgentIdentifier.value = this.dataset.id;
                        editAgentName.value = this.dataset.name;
                        editAgentLevel.value = this.dataset.level;
                        editAgentBalance.value = this.dataset.balance;
                        editAgentStatus.value = this.dataset.status;
                    });
                });
            });
        </script>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            let amountInput = document.getElementById("amount");
            let coinInput = document.getElementById("coin");

            if (!amountInput || !coinInput) {
                return;
            }
    
            fetch("function/get_rate.php")
                .then(response => response.json())
                .then(data => {
                    let rateCoin = parseFloat(data.rate_coin) || 7.5;
    
                    amountInput.addEventListener("input", function() {
                        let amount = parseFloat(amountInput.value) || 0;
                        let coinAmount = rateCoin > 0 ? Math.floor(amount / (rateCoin / 100)) : 0;
                        coinInput.value = coinAmount.toLocaleString();
                    });
    
                    const topupForm = amountInput.closest("form");

                    if (topupForm) {
                        topupForm.addEventListener("submit", function() {
                            coinInput.value = coinInput.value.replace(/,/g, "").replace(/\./g, "");
                        });
                    }
                })
                .catch(error => console.error("Error fetching rate_coin:", error));
        });
    </script>
    <script>
  document.addEventListener("DOMContentLoaded", function () {
    let coinInput = document.getElementById("coinx");
    let amountInput = document.getElementById("amountx");

    if (!coinInput || !amountInput) {
        return;
    }

    fetch("function/get_rate.php")
        .then(response => {
            if (!response.ok) {
                throw new Error("Gagal mengambil rate koin.");
            }
            return response.json();
        })
        .then(data => {
            let rateCoin = parseFloat(data.rate_coin) || 7.5;

            coinInput.addEventListener("input", function () {
                let coinAmount = parseFloat(coinInput.value.replace(/[^\d]/g, "")) || 0;
                let amount = Math.floor(coinAmount * (rateCoin / 100)); 

                amountInput.value = amount.toLocaleString("id-ID", {
                    maximumFractionDigits: 0 
                });
            });

            const balanceForm = coinInput.closest("form");

            if (balanceForm) {
                balanceForm.addEventListener("submit", function () {
                    amountInput.value = amountInput.value.replace(/\./g, "");
                });
            }
        })
        .catch(error => console.error("Error fetching rate_coin:", error));
    });
    </script>
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            let totalAmount = 0;
            let totalHarga = 0;
            let rateCoin = 7.5;
    
            fetch("function/get_rate.php")
                .then(response => response.json())
                .then(data => {
                    rateCoin = parseFloat(data.rate_coin) || 7.5;
    
                    document.querySelectorAll("tbody#topupTable tr").forEach(row => {
                        let amountCell = row.querySelector(".amount");
                        let hargaCell = row.querySelector(".harga");
    
                        if (amountCell && hargaCell) {
                            let amount = parseFloat(amountCell.getAttribute("data-amount")) || 0;
                            let harga = rateCoin > 0 ? Math.floor(amount * (rateCoin / 100)) : 0;
    
                            hargaCell.textContent = harga.toLocaleString();
                            totalAmount += amount;
                            totalHarga += harga;
                        }
                    });
    
                    document.getElementById("totalAmount").value = totalAmount.toLocaleString();
                    document.getElementById("totalHarga").value = totalHarga.toLocaleString();
                })
                .catch(error => console.error("Error fetching rate_coin:", error));
        });
        
    </script>
    <script>
    document.addEventListener("DOMContentLoaded", function () {
        $(".datepicker").datepicker({
            format: "yyyy-mm-dd",
            autoclose: true
        });
    
        document.getElementById("filterButton").addEventListener("click", function () {
            let startDate = document.getElementById("startDate").value;
            let endDate = document.getElementById("endDate").value;
    
            if (!startDate || !endDate) {
                alert("Silakan pilih rentang tanggal terlebih dahulu.");
                return;
            }
    
            fetchTransactions(startDate, endDate);
        });
    
        function fetchTransactions(startDate, endDate) {
            fetch(`function/get_rate.php?start=${startDate}&end=${endDate}`)
                .then(response => response.json())
                .then(data => {
                    document.getElementById("totalAmount").value = (data.total_amount || 0).toLocaleString("id-ID");
                    document.getElementById("totalHarga").value = (data.total_harga || 0).toLocaleString("id-ID");
                })
                .catch(error => console.error("Error fetching transactions:", error));
        }
    });
    </script>
    <script>
document.addEventListener("DOMContentLoaded", async function () {
    let chartInstance = null;
    let areaCanvas = document.getElementById("chartjsArea");

    if (!areaCanvas) {
        console.error("Canvas chartjsArea tidak ditemukan.");
        return;
    }

    async function fetchChartData() {
        try {
            let response = await fetch("function/charts.php");
            let data = await response.json();
            console.log("Data grafik:", data);

            let labels = data.map(row => row.bulan);
            let values = data.map(row => row.jumlah);

            let ctx = areaCanvas.getContext("2d");

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

            const gradient = ctx.createLinearGradient(0, 0, 0, 320);
            gradient.addColorStop(0, "rgba(21, 112, 239, 0.28)");
            gradient.addColorStop(0.55, "rgba(18, 183, 106, 0.12)");
            gradient.addColorStop(1, "rgba(21, 112, 239, 0.02)");

            chartInstance = new Chart(ctx, {
                type: "line",
                data: {
                    labels: labels,
                    datasets: [{
                        label: "Jumlah Pendaftaran",
                        data: values,
                        borderColor: "#1570ef",
                        backgroundColor: gradient,
                        fill: true,
                        tension: 0.45,
                        borderWidth: 3,
                        pointRadius: 4,
                        pointHoverRadius: 7,
                        pointBackgroundColor: "#ffffff",
                        pointBorderColor: "#1570ef",
                        pointBorderWidth: 3
                    }]
                },
                options: {
                    responsive: true,
                    interaction: {
                        mode: "index",
                        intersect: false
                    },
                    plugins: {
                        legend: { display: false },
                        tooltip: {
                            backgroundColor: "rgba(17, 24, 39, 0.92)",
                            padding: 12,
                            displayColors: false,
                            callbacks: {
                                label: function(context) {
                                    return " " + context.parsed.y.toLocaleString("id-ID") + " member";
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            grid: { display: false },
                            ticks: {
                                color: "#98a2b3",
                                font: { weight: "600" }
                            }
                        },
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: "rgba(148, 163, 184, 0.22)",
                                borderDash: [4, 4]
                            },
                            ticks: {
                                color: "#98a2b3",
                                font: { weight: "600" },
                                callback: function(value) {
                                    return value.toLocaleString("id-ID");
                                }
                            }
                        }
                    }
                }
            });

        } catch (error) {
            console.error("Error mengambil data:", error);
        }
    }

    fetchChartData();
});
    </script>
    <script>
    document.addEventListener("DOMContentLoaded", async function () {
    let chartInstance = null;
    let doughnutCanvas = document.getElementById("chartjsDoughnut");

    if (!doughnutCanvas) {
        console.error("Canvas chartjsDoughnut tidak ditemukan.");
        return;
    }

    async function fetchBalanceData() {
        try {
            let response = await fetch("function/balanceCharts.php");
            let data = await response.json();
            console.log("Data balance:", data);

            let labels = Object.keys(data);
            let values = Object.values(data);

            let ctx = doughnutCanvas.getContext("2d");

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

            const palette = ["#727cf5", "#57caeb", "#5ddab4", "#ff7976", "#f7c94b"];
            const colors = labels.map((_, index) => palette[index % palette.length]);

            chartInstance = new Chart(ctx, {
                type: "doughnut",
                data: {
                    labels: labels,
                    datasets: [{
                        label: "Total Saldo",
                        data: values,
                        backgroundColor: colors,
                        borderWidth: 0,
                        hoverOffset: 12,
                        spacing: 3
                    }]
                },
                options: {
                    responsive: true,
                    cutout: "70%",
                    plugins: {
                        legend: {
                            position: "bottom",
                            labels: {
                                usePointStyle: true,
                                boxWidth: 8,
                                padding: 16
                            }
                        },
                        tooltip: {
                            backgroundColor: "rgba(32, 34, 44, 0.9)",
                            padding: 10,
                            callbacks: {
                                label: function(context) {
                                    var value = context.parsed || 0;
                                    return " " + context.label + ": " + value.toLocaleString("id-ID");
                                }
                            }
                        }
                    }
                }
            });

        } catch (error) {
            console.error("Error mengambil data saldo:", error);
        }
    }

    fetchBalanceData();
});
    </script>
    <script>
    document.addEventListener("DOMContentLoaded", function() {
        const editProviderCode = document.getElementById("editProviderCode");
        const editProviderStatus = document.getElementById("editProviderStatus");

        if (!editProviderCode || !editProviderStatus) {
            return;
        }

        const editButtons = document.querySelectorAll(".edit-provider-btn");
    
        editButtons.forEach(button => {
            button.addEventListener("click", function() {
                const providerCode = this.getAttribute("data-id");
                const providerStatus = this.getAttribute("data-status");
    
                editProviderCode.value = providerCode;
                editProviderStatus.value = providerStatus;
            });
        });
    });
    </script>
<script>
    function updatePaymentInfo() {
        var paymentSelect = document.getElementById("payment_method");
        if (!paymentSelect) {
            return;
        }

        var selectedOption = paymentSelect.options[paymentSelect.selectedIndex];

        var bank = selectedOption.value;
        var namaRekening = selectedOption.getAttribute("data-nama") || "";
        var nomorRekening = selectedOption.getAttribute("data-nomor") || "";
        var isQris = selectedOption.getAttribute("data-qris") === "1";
        var selectedBank = document.getElementById("selected_bank");
        var selectedAccount = document.getElementById("selected_account");
        var selectedNumber = document.getElementById("selected_number");
        var hiddenNama = document.getElementById("hidden_nama_rekening");
        var hiddenNomor = document.getElementById("hidden_nomor_rekening");
        var paymentInfo = document.getElementById("payment_info");

        if (selectedBank) {
            selectedBank.innerText = isQris ? "QRIS Otomatis" : bank;
        }
        if (selectedAccount) {
            selectedAccount.innerText = namaRekening;
        }
        if (selectedNumber) {
            selectedNumber.innerText = nomorRekening;
        }
        if (hiddenNama) {
            hiddenNama.value = namaRekening;
        }
        if (hiddenNomor) {
            hiddenNomor.value = nomorRekening;
        }
        if (paymentInfo) {
            paymentInfo.style.display = bank !== "0" ? "block" : "none";
        }
    }

    document.addEventListener("DOMContentLoaded", function() {
        updatePaymentInfo();
    });

    function copyToClipboard() {
        var selectedNumber = document.getElementById("selected_number");
        if (!selectedNumber) {
            return;
        }

        var text = selectedNumber.innerText;
        navigator.clipboard.writeText(text).then(function() {
            alert("Nomor rekening berhasil disalin!");
        }).catch(function(err) {
            console.error("Gagal menyalin: ", err);
        });
    }
</script>
<script>
    document.addEventListener("DOMContentLoaded", function() {
        document.querySelectorAll("form.call-apply-form").forEach(function(form) {
            var agentBalance = parseFloat(form.dataset.agentBalance || "0");
            var callRtpSelect = form.querySelector(".call-rtp-select");
            var callTypeSelect = form.querySelector("select[name='call_type']");
            var callRequiredEl = form.querySelector(".call-required");
            var warningEl = form.querySelector(".call-warning");
            var applyBtn = form.querySelector(".call-apply-btn");

            if (!callRtpSelect || !callRequiredEl || !applyBtn) {
                return;
            }

            function updateCallState() {
                if (callRtpSelect.disabled) {
                    if (warningEl) {
                        warningEl.classList.remove("d-none");
                    }
                    applyBtn.disabled = true;
                    return;
                }

                var selectedOption = callRtpSelect.options[callRtpSelect.selectedIndex];
                var required = 0;

                if (selectedOption && selectedOption.dataset.required) {
                    required = parseFloat(selectedOption.dataset.required) || 0;
                }

                callRequiredEl.textContent = required.toLocaleString("id-ID");

                if (required > agentBalance) {
                    if (warningEl) {
                        warningEl.classList.remove("d-none");
                    }
                    applyBtn.disabled = true;
                    return;
                }

                if (warningEl) {
                    warningEl.classList.add("d-none");
                }
                applyBtn.disabled = false;
            }

            callRtpSelect.addEventListener("change", updateCallState);
            if (callTypeSelect) {
                callTypeSelect.addEventListener("change", updateCallState);
            }
            updateCallState();
        });
    });
</script>
