document.addEventListener("DOMContentLoaded", function () {
    const params = new URLSearchParams(window.location.search);
    const page = params.get("p") || "dashboard"; //page

    const hide = (...ids) => ids.forEach((id) => setDisplay(id, "none"));
    const show = (...ids) => ids.forEach((id) => setDisplay(id, ""));

    function byId(id) {
        return document.getElementById(id);
    }

    function setDisplay(id, value) {
        const element = byId(id);
        if (element) element.style.display = value;
    }

    function setValue(selector, value) {
        document.querySelectorAll(selector).forEach((element) => {
            element.value = value;
        });
    }

    function setDisabled(selector, disabled) {
        document.querySelectorAll(selector).forEach((element) => {
            element.disabled = disabled;
        });
    }

    function clearFields(selector) {
        document.querySelectorAll(selector).forEach((element) => {
            element.value = "";
        });
    }

    function formatNumber(value) {
        return Number(value || 0).toLocaleString("id-ID");
    }

    function updateSummaryLabels(level) {
        const label2 = document.getElementById('summary-label-2');
        const label3 = document.getElementById('summary-label-3');
        const label4 = document.getElementById('summary-label-4');
        const unit1 = document.getElementById('summary-unit-1');
        const unit2 = document.getElementById('summary-unit-2');
        const unit3 = document.getElementById('summary-unit-3');
        const unit4 = document.getElementById('summary-unit-4');

        if (!label2 || !label3 || !label4 || !unit1 || !unit2 || !unit3 || !unit4) return;

        if (level === 'bendahara') {
            label2.textContent = 'Pemasukan';
            label3.textContent = 'Sudah Lunas';
            label4.textContent = 'Belum Bayar';
            unit1.textContent = 'orang';
            unit2.textContent = 'Rp';
            unit3.textContent = 'orang';
            unit4.textContent = 'orang';
        } else if (level === 'warga') {
            label2.textContent = 'Pemakaian Air';
            label3.textContent = 'Tagihan';
            label4.textContent = 'Status Tagihan';
            unit1.textContent = '';
            unit2.innerHTML = 'm<sup>3</sup>';
            unit3.textContent = 'Rp';
            unit4.textContent = '';
        } else {
            label2.textContent = 'Pemakaian Air';
            label3.textContent = 'Sudah Dicatat';
            label4.textContent = 'Belum Dicatat';
            unit1.textContent = 'orang';
            unit2.innerHTML = 'm<sup>3</sup>';
            unit3.textContent = 'warga';
            unit4.textContent = 'warga';
        }
    }

    function appendHidden(formSelector, name, value) {
        const form = document.querySelector(formSelector);
        if (!form) return;

        form.querySelectorAll(`input[type="hidden"][name="${name}"]`).forEach((input) => input.remove());

        const input = document.createElement("input");
        input.type = "hidden";
        input.name = name;
        input.value = value || "";
        form.appendChild(input);
    }

    function addToolbarButton(label, iconClass, onClick, fallbackSelector) {
        const action = label.toLowerCase();
        const dropdowns = document.querySelectorAll(".datatable-dropdown");
        const targets = dropdowns.length ? dropdowns : document.querySelectorAll(fallbackSelector);

        if (dropdowns.length) {
            document.querySelectorAll(`[data-air-action="${action}"]`).forEach((button) => {
                if (!button.closest(".datatable-dropdown")) button.remove();
            });
        }

        targets.forEach((target) => {
            if (target.querySelector("[data-air-action]")) return;

            const button = document.createElement("button");
            button.type = "button";
            button.className = dropdowns.length
                ? "btn btn-outline-success float-start me-2"
                : "btn btn-outline-success btn-sm float-end";
            button.dataset.airAction = action;
            button.innerHTML = `<i class="${iconClass}"></i> ${label}`;
            button.addEventListener("click", onClick);
            target.appendChild(button);
        });
    }

    function initDataTable(tableId) {
        const table = byId(tableId);
        if (!table || !window.simpleDatatables || !window.simpleDatatables.DataTable) return;
        if (table.dataset.airDatatable === "ready") return;

        new window.simpleDatatables.DataTable(table);
        table.dataset.airDatatable = "ready";
    }

    function setModalMessage(message, hiddenName, hiddenValue, submitValue) {
        const modalBody = document.querySelector("#myModal .modal-body");
        const modalForm = document.querySelector("#myModal .modal-footer form");
        const submitButton = document.querySelector("#myModal .modal-footer button[type='submit']");

        if (modalBody) modalBody.textContent = message;
        if (modalForm && hiddenName) {
            modalForm.querySelectorAll("input[type='hidden']").forEach((input) => input.remove());
            appendHidden("#myModal .modal-footer form", hiddenName, hiddenValue);
        }
        if (submitButton && submitValue) submitButton.value = submitValue;
    }

    function bindDeleteButtons() {
        document.addEventListener("click", function (event) {
            const button = event.target.closest("button[data-bs-toggle='modal']");
            if (!button) return;

            if (button.dataset.user) {
                setModalMessage(`Yakin hapus data user '${button.dataset.user}'?`, "user", button.dataset.user, "user_hapus");
            } else if (button.dataset.id_tarif) {
                setModalMessage(`Yakin hapus data tarif '${button.dataset.id_tarif}'?`, "id_tarif", button.dataset.id_tarif, "tarif_hapus");
            } else if (button.dataset.no) { //bagian tulisan "Yakin hapus data meter ''?, angka meter dari
                setModalMessage(`Yakin hapus data meter '${button.dataset.no}'?`, "no", button.dataset.no, "meter_hapus");
            }
        });
    }

    hide("user_add", "user_list", "tarif_add", "tarif_list", "meter_add", "meter_list", "pemakaian_sendiri");

    if (page === "user" || page === "user_edit") {
        hide("summary", "chart", "tarif_add", "tarif_list", "meter_add", "meter_list", "pemakaian_sendiri");

        if (page === "user_edit") {
            hide("user_list");
            show("user_add");
            setDisabled("#user_form input[name='yuser']", true);
            setValue("#user_form button", "user_edit");
            appendHidden("#user_form", "yuser", params.get("user"));
        } else {
            show("user_list");
            hide("user_add");
        }

        if (document.querySelector("#alert-user.alert-danger")) {
            hide("user_list");
            show("user_add");
        } else if (document.querySelector("#alert-user.alert-success")) {
            show("user_list");
            hide("user_add");
        }

        const showUserForm = function () {
            hide("user_list");
            show("user_add");
            clearFields("#user_form input, #user_form textarea, #user_form select");
            setValue("#user_form button", "user_add");
            setDisabled("#user_form input[name='user']", false);
        };

        setTimeout(function () {
            addToolbarButton("User", "fa-solid fa-user-plus fa-beat", showUserForm, "#user_list .card-header");
        }, 0);
    } else if (page === "tarif" || page === "tarif_edit") {
        hide("summary", "chart", "user_add", "user_list", "meter_add", "meter_list", "pemakaian_sendiri");

        if (page === "tarif_edit") {
            show("tarif_add");
            hide("tarif_list");
            setDisabled("#tarif_form input[name='id_tarif']", true);
            setValue("#tarif_form button", "tarif_edit");
            appendHidden("#tarif_form", "id_tarif", params.get("id_tarif"));
        } else {
            hide("tarif_add");
            show("tarif_list");
        }

        if (document.querySelector("#alert-tarif.alert-danger")) {
            hide("tarif_list");
            show("tarif_add");
        } else if (document.querySelector("#alert-tarif.alert-success")) {
            show("tarif_list");
            hide("tarif_add");
        }

        initDataTable("table_tarif");
        addToolbarButton("Tarif", "fa-solid fa-money-bill-wave fa-beat", function () {
            hide("tarif_list");
            show("tarif_add");
            setValue("#tarif_form button", "tarif_add");
            setDisabled("#tarif_form input[name='id_tarif']", false);
        }, "#tarif_list .card-header");

       // form meter edit 
    } else if (page === "catat_meter" || page === "meter_edit") {
        hide("summary", "chart", "user_add", "user_list", "tarif_add", "tarif_list", "pemakaian_sendiri");

        if (page === "meter_edit") {
            show("meter_add");
            hide("meter_list");
            setDisabled("#meter_form input[name='no']", true);
            setValue("#meter_form button", "meter_edit");
            appendHidden("#meter_form", "no", params.get("no"));
        } else {
            hide("meter_add");
            show("meter_list");
        }

        if (document.querySelector("#alert-meter.alert-danger")) {
            hide("meter_list");
            show("meter_add");
        } else if (document.querySelector("#alert-meter.alert-success")) {
            show("meter_list");
            hide("meter_add");
        }

        initDataTable("table_meter");
        //tombol hijau di meter, toolbar untuk tulisan meter
        const currentLevel = typeof level_login !== "undefined" ? level_login : "";
        if (currentLevel === "admin" || currentLevel === "petugas") {
            addToolbarButton("Meter", "fa-solid fa-hand-holding-droplet fa-beat", function () {
                hide("meter_list");
                show("meter_add");
                clearFields("#meter_form input");
            }, "#meter_list .card-header");
        }
    } else if (page === "lihat_pemakaian") {
        hide("summary", "chart", "user_add", "user_list", "tarif_add", "tarif_list", "meter_add", "meter_list");
        show("pemakaian_sendiri");
        initDataTable("table_pemakaian");
    } else {
        show("summary", "chart");
        updateSummaryLabels(level_login);
        
        // ambil bulan dari dropdown
        $("#pilih_waktu select[name='pilih_waktu']").on("change",function(){
            bln=$(this).val();
            console.log("bulan dipilih: "+bln);

            $.ajax({
                type: "post",
                url: "../assets/ajax.php",
                data: {p:"summary",t:bln},
                dataType: "json"
            })
            .done(function(res){
                if (!res) return;
                var role = res.role || 'default';
                var d = res.data || {};

                updateSummaryLabels(level_login);

                if (role === 'warga') {
                    $("#summary .bg-primary h1").text(d.waktu_pencatatan || '');
                    $("#summary .bg-primary").find("#summary-unit-1").text(d.jam || '');
                    $("#summary .bg-warning h1").text(formatNumber(d.pemakaian || 0));
                    $("#summary .bg-success h1").text(formatNumber(d.tagihan || 0));
                    $("#summary .bg-danger h1").text(d.status_tagihan || '');
                } else if (role === 'bendahara') {
                    $("#summary .bg-primary h1").text(formatNumber(d.jml_pelanggan || 0));
                    $("#summary .bg-warning h1").text(formatNumber(d.jml_pemasukan || 0));
                    $("#summary .bg-success h1").text(formatNumber(d.sudah_lunas || 0));
                    $("#summary .bg-danger h1").text(formatNumber(d.belum_lunas || 0));
                } else {
                    $("#summary .bg-primary h1").text(formatNumber(d.jml_pelanggan || 0));
                    $("#summary .bg-warning h1").text(formatNumber(d.jml_pemakaian || 0));
                    $("#summary .bg-success h1").text(formatNumber(d.sudah_dicatat || 0));
                    var belum_dicatat = (d.jml_pelanggan || 0) - (d.sudah_dicatat || 0);
                    $("#summary .bg-danger h1").text(formatNumber(belum_dicatat));
                }
            })
            .fail(function(){
                console.log("ada error");
            })
        })

        $.ajax({
            type: "post",
            url: "../assets/ajax.php",
            data: {p:"chart_bar",user:user_login},
            dataType: "json"
        })
        .done(function(res){
            
            sumbuX=res.filter((num, index) => index % 2 == 0);
            sumbuY=res.filter((num, index) => index % 2 != 0);
    
        console.log("res: "+res);

                    // Set new default font family and font color to mimic Bootstrap's default styling
        Chart.defaults.global.defaultFontFamily = '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif';
        Chart.defaults.global.defaultFontColor = '#292b2c';

        // Bar Chart Example
        var ctx = document.getElementById("myBarChart");
        var myLineChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: sumbuX,
            datasets: [{
            label: "Pemakaian (m3)",
            backgroundColor: "rgba(2,117,216,1)",
            borderColor: "rgba(2,117,216,1)",
            data: sumbuY,
            }],
        },
        options: {
            scales: {
            xAxes: [{
                time: {
                unit: 'month'
                },
                gridLines: {
                display: false
                },
                ticks: {
                maxTicksLimit: 6
                }
            }],
            yAxes: [{
                ticks: {
                min: 0,
                max: 200,
                maxTicksLimit: 5
                },
                gridLines: {
                display: true
                }
            }],
            },
            legend: {
            display: false
            }
        }
        });

            if (!res) return;
        })


    }

    bindDeleteButtons();
});

