
// ============================
// Search Planning/Zoning Facts
// ============================

$(document).ready(function () {

    var $application = $("#APPLICATION_MNEMONIC").val(), $sessionStorage = JSON.parse(sessionStorage.getItem($application) || "{}");

    // -----------
    // Input Masks
    // -----------

    $(".date-mask").inputmask({alias: "datetime",
        inputFormat: "mm/dd/yyyy",
        placeholder: "MM/DD/YYYY",
        showMaskOnHover: false});

    $(".numeric-mask").inputmask("9{0,9}", {showMaskOnHover: false});

    $('.sqft-mask').inputmask('numeric', {
        groupSeparator: ',',
        autoGroup: true,
        digits: 0, // whole numbers only
        digitsOptional: false,
        allowMinus: false,
        rightAlign: false,
        removeMaskOnSubmit: true
    });

    // --------------
    // Select Pickers
    // --------------

    $(".search-dropdown").selectpicker({noneSelectedText: "",
        style: "",
        styleBase: "form-select form-select-sm",
        iconBase: "bi",
        virtualScroll: true,
        size: 10,
        selectOnTab: true,
        containter: "body",
        liveSearch: true});

    $(".multiple-dropdown").selectpicker({noneSelectedText: "Choose...",
        style: "",
        styleBase: "form-select form-select-sm",
        iconBase: "fa",
        actionsBox: true,
        selectedTextFormat: "count",
        virtualScroll: true,
        size: 10,
        selectOnTab: true,
        containter: "body",
        liveSearch: true});

    // ------------
    // Date Pickers
    // ------------

    $("#pzfact_entry_date_from").datepicker({format: "mm-dd-yyyy",
        container: "div.entry_date",
        keyboardNavigation: false,
        showOnFocus: false,
        autoclose: true,
        endDate: "0d",
        orientation: "left bottom",
        todayBtn: "linked",
        todayHighlight: true});

    $("#pzfact_entry_date_to").datepicker({format: "mm-dd-yyyy",
        container: "div.entry_date",
        keyboardNavigation: false,
        showOnFocus: false,
        autoclose: true,
        endDate: "0d",
        orientation: "left bottom",
        todayBtn: "linked",
        todayHighlight: true});

    // ---------------------
    // Show Calendar Buttons
    // ---------------------

    $(".btnEntryDateFromCalendar").on("click", function (e) {
        e.preventDefault();
        $("#pzfact_entry_date_from").focus().datepicker("show");
    });
    $(".btnEntryDateToCalendar").on("click", function (e) {
        e.preventDefault();
        $("#pzfact_entry_date_to").focus().datepicker("show");
    });

    $("#pzfacts_per_page").val($sessionStorage.pzfacts_per_page || "20");

    // ---------------
    // Per Page Change
    // ---------------

    $("#pzfacts_per_page").on("change", function () {

        $sessionStorage.pzfacts_per_page = $(this).val();
        $sessionStorage.action = "PlanningAndZoningFacts.searchPlanningAndZoningFacts";
        $sessionStorage.pagination = "first";

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

        $("#spinner-dialog").modal("show");

        formSubmit($sessionStorage);

    });

    // ------------------
    // Pagination Buttons
    // ------------------

    $(".btnPagination").on("click", function () {

        $sessionStorage.action = "PlanningAndZoningFacts.searchPlanningAndZoningFacts";
        $sessionStorage.pagination = $(this).data("pagination");

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

        $("#spinner-dialog").modal("show");

        formSubmit($sessionStorage);

        delete $sessionStorage.pagination;

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

    });

    // =================
    // Process Enter Key
    // =================

    $(document).on('keypress', function (e) {
        if (e.which === 13) {
            e.preventDefault();
            $("#searchPZFacts").submit();
        }
    });

    // -------------------
    // Filter the PZ Cards
    // -------------------

    $("#filter").on("keyup", function () {

        const filter = $(this).val().toLowerCase().trim();

        $(".pzfact-card").hide().filter(function () {
            return $(this).text().toLowerCase().indexOf(filter) > -1;
        }).show();

        if ($(".pzfact-card:visible").length === 0) {
            $(".filter-error").removeClass("d-none");
            $(".print_page_buttons").addClass("d-none");
        } else {
            $(".filter-error").addClass("d-none");
            $(".print_page_buttons").removeClass("d-none");
        }
    });

    // ----------------
    // Clear the filter
    // ----------------

    $("#filter").on("keydown", function (e) {
        if (e.key === "Escape") {
            $(this).val("").trigger("keyup");
        }
    });

    // -----------------------
    // Export PZ Facts - Excel
    // -----------------------

    $(".btnExportExcel").on("click", function (e) {

        $("#spinner-dialog").modal("show");

        $sessionStorage.action = "Export_PZFactsToExcel.export";
        $sessionStorage.subscription_reference = $sessionStorage.subscription_serial;
        $sessionStorage.pagination = "off";

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

        // Submit in a new tab
        formSubmit($sessionStorage, "_blank");

        // Hide spinner immediately, since the main page isn't going anywhere
        setTimeout(function () {
            $("#spinner-dialog").modal("hide");
        }, 2000); // optional: add a slight delay so it feels responsive
    });

    // -------------------------
    // Export PZ Facts - CSV
    // -------------------------

    $(".btnExportCSV").on("click", function (e) {

        $("#spinner-dialog").modal("show");

        $sessionStorage.action = "Export_PZFactsToCSV.export";
        $sessionStorage.subscription_reference = $sessionStorage.subscription_serial;
        $sessionStorage.pagination = "off";

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

        // Submit in a new tab
        formSubmit($sessionStorage, "_blank");

        // Hide spinner immediately, since the main page isn't going anywhere
        setTimeout(function () {
            $("#spinner-dialog").modal("hide");
        }, 2000); // optional: add a slight delay so it feels responsive

    });

    // ------------------------
    // Print PZ Facts - PDF
    // ------------------------

    $(".btnPrintSearchResultsPDF").on("click", function (e) {

        $("#spinner-dialog").modal("show");

        $sessionStorage.action = "Print_PZFactsPDF.print";
        $sessionStorage.subscription_reference = $sessionStorage.subscription_serial;
        $sessionStorage.pagination = "off";

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

        // Submit in a new tab
        formSubmit($sessionStorage, "_blank");

        // Hide spinner immediately, since the main page isn't going anywhere
        setTimeout(function () {
            $("#spinner-dialog").modal("hide");
        }, 2000); // optional: add a slight delay so it feels responsive

    });

    // --------------------------------------
    // Export All Planning/Zoning Facts - CSV
    // --------------------------------------

    $(".btnExportAllRecordsCSV").on("click", function (e) {

        $sessionStorage.action = "Export.createExportRequest";
        $sessionStorage.subscription_reference = $sessionStorage.subscription_serial;
        $sessionStorage.userSubscriptions = "Export.usersExports";
        $sessionStorage.report_type = "csv";

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

        formSubmit($sessionStorage);

    });
    // -------------------------------
    // Export All Permit Facts - Excel
    // -------------------------------

    $(".btnExportAllRecordsExcel").on("click", function (e) {

        $sessionStorage.action = "Export.createExportRequest";
        $sessionStorage.subscription_reference = $sessionStorage.subscription_serial;
        $sessionStorage.userSubscriptions = "Export.usersExports";
        $sessionStorage.report_type = "xlsx";

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

        formSubmit($sessionStorage);

    });
    // -----------------------------
    // Export All Permit Facts - PDF
    // -----------------------------

    $(".btnPrintAllRecordsPDF").on("click", function (e) {

        $sessionStorage.action = "Export.createExportRequest";
        $sessionStorage.subscription_reference = $sessionStorage.subscription_serial;
        $sessionStorage.userSubscriptions = "Export.usersExports";
        $sessionStorage.report_type = "pdf";

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

        formSubmit($sessionStorage);

    });

    // -----------
    // Save Button
    // -----------

    $(".btnSearch").on("click", function (e) {
        e.preventDefault();
        $("#searchPZFacts").submit();
    });

    // -----------
    // Home Button
    // -----------

    $(".btnHome").on("click", function () {

        $sessionStorage.action = "Subscriptions.usersSubscriptions";

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

        formSubmit($sessionStorage);

    });

    // -------------------
    // Reset Search Button
    // -------------------

    $(".btnReset").on("click", function () {

        clearForm($('#searchPZFacts'));

        $sessionStorage = clearSubscriptionSessionVariableFilters($sessionStorage);

        $sessionStorage.action = "PlanningAndZoningFacts.searchPlanningAndZoningFacts";

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

        formSubmit($sessionStorage);

    });

    // ---------------
    // Validate Inputs
    // ---------------

    $("#searchPZFacts").submit(function (e) {

        var pzfact_project_name = $("#pzfact_project_name").val(),
                pzfact_in_city_limit = $("#pzfact_in_city_limit").val(),
                pzfact_project_city = $("#pzfact_project_city").val(),
                pzfact_county = $("#pzfact_county").val(),
                pzfact_project_type = $("#pzfact_project_type").val(),
                pzfact_action_code = $("#pzfact_action_code").val(),
                pzfact_acres_from = $("#pzfact_acres_from"),
                pzfact_acres_to = $("#pzfact_acres_to"),
                pzfact_entry_date_from = $("#pzfact_entry_date_from"),
                pzfact_entry_date_to = $("#pzfact_entry_date_to");

        clearInputErrors();

        /*
         * Normalize values (strip commas, spaces, etc.)
         */
        let minSqft = parseInt(pzfact_acres_from.val().replace(/[^0-9]/g, ''), 10);
        let maxSqft = parseInt(pzfact_acres_to.val().replace(/[^0-9]/g, ''), 10);

        /*
         * Range validation
         */
        if (!isNaN(minSqft) && !isNaN(maxSqft)) {
            if (minSqft > maxSqft) {
                createInputError(pzfact_acres_from, "Min acreage is greater than Max acreage");
                return false;
            }
        }

        if ((!isBlank(pzfact_entry_date_from)) && (!pzfact_entry_date_from.inputmask("isComplete"))) {
            createInputError(pzfact_entry_date_from, "Date is incomplete");
            return false;
        }

        if ((!isBlank(pzfact_entry_date_to)) && (!pzfact_entry_date_to.inputmask("isComplete"))) {
            createInputError(pzfact_entry_date_to, "Date is incomplete");
            return false;
        }

        let startDate2 = new Date(pzfact_entry_date_from.val()),
                endDate2 = new Date(pzfact_entry_date_to.val());

        if (startDate2 > endDate2) {
            createInputError(pzfact_entry_date_from, "Date is after End Date");
            return false;
        }

        e.preventDefault();

        $sessionStorage.action = "PlanningAndZoningFacts.searchPlanningAndZoningFacts";
        $sessionStorage.pagination = "first";

        $sessionStorage.pzfact_project_name = pzfact_project_name;
        $sessionStorage.pzfact_in_city_limit = pzfact_in_city_limit;
        $sessionStorage.pzfact_project_city = pzfact_project_city;
        $sessionStorage.pzfact_county = pzfact_county;
        $sessionStorage.pzfact_project_type = pzfact_project_type;
        $sessionStorage.pzfact_project_type = pzfact_project_type;
        $sessionStorage.pzfact_action_code = pzfact_action_code;
        $sessionStorage.pzfact_acres_from = pzfact_acres_from.val();
        $sessionStorage.pzfact_acres_to = pzfact_acres_to.val();
        $sessionStorage.pzfact_entry_date_from = pzfact_entry_date_from.val();
        $sessionStorage.pzfact_entry_date_to = pzfact_entry_date_to.val();

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

        $("#spinner-dialog").modal("show");

        formSubmit($sessionStorage);

    });
});

function clearForm($form) {

    // Clear text, number, masked inputs, and textareas
    $form.find('input:not([type=checkbox]):not([type=radio]), textarea')
            .val('')
            .trigger('change');

    // Clear checkboxes and radios
    $form.find('input[type=checkbox], input[type=radio]')
            .prop('checked', false)
            .trigger('change');

    // Clear standard selects
    $form.find('select').val('').trigger('change');

    // Refresh bootstrap-select (selectpicker)
    if ($.fn.selectpicker) {
        $form.find('.selectpicker').selectpicker('refresh');
    }

    // Clear jQuery UI / Bootstrap datepickers
    $form.find('.date-mask').each(function () {
        if ($(this).data('datepicker')) {
            $(this).datepicker('clearDates');
        }
    });
}

function printElement(selector) {
    const content = document.querySelector(selector).innerHTML;
    const original = document.body.innerHTML;

    document.body.innerHTML = content;
    window.print();
    document.body.innerHTML = original;
    location.reload(); // restores JS state
}
