
// ===================
// Search Permit 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});

    $(".zip-mask").inputmask("9{5}", {showMaskOnHover: false, removeMaskOnSubmit: true});

    $('.money-mask').inputmask('currency', {
        prefix: '$',
        groupSeparator: ',',
        digits: 0,
        digitsOptional: false,
        autoGroup: true,
        removeMaskOnSubmit: true
    });

    $('.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
    // ------------

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

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

    $("#permitfact_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});

    $("#permitfact_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
    // ---------------------

    $(".btnPermitDateFromCalendar").on("click", function (e) {
        e.preventDefault();
        $("#permitfact_permit_date_from").focus().datepicker("show");
    });
    $(".btnPermitDateToCalendar").on("click", function (e) {
        e.preventDefault();
        $("#permitfact_permit_date_to").focus().datepicker("show");
    });

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

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

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

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

        $sessionStorage.permitfacts_per_page = $(this).val();
        $sessionStorage.action = "PermitFacts.searchPermitFacts";
        $sessionStorage.pagination = "first";

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

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

        formSubmit($sessionStorage);

    });

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

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

        $sessionStorage.action = "PermitFacts.searchPermitFacts";
        $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();
            $("#searchPermitFacts").submit();
        }
    });

    // -----------------------
    // Filter the Permit Cards
    // -----------------------

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

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

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

        if ($(".permitfact-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 Permit Facts - Excel
    // ---------------------------

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

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

        $sessionStorage.action = "Export_PermitFactsToExcel.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 Permit Facts - CSV
    // -------------------------

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

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

        $sessionStorage.action = "Export_PermitFactsToCSV.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 Search Results - PDF
    // --------------------------

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

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

        $sessionStorage.action = "Print_PermitFactsPDF.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 Permit 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);

    });

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

    $(".btnSearch").on("click", function (e) {
        e.preventDefault();
        $("#searchPermitFacts").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($('#searchPermitFacts'));

        $sessionStorage = clearSubscriptionSessionVariableFilters($sessionStorage);

        $sessionStorage.action = "PermitFacts.searchPermitFacts";

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

        formSubmit($sessionStorage);

    });

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

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

        var permitfact_size_from = $("#permitfact_size_from"),
                permitfact_size_to = $("#permitfact_size_to"),
                permitfact_value_from = $("#permitfact_value_from"),
                permitfact_value_to = $("#permitfact_value_to"),
                permitfact_permit_date_from = $("#permitfact_permit_date_from"),
                permitfact_permit_date_to = $("#permitfact_permit_date_to"),
                permitfact_entry_date_from = $("#permitfact_entry_date_from"),
                permitfact_entry_date_to = $("#permitfact_entry_date_to"),
                permitfact_company = $("#permitfact_company").val(),
                permitfact_project_name = $("#permitfact_project_name").val(),
                permitfact_project_zip = $("#permitfact_project_zip").val(),
                permitfact_project_city = $("#permitfact_project_city").val(),
                permitfact_county = $("#permitfact_county").val(),
                permitfact_project_type = $("#permitfact_project_type").val(),
                permitfact_work_type = $("#permitfact_work_type").val(),
                permitfact_building_type = $("#permitfact_building_type").val();


        clearInputErrors();

        if ((!isBlank(permitfact_size_from)) && (!permitfact_size_from.inputmask("isComplete"))) {
            createInputError(permitfact_size_from, "Square footage is incomplete");
            return false;
        }

        if ((!isBlank(permitfact_size_to)) && (!permitfact_size_to.inputmask("isComplete"))) {
            createInputError(permitfact_size_to, "Square footage is incomplete");
            return false;
        }

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

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

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

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

        /*
         * Normalize values (strip $, commas, etc.)
         */
        let minValue = parseFloat(
                permitfact_value_from.val().replace(/[^0-9.-]/g, '')
                );

        let maxValue = parseFloat(
                permitfact_value_to.val().replace(/[^0-9.-]/g, '')
                );

        /*
         * Range validation
         */
        if (!isNaN(minValue) && !isNaN(maxValue)) {
            if (minValue > maxValue) {
                createInputError(permitfact_value_from, "Minimum amount is greater than maximum amount");
                return false;
            }
        }


        // -----------------------------
        // Date filter: issue OR entry
        // -----------------------------
        const hasPermitDate =
                !isBlank(permitfact_permit_date_from) || !isBlank(permitfact_permit_date_to);

        const hasEntryDate =
                !isBlank(permitfact_entry_date_from) || !isBlank(permitfact_entry_date_to);

        // Disallow using both
        if (hasPermitDate && hasEntryDate) {
            createInputError(permitfact_permit_date_from, "Use either Issue Date OR Entry Date (not both).");
            createInputError(permitfact_entry_date_from, "Use either Issue Date OR Entry Date (not both).");
            return false;
        }

        // OPTIONAL (recommended): if they choose one, require both From + To for that one
        if (hasPermitDate) {
            if (isBlank(permitfact_permit_date_from) || isBlank(permitfact_permit_date_to)) {
                createInputError(permitfact_permit_date_from, "Please enter both Issue Date From and To.");
                createInputError(permitfact_permit_date_to, "Please enter both Issue Date From and To.");
                return false;
            }
        }

        if (hasEntryDate) {
            if (isBlank(permitfact_entry_date_from) || isBlank(permitfact_entry_date_to)) {
                createInputError(permitfact_entry_date_from, "Please enter both Entry Date From and To.");
                createInputError(permitfact_entry_date_to, "Please enter both Entry Date From and To.");
                return false;
            }
        }

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

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

        let startDate = new Date(permitfact_permit_date_from.val()),
                endDate = new Date(permitfact_permit_date_to.val());

        if (startDate > endDate) {
            createInputError(permitfact_permit_date_from, "Date is after End Date");
            return false;
        }

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

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

        let startDate2 = new Date(permitfact_entry_date_from.val()),
                endDate2 = new Date(permitfact_entry_date_to.val());

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

        e.preventDefault();

        $sessionStorage.action = "PermitFacts.searchPermitFacts";
        $sessionStorage.pagination = "first";

        $sessionStorage.permitfact_company = permitfact_company;
        $sessionStorage.permitfact_project_name = permitfact_project_name;
        $sessionStorage.permitfact_project_zip = permitfact_project_zip;
        $sessionStorage.permitfact_project_city = permitfact_project_city;
        $sessionStorage.permitfact_county = permitfact_county;
        $sessionStorage.permitfact_project_type = permitfact_project_type;
        $sessionStorage.permitfact_work_type = permitfact_work_type;
        $sessionStorage.permitfact_building_type = permitfact_building_type;
        $sessionStorage.permitfact_size_from = permitfact_size_from.val();
        $sessionStorage.permitfact_size_to = permitfact_size_to.val();
        $sessionStorage.permitfact_value_from = permitfact_value_from.val();
        $sessionStorage.permitfact_value_to = permitfact_value_to.val();
        $sessionStorage.permitfact_permit_date_from = permitfact_permit_date_from.val();
        $sessionStorage.permitfact_permit_date_to = permitfact_permit_date_to.val();
        $sessionStorage.permitfact_entry_date_from = permitfact_entry_date_from.val();
        $sessionStorage.permitfact_entry_date_to = permitfact_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
}
