
// =============================
// Search Permits By Subdivision
// =============================

$(document).ready(function () {

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

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

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

    // --------------------
    // Initialize Dropdowns
    // --------------------

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

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

    $(".date-mask").inputmask({alias: "datetime",
        inputFormat: "mm/dd/yyyy",
        placeholder: "MM/DD/YYYY",
        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
    // ------------

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

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

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

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

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

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

        e.preventDefault();

        $("#permit_entry_start_date").focus().datepicker("show");

    });

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

        e.preventDefault();

        $("#permit_entry_end_date").focus().datepicker("show");

    });

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

        e.preventDefault();

        $("#permit_permit_start_date").focus().datepicker("show");

    });

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

        e.preventDefault();

        $("#permit_permit_end_date").focus().datepicker("show");

    });

    // ----------------
    // Filter the Rows.
    // ----------------

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

        var filter = $(this).val().toLowerCase();

        $(".permit-row").hide().filter(function () {
            return $(this).find(".filterable").text().toLowerCase().indexOf(filter) > -1;
        }).show();

        if ($(".permit-row:visible").length === 0) {
            $("#permits-table thead").hide();
            $(".filter-error").removeClass("d-none");
        } else {
            $("#permits-table thead").show();
            $(".filter-error").addClass("d-none");
        }

    });

    // -------------------
    // Clear Filter Button
    // -------------------

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

        $("#filter").val("").trigger("change");

        $sessionStorage.action = "PermitsBySubdivision.searchPermits";
        $sessionStorage.pagination = "first";

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

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

        formSubmit($sessionStorage);

    });

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

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

        $sessionStorage.permits_per_page = $(this).val();
        $sessionStorage.action = "PermitsBySubdivision.searchPermits";
        $sessionStorage.pagination = "first";

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

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

        formSubmit($sessionStorage);

    });


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

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

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

    });

    // ====================
    // Autocomplete Searches
    // ====================

    let subdivisionSearchTimer = null;

    $(".subdivision-autocomplete").on("keyup", function () {

        clearTimeout(subdivisionSearchTimer);

        let $input = $(this);
        let searchValue = $input.val().trim();

        // optional: don't search until 2+ chars
        if (searchValue.length < 2) {
            $(".subdivision-results").empty().hide();
            return;
        }

        subdivisionSearchTimer = setTimeout(function () {

            $.ajax({
                url: "main.php",
                type: "GET",
                dataType: "json",
                data: {
                    Xaction: "PermitsBySubdivision.getAutoCompleteSubdivisions",
                    subscription_serial: $sessionStorage.subscription_serial,
                    permit_sub_div_name: searchValue
                },
                success: function (results) {
                    renderSubdivisionResults(results, $input);

                }
            });

        }, 250);

    });

    $(".city-autocomplete").autoComplete({
        resolverSettings: {
            url: "main.php?Xaction=PermitsBySubdivision.getAutoCompleteCities",
            queryKey: "permit_project_city",
            requestThrottling: 0
        },
        noResultsText: "No Matching Cities Found.",
        bootstrapVersion: "4"

    });

    $(".street-autocomplete").autoComplete({

        resolverSettings: {
            url: "main.php?Xaction=PermitsBySubdivision.getAutoCompleteStreets",
            queryKey: "permit_project_addr",
            requestThrottling: 0
        },
        noResultsText: "No Matching Streets Found.",
        bootstrapVersion: "4"

    });

    // ----------------
    // Display Scollbar
    // ----------------

    $(".scrollable").scroll(function () {
        if ($(this).scrollTop() > 60) {
            $("#btnTop").fadeIn();
        } else {
            $("#btnTop").fadeOut();
        }
    });

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

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

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

    $(".btnReset").on("click", function (e) {
        e.preventDefault();

        $sessionStorage.action = "PermitsBySubdivision.searchPermits";
        $sessionStorage.pagination = $(this).data("pagination");

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

        delete $sessionStorage.pagination;
        delete $sessionStorage.permit_company;
        delete $sessionStorage.permit_county;
        delete $sessionStorage.permit_sub_div_name;
        delete $sessionStorage.permit_project_city;
        delete $sessionStorage.permit_project_addr;
        delete $sessionStorage.permit_and_or;
        delete $sessionStorage.permit_entry_start_date;
        delete $sessionStorage.permit_entry_end_date;
        delete $sessionStorage.permit_permit_start_date;
        delete $sessionStorage.permit_permit_end_date;

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

        formSubmit($sessionStorage);
    });

    // -------------
    // Cancel Button
    // -------------

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

        $sessionStorage.action = $sessionStorage.userSubscriptions || "";

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

        formSubmit($sessionStorage);

    });

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

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

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

        var permit_county = $("#permit_county"),
                permit_and_or = $("#permit_and_or"),
                permit_company = $("#permit_company"),
                permit_sub_div_name = $("#permit_sub_div_name"),
                permit_project_city = $("#permit_project_city"),
                permit_project_addr = $("#permit_project_addr"),
                permit_entry_start_date = $("#permit_entry_start_date"),
                permit_entry_end_date = $("#permit_entry_end_date"),
                permit_permit_start_date = $("#permit_permit_start_date"),
                permit_permit_end_date = $("#permit_permit_end_date"),
                form_error = $("#search-form-error");

        clearInputErrors();

        // Function to display errors and hide spinner
        function showError(message, element) {
            $("#spinner-dialog").modal("hide");
            createInputError(form_error, message);
            if (element)
                createInputError(element, "");
            return false;
        }

        // Validate required fields
        if ([permit_county, permit_company, permit_sub_div_name, permit_project_city, permit_project_addr, permit_entry_start_date, permit_entry_end_date, permit_permit_start_date, permit_permit_end_date].every(isBlank)) {
            return showError("Please provide a search criteria.");
        }

        if (isBlank(permit_entry_start_date) && !isBlank(permit_entry_end_date)) {
            return showError("Please provide an Entry From Date for range.", permit_entry_start_date);
        }

        if (isBlank(permit_permit_start_date) && !isBlank(permit_permit_end_date)) {
            return showError("Please provide a Permit From Date for range.", permit_permit_start_date);
        }

        // Validate date ranges
        if (permit_entry_end_date.val() && !checkEndingDate(permit_entry_start_date, permit_entry_end_date)) {
            return showError("Start Date must be prior to End Date");
        }

        if (permit_permit_end_date.val() && !checkEndingDate(permit_permit_start_date, permit_permit_end_date)) {
            return showError("Start Date must be prior to End Date");
        }

        e.preventDefault();

        $sessionStorage.permit_company = permit_company.val();
        $sessionStorage.permit_county = permit_county.val();
        $sessionStorage.permit_and_or = permit_and_or.val();
        $sessionStorage.permit_sub_div_name = permit_sub_div_name.val();
        $sessionStorage.permit_project_city = permit_project_city.val();
        $sessionStorage.permit_project_addr = permit_project_addr.val();
        $sessionStorage.permit_entry_start_date = permit_entry_start_date.val();
        $sessionStorage.permit_entry_end_date = permit_entry_end_date.val();
        $sessionStorage.permit_permit_start_date = permit_permit_start_date.val();
        $sessionStorage.permit_permit_end_date = permit_permit_end_date.val();

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

        formSubmit($sessionStorage);

    });

    // -------------------
    // Column Heading Sort
    // -------------------

    if (($sessionStorage.permits_order_by || "") !== "") {

        $("th[data-order-by = '" + ($sessionStorage.permits_order_by || "") + "']").append('<i class="' + ($sessionStorage.permits_order_icon || "") + ' text-danger ms-1 me-0"/>');

    }

    $("th.sortable").on("click", function (e) {

        if ($(e.target).data("order-by") !== ($sessionStorage.permits_order_by || "")) {  // New Column

            $sessionStorage.permits_order_by = $(e.target).data("order-by");
            $sessionStorage.permits_order_direction = "asc";
            $sessionStorage.permits_order_icon = "bi bi-arrow-up";

        } else {

            switch ($sessionStorage.permits_order_direction) {

                case "" :

                    $sessionStorage.permits_order_by = $(e.target).data("order-by");
                    $sessionStorage.permits_order_direction = "asc";
                    $sessionStorage.permits_order_icon = "bi bi-arrow-up";
                    break;

                case "asc" :

                    $sessionStorage.permits_order_by = $(e.target).data("order-by");
                    $sessionStorage.permits_order_direction = "desc";
                    $sessionStorage.permits_order_icon = "bi bi-arrow-down";
                    break;

                case "desc" :

                    $sessionStorage.permits_order_by = "";
                    $sessionStorage.permits_order_direction = "";
                    $sessionStorage.permits_order_icon = "";
                    break;

            }

        }

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

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

        formSubmit($sessionStorage);

    });

    // -----------------
    // Select All Button
    // -----------------

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

        e.preventDefault();

        $(".selection-checkbox:input:checkbox").prop("checked", true);

        $(".btnDeselectAll, .btnExportSelected").removeClass("d-none");

    });

    // -------------------
    // Deselect All Button
    // -------------------

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

        e.preventDefault();

        $(".selection-checkbox:input:checkbox").prop("checked", false);

        $(".btnDeselectAll, .btnExportSelected").addClass("d-none");

    });

    // ------------------------
    // Toggle a Select Checkbox
    // ------------------------

    $(".permit-row").on("click touch", function (e) {

        if (!($(e.target).hasClass("selection-area"))) {
            return false;
        }
        ;

        e.preventDefault();
        e.stopPropagation();

        var $this = $(e.target), checked = ($this.closest("tr").find("input[name='selected[]']").prop("checked"));

        // Toggle the selected Checkbox.

        $this.closest("tr").find("input[name='selected[]']").prop("checked", !checked);

        if ($("input[name='selected[]']:checked").length === 0) {
            $(".btnDeselectAll, .btnExportSelected").addClass("d-none");
        } else {
            $(".btnDeselectAll, .btnExportSelected").removeClass("d-none");
        }

    });

    $("#permits-table tbody tr").on("click touch", function (e) {

        // If the click was on selection area (or the checkbox itself), do nothing
        if ($(e.target).closest(".selection-area, input[name='selected[]'], label").length) {
            return;
        }

        const permit_serial = $(this).data("permit-serial");

        openPermitDialog(getPermitRecordDialog(permit_serial));

    });

