document.addEventListener('DOMContentLoaded', function () {
    /* ---------- SAVE FILTER MODAL (MODAL 1) ---------- */
    const openBtn  = document.getElementById('openFilterModal');
    const modal1   = document.getElementById('filterModal');
    const close1   = modal1?.querySelector('.close');
	/* ---------- EDIT / UPDATE BUTTON TOGGLE ---------- */
    const editBtn     = document.getElementById('editFilterBtn');
    const updateBtn   = document.getElementById('updateFilterBtn');
    const saveBtn     = document.getElementById('openFilterModal');
    const savedFilter = document.getElementById('saved_filter');
    openBtn?.addEventListener('click', function (e) {
        e.preventDefault();
        modal1.classList.add('show');
    });

    close1?.addEventListener('click', function () {
        modal1.classList.remove('show');
    });

    modal1?.addEventListener('click', function (e) {
        if (e.target === modal1) modal1.classList.remove('show');
    });

    editBtn?.addEventListener('click', function () {
        if (!savedFilter.value) {
            alert('Please select a filter to edit');
            return;
        }
        saveBtn.style.display   = 'none';
        updateBtn.style.display = 'inline-block';
    });
    /* ---------- LOAD FILTER ON DROPDOWN CHANGE ---------- */
    savedFilter?.addEventListener('change', function () {


	    if (this.value) {
			// hide Save Filter button
			saveBtn.style.display = 'none';
		} else {
			// show Save Filter button again if selection cleared
			saveBtn.style.display = 'inline-block';
		}
        if (!this.value) return;

        $.ajax({
            url: "omnichannel_config/save_filter_function.php",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({
                action: "get_filter",
                filter_id: this.value
            }),
            success: function (response) {

                if (response.status !== "success" || !response.filters) return;

                let f = response.filters;

                $('#startdatetime').val(f.startdatetime ?? "");
                $('#enddatetime').val(f.enddatetime ?? "");
                $('#agent_n').val(f.agent_n ?? "");
                $('#channel').val(f.channel ?? "");
                $('#product').val(f.product ?? "");
                $('#requesttype').val(f.requesttype ?? "");
                $('#user_email').val(f.user_email ?? "");

                $('#intraction_report_form').trigger('submit');
            }
        });
    });
    /* ---------- UPDATE FILTER MODAL (MODAL 2) ---------- */
    const modal2        = document.getElementById('filterModal2');
    const close2        = modal2?.querySelector('.close');
    const filterNameUpd = document.getElementById('filter_name_update');
    const saveUpdateBtn = document.getElementById('save_filters2');

    updateBtn?.addEventListener('click', function () {

        if (!savedFilter.value) {
            alert('Please select a filter to update');
            return;
        }

        filterNameUpd.value =
            savedFilter.options[savedFilter.selectedIndex].text;

        modal2.dataset.filterId = savedFilter.value;
        modal2.classList.add('show');
    });

    close2?.addEventListener('click', function () {
        modal2.classList.remove('show');
    });

    modal2?.addEventListener('click', function (e) {
        if (e.target === modal2) modal2.classList.remove('show');
    });
    /* ---------- UPDATE FILTER SAVE ---------- */
    saveUpdateBtn?.addEventListener('click', function () {

        $.ajax({
            url: "omnichannel_config/save_filter_function.php",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({
                action: "update_filter",
                filter_id: modal2.dataset.filterId,
                filter_name: filterNameUpd.value.trim(),
                filter_page: "interaction_report",
                filters: {
                    startdatetime: $('#startdatetime').val() || "",
                    enddatetime: $('#enddatetime').val() || "",
                    agent_n: $('#agent_n').val() || "",
                    channel: $('#channel').val() || "",
                    product: $('#product').val() || "",
                    requesttype: $('#requesttype').val() || "",
                    user_email: $('#user_email').val() || ""
                }
            }),
            success: function () {
                modal2.classList.remove('show');
            }
        });
    });
    /* ---------- SAVE NEW FILTER ---------- */
    const saveNewBtn = document.getElementById('save_filters1');

    saveNewBtn?.addEventListener('click', function (e) {
        e.preventDefault();

        $.ajax({
            url: "omnichannel_config/save_filter_function.php",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({
                action: "save_filter",
                filter_name: $('#filter_name').val().trim(),
                filter_page: "interaction_report",
                filter_id: "",
                filters: {
                    startdatetime: $('#startdatetime').val() || "",
                    enddatetime: $('#enddatetime').val() || "",
                    agent_n: $('#agent_n').val() || "",
                    channel: $('#channel').val() || "",
                    product: $('#product').val() || "",
                    requesttype: $('#requesttype').val() || "",
                    user_email: $('#user_email').val() || ""
                }
            })
        });
    });
});