
// ==============
// Business Facts
// ==============

$(document).ready(function () {

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

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

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

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

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

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

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

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

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

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

    $("#businessfact_lease_end_to").datepicker({format: "mm-dd-yyyy",
        container: "div.lease-end-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();
        $("#businessfact_entry_date_from").focus().datepicker("show");
    });
    $(".btnEntryDateToCalendar").on("click", function (e) {
        e.preventDefault();
        $("#businessfact_entry_date_to").focus().datepicker("show");
    });

    $(".btnLeaseEndDateFromCalendar").on("click", function (e) {
        e.preventDefault();
        $("#businessfact_lease_end_from").focus().datepicker("show");
    });
    $(".btnLeaseEndDateToCalendar").on("click", function (e) {
        e.preventDefault();
        $("#businessfact_lease_end_to").focus().datepicker("show");
    });

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

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

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

        $sessionStorage.businessfacts_per_page = $(this).val();
        $sessionStorage.action = "BusinessFacts.searchBusinessFacts";
        $sessionStorage.pagination = "first";

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

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

        formSubmit($sessionStorage);

    });

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

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

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

    // -----------------------
    // Filter the Business Cards
    // -----------------------

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

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

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

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

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

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

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

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

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

        $sessionStorage.action = "Export_BusinessFactsToCSV.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 Business Facts - PDF
    // --------------------------

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

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

        $sessionStorage.action = "Print_BusinessFactsPDF.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();
        $("#searchBusinessFacts").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($('#searchBusinessFacts'));

        $sessionStorage = clearSubscriptionSessionVariableFilters($sessionStorage);

        $sessionStorage.action = "BusinessFacts.searchBusinessFacts";

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

        formSubmit($sessionStorage);

    });

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

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

        var businessfact_company = $("#businessfact_company").val(),
                businessfact_zip = $("#businessfact_zip").val(),
                businessfact_city = $("#businessfact_city").val(),
                businessfact_county = $("#businessfact_county").val(),
                businessfact_business_class = $("#businessfact_business_class").val(),
                businessfact_action = $("#businessfact_action").val(),
                businessfact_sic_code = $("#businessfact_sic_code").val(),
                businessfact_home_based_business = $("#businessfact_home_based_business").val(),
                businessfact_employee_count_from = $("#businessfact_employee_count_from"),
                businessfact_employee_count_to = $("#businessfact_employee_count_to"),
                businessfact_entry_date_from = $("#businessfact_entry_date_from"),
                businessfact_entry_date_to = $("#businessfact_entry_date_to"),
                businessfact_lease_end_from = $("#businessfact_lease_end_from"),
                businessfact_lease_end_to = $("#businessfact_lease_end_to");

        clearInputErrors();

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

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

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

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

        let startDate = new Date(businessfact_entry_date_from.val()),
                endDate = new Date(businessfact_entry_date_to.val());

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

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

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

        let lease_startDate = new Date(businessfact_lease_end_from.val()),
                lease_endDate = new Date(businessfact_lease_end_to.val());

        if (lease_startDate > lease_endDate) {
            createInputError(businessfact_lease_end_from, "Start Date is after End Date");
            return false;
        }

        e.preventDefault();

        $sessionStorage.action = "BusinessFacts.searchBusinessFacts";
        $sessionStorage.pagination = "first";

        $sessionStorage.businessfact_company = businessfact_company;
        $sessionStorage.businessfact_zip = businessfact_zip;
        $sessionStorage.businessfact_city = businessfact_city;
        $sessionStorage.businessfact_county = businessfact_county;
        $sessionStorage.businessfact_business_class = businessfact_business_class;
        $sessionStorage.businessfact_action = businessfact_action;
        $sessionStorage.businessfact_sic_code = businessfact_sic_code;
        $sessionStorage.businessfact_home_based_business = businessfact_home_based_business;
        $sessionStorage.businessfact_employee_count_from = businessfact_employee_count_from.val();
        $sessionStorage.businessfact_employee_count_to = businessfact_employee_count_to.val();
        $sessionStorage.businessfact_entry_date_from = businessfact_entry_date_from.val();
        $sessionStorage.businessfact_entry_date_to = businessfact_entry_date_to.val();

        if (businessfact_lease_end_from.length) {
            $sessionStorage.businessfact_lease_end_from = businessfact_lease_end_from.val();
            $sessionStorage.businessfact_lease_end_to = businessfact_lease_end_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=hidden]):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 and multiple selects
    $form.find('select').each(function () {
        $(this).val($(this).prop('multiple') ? [] : '').trigger('change');
    });

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

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

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
}