//    // ------------------------
//    // Export All Permits - PDF
//    // ------------------------
//
//    $(".btnExportAllPDF").on("click", function (e) {
//
//        e.preventDefault();
//
//        window.open("", "PrintTab");
//
//        $("input[name = 'action']", "#PrintAllPermitsBySubdivisionPDFForm").val("print");
//        $("input[name = 'subscription_serial']", "#PrintAllPermitsBySubdivisionPDFForm").val($sessionStorage.subscription_serial);
//        $("input[name = 'subscription_serial']", "#PrintAllPermitsBySubdivisionPDFForm").val($sessionStorage.subscription_serial);
//        $("#PrintAllPermitsBySubdivisionPDFForm").submit();
//
//    });

    // ------------------------
    // Export All Permits - PDF
    // ------------------------

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

        e.preventDefault();

        const $printForm = $("#PrintAllPermitsBySubdivisionPDFForm");
        const $searchForm = $("#searchPermitsBySubdivision");

        // Remove fields added by a previous PDF export.
        $printForm.find(".print-search-field").remove();

        // Copy populated search criteria into the PDF form.
        $searchForm.find(":input[name]").not(":button, :submit, :reset").not("[name='action']").not("[name='subscription_serial']").each(function () {

            const $input = $(this);
            const fieldName = $input.attr("name");

            // Ignore unchecked checkboxes and radio buttons.
            if (($input.is(":checkbox") || $input.is(":radio")) && !$input.is(":checked")) {
                return;
            }

            let values = $input.val();

            if (values === null || values === undefined) {
                return;
            }

            // Supports multiple-select inputs.
            if (!Array.isArray(values)) {
                values = [values];
            }

            $.each(values, function (_, value) {

                value = String(value).trim();

                if (value === "") {
                    return;
                }

                $("<input>", {type: "hidden", name: fieldName, value: value, class: "print-search-field"}).appendTo($printForm);
            });
        });

        $printForm.find("[name='action']").val("print");
        $printForm.find("[name='subscription_serial']").val($sessionStorage.subscription_serial);

        window.open("", "PrintTab");
        $printForm.trigger("submit");
    });



    // --------------------------
    // Export All Permits - Excel
    // --------------------------

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

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

        $sessionStorage.action = "Export_AllPermitsBySubdivision_Excel.export";
        $sessionStorage.subscription_reference = $sessionStorage.subscription_serial;
        $sessionStorage.downloadReturn = "Reports.selectReport";

        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 Permits - CSV
    // ------------------------

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

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

        $sessionStorage.action = "Export_AllPermitsBySubdivision_CSV.export";
        $sessionStorage.subscription_reference = $sessionStorage.subscription_serial;

        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 Selected Permits Button
    // -----------------------------

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

        e.preventDefault();

        window.open("", "PrintTab");

        var selected = $("input[name='selected[]']:checked").map(function () {
            return $(this).val();
        }).get();

        $("input[name = 'action']", "#PrintSelectedPermitsBySubdivisionForm").val("print");
        $("input[name = 'selected_permits']", "#PrintSelectedPermitsBySubdivisionForm").val(selected);
        $("input[name = 'subscription_serial']", "#PrintSelectedPermitsBySubdivisionForm").val($sessionStorage.subscription_serial);
        $("#PrintSelectedPermitsBySubdivisionForm").submit();

    });

    // -----------------------------
    // Export Selected Permits - CSV
    // -----------------------------

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

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

        var selected = $("input[name='selected[]']:checked").map(function () {
            return $(this).val();
        }).get();

        console.log(selected);

        $sessionStorage.action = "Export_SelectedPermitsBySubdivision_CSV.export";
        $sessionStorage.selected_permits = selected;
        $sessionStorage.subscription_reference = $sessionStorage.subscription_serial;

        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 Selected Permits - Excel
    // -------------------------------

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

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

        var selected = $("input[name='selected[]']:checked").map(function () {
            return $(this).val();
        }).get();

        console.log(selected);

        $sessionStorage.action = "Export_SelectedPermitsBySubdivision_Excel.export";
        $sessionStorage.subscription_reference = $sessionStorage.subscription_serial;
        $sessionStorage.selected_permits = selected;

        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
    });

    // -------------------
    // Save Changed Inputs
    // -------------------

    $(".autosave").on("change", function (e) {

        switch (e.target.type) {

            case "text"       :
                $sessionStorage[e.target.name] = $(this).val();
                break;
            case "radio"      :
                $sessionStorage[e.target.name] = $(this).val();
                break;
            case "checkbox"   :
                $sessionStorage[e.target.name] = $(this).prop("checked");
                break;
            case "select-one" :
                $sessionStorage[e.target.name] = $(this).val();
                break;
            case "hidden"     :
                $sessionStorage[e.target.name] = $(this).val();
                break;

            default           :
                $sessionStorage[e.target.name] = $(this).val();
                break;

        }

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

    });

    // ----------------
    // Initalize Inputs
    // ----------------

    $.each($sessionStorage, function (name, value) {

        var $input = $(":input").filter("[name='" + name + "']");

        if ($input.length > 0) {

            switch ($input.prop("type")) {

                case "text"       :
                    $input.val(value);
                    break;
                case "radio"      :
                    $input.filter("[value=" + value + "]").prop("checked", true);
                    break;
                case "checkbox"   :
                    $input.prop("checked", value);
                    break;
                case "select-one" :
                    $input.val(value);
                    break;
                case "hidden"     :
                    $input.val(value);
                    break;

                default           :
                    $input.val(value);
                    break;

            }

        }

    });

    // ------------------
    // Save preset Inputs
    // ------------------

    $("input[type=radio]:checked").trigger("change");

    // -----------------
    // Per Page Dropdown
    // -----------------

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

        $(".btnFind").trigger("click");

    });

});