$.ajax({
            type: "post",
            url: "../assets/ajax.php",
            data: {p:"chart_line",user:user_login},
            dataType: "json"
        })
        .done(function(res){
            
             sumbuX=res.filter((num, index) => index % 2 == 0);
            sumbuY=res.filter((num, index) => index % 2 != 0);
    
        console.log("res: "+res);

                    // Set new default font family and font color to mimic Bootstrap's default styling
        Chart.defaults.global.defaultFontFamily = '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif';
        Chart.defaults.global.defaultFontColor = '#292b2c';

        // Area Chart Example
        var ctx = document.getElementById("myAreaChart");
        var myLineChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: sumbuX,
            datasets: [{
            label: "Tagihan (Rp)",
            lineTension: 0.3,
            backgroundColor: "rgba(2,117,216,0.2)",
            borderColor: "rgba(2,117,216,1)",
            pointRadius: 5,
            pointBackgroundColor: "rgba(2,117,216,1)",
            pointBorderColor: "rgba(255,255,255,0.8)",
            pointHoverRadius: 5,
            pointHoverBackgroundColor: "rgba(2,117,216,1)",
            pointHitRadius: 50,
            pointBorderWidth: 2,
            data: sumbuY,
            }],
        },
        options: {
            scales: {
            xAxes: [{
                time: {
                unit: 'date'
                },
                gridLines: {
                display: false
                },
                ticks: {
                maxTicksLimit: 7
                }
            }],
            yAxes: [{
                ticks: {
                min: 0,
                max: 1000000,
                maxTicksLimit: 5
                },
                gridLines: {
                color: "rgba(0, 0, 0, .125)",
                }
            }],
            },
            legend: {
            display: false
            }
        }
        });

            if (!res) return;
        })  