function openPermitDialog(modalHtml) {
    const $modal = $(modalHtml);

    // Remove any existing instance
    $("#permit-details-dialog").remove();

    $("body").append($modal);

    const modal = new bootstrap.Modal(
            document.getElementById("permit-details-dialog"),
            {backdrop: "static", keyboard: false}
    );

    modal.show();
}


// -------------------------------------
// Returns Modal with Permit Record Data
// -------------------------------------

function getPermitRecordDialog(permit_serial) {

    var dialog = null;

    $.ajax({
        url: "main.php?Xaction=PermitsBySubdivision.getPermitRecordDialog",
        type: "POST",
        async: false,
        data: {permit_serial: permit_serial},
        dataType: "html",
        success: function (result) {
            dialog = result;
        }
    });

    return dialog;

}

function renderSubdivisionResults(results, $input) {

    let $dropdown = $(".subdivision-results");

    if (!$dropdown.length) {
        $dropdown = $("<div class='subdivision-results dropdown-menu show w-100'></div>");
        $input.closest(".subdivision-wrapper").append($dropdown);
    }

    $dropdown.empty();

    if (!results.length) {
        $dropdown.append("<span class='dropdown-item text-muted'>No Matching Subdivisions Found</span>");
        return;
    }

    results.forEach(function (item) {

        let $option = $("<button type='button' class='dropdown-item'></button>").text(item);

        $option.on("click", function () {
            $input.val(item);
            $dropdown.hide();
        });

        $dropdown.append($option);

    });

    $dropdown.show();
}