Subversion Repositories SmartDukaan

Rev

Rev 37050 | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

$(function () {
    $(document).on('click', ".lead", function () {
        loadLead("main-content");
    });

    $(document).on('click', ".team-commitment", function () {
        loadTeamCommitment("main-content");
    });


    $(document).on('click', ".partner-health", function () {
        loadPartnerHealth("main-content");
    });

    $(document).on('click', ".lead-detail", function () {
        loadLeadDetail("main-content");
    });


    $(document).on('click', ".submitCommitment",
        function () {
            var startDateTime = getDatesFromPicker('input[name="commitmentDate"]').startDate;
            doGetAjaxRequestHandler(context + "/getTeamCommitment?date="
                + startDateTime, function (response) {
                $('.teamcommitmentcontainer').html(response);

            });
        });


    $(document).on('click', ".submitDateWiseLead", function () {

        var startDate = $("#startDate").val();
        var endDate = $("#endDate").val();
        var status = $("#statusFilter").val();
        var color = $("#colorFilter").val();

        if (color == null) {
            color = "";
        }

        if (startDate && endDate) {
            var start = new Date(startDate);
            var end = new Date(endDate);
            if (end < start) {
                alert("End date must be after start date");
                return;
            }
        }

        doGetAjaxRequestHandler(context + "/getOpenLead?leadStatus=" + status + "&color=" + color + "&startDate=" + startDate + "&endDate=" + endDate, function (response) {
            $('#' + 'main-content').html(response);
        });


    })
    ;$(document).on('click', ".downloadDateWiseLead", function () {

        var startDate = $("#startDate").val();
        var endDate = $("#endDate").val();
        var status = $("#statusFilter").val();
        var color = $("#colorFilter").val();

        if (color == null) {
            color = "";
        }

        if (startDate && endDate) {
            var start = new Date(startDate);
            var end = new Date(endDate);
            if (end < start) {
                alert("End date must be after start date");
                return;
            }
        }

        let endPoint = `${context}/downloadDateWiseLead?leadStatus=${status}&color=${color}&startDate=${startDate}&endDate=${endDate}`;
        window.location.href = endPoint;

    });

    // Lead-table Search boxes (top DataTables box + bottom mirror below the table/pagination) =
    // GLOBAL partner search: matches ANY lead by name / mobile / outlet / city across ALL statuses
    // and ALL dates (this year, last year, anytime) - not just the loaded date-scoped rows. It
    // searches AS YOU TYPE (debounced) so old partners surface without needing to press Enter;
    // Enter still triggers an immediate search. Results render into #global-search-results above
    // the date-scoped table; the view auto-scrolls there so a search from the bottom box is visible
    // without the user having to scroll back up manually.
    var LEAD_SEARCH_BOXES = "#lead-table_filter input, #lead-table-bottom-filter";
    var leadGlobalSearchTimer = null;

    function clearInjectedGlobalRows() {
        if ($.fn.dataTable.isDataTable('#lead-table')) {
            $('#lead-table').DataTable()
                .rows('.global-search-row')
                .remove()
                .draw(false);
        }
    }

    // Exposed so handlers outside the $(function () { ... }) scope (e.g. #vrSendBtn) can
    // refresh the search view after they mutate a lead.
    window.runGlobalLeadSearch = function (term) {
        runGlobalLeadSearch(term);
    };

    function runGlobalLeadSearch(term) {
        term = $.trim(term || "");
        if (term.length < 2) {
            $('#global-search-results').html("");
            clearInjectedGlobalRows();
            return;
        }
        var safeTerm = $('<div>').text(term).html();
        doGetAjaxRequestHandler(context + "/globalLeadSearch?searchTerm=" + encodeURIComponent(term),
            function (response) {
                $('#global-search-results').html(
                    '<h4 style="margin:15px 0 8px;">Search results — all partners, any date '
                    + '<small class="text-muted">(matching "' + safeTerm + '")</small></h4>' + response);
                var resultsEl = document.getElementById('global-search-results');
                if (resultsEl) {
                    resultsEl.scrollIntoView({behavior: 'smooth', block: 'start'});
                }

                // Mirror the hits into the main #lead-table so the same row is findable there too.
                // Rows carry class .global-search-row so we can clear them on the next search.
                clearInjectedGlobalRows();
                var $hiddenRows = $('#global-search-main-rows tbody tr');
                if ($hiddenRows.length && $.fn.dataTable.isDataTable('#lead-table')) {
                    var dt = $('#lead-table').DataTable();
                    // Collect lead ids already in the main table (from the initial date-scoped
                    // render) so we don't inject a duplicate row for the same lead.
                    var existingIds = {};
                    dt.rows().nodes().to$().each(function () {
                        var id = $(this).attr('data');
                        if (id) existingIds[id] = true;
                    });
                    $hiddenRows.each(function () {
                        var id = $(this).attr('data');
                        if (id && existingIds[id]) return;
                        dt.row.add(this);
                    });
                    dt.draw(false);
                }
            });
    }

    $(document).on('keydown', LEAD_SEARCH_BOXES, function (e) {
        if (e.which === 13) {
            e.preventDefault();
            clearTimeout(leadGlobalSearchTimer);
            runGlobalLeadSearch($(this).val());
        }
    });

    $(document).on('input', LEAD_SEARCH_BOXES, function () {
        var term = $(this).val();
        clearTimeout(leadGlobalSearchTimer);
        leadGlobalSearchTimer = setTimeout(function () {
            runGlobalLeadSearch(term);
        }, 350);
    });

    // Bottom box isn't a native DataTables filter element, so mirror it into the DataTable's own
    // search + keep both boxes showing the same value regardless of which one the user typed into.
    $(document).on('keyup input', '#lead-table-bottom-filter', function () {
        var term = $(this).val();
        $('#lead-table_filter input').val(term);
        if ($.fn.dataTable.isDataTable('#lead-table')) {
            $('#lead-table').DataTable().search(term).draw();
        }
    });

    $(document).on('keyup input', '#lead-table_filter input', function () {
        $('#lead-table-bottom-filter').val($(this).val());
    });


    $(document).on('click', ".visit-request-plan", function () {

        doGetAjaxRequestHandler(context + "/visitPlan", function (response) {
            $('#' + 'main-content').html(response);
        });

    });

    $(document).on('click', ".visitPlan", function () {

        let dateWisePlan = $("#dateVisitSearch").val();

        doGetAjaxRequestHandler(context + "/visit/getVisitPlan?date=" + dateWisePlan, function (response) {
            $('#' + 'main-content').html(response);
        });

    });

    $(document).on('click', ".lead-close", function () {
        loadClosedLead("main-content");
    });

    $(document).on('click', "#lead-close-paginated .next",
        function () {

            var searchText = $("#authUser").val();
            // var searchTxt=$("#scheme-search-text").val();
            console.log(searchText);
            if (typeof (searchText) == "undefined" || !searchText) {
                searchText = "";
            }

            if ((searchText)) {
                var params = {};
                params['searchTerm'] = searchText;
                loadPaginatedNextItems('/searchLeadPaginated', params,
                    'lead-close-paginated', 'close-lead-table',
                    'lead-close-container');
            } else {

                loadPaginatedNextItems('/getPaginatedClosedLeads', null,
                    'lead-close-paginated', 'close-lead-table',
                    'lead-close-container');
            }
            $(this).blur();
        });

    $(document).on('click', "#lead-close-paginated .previous",
        function () {
            var searchText = $("#authUser").val();
            // var searchTxt=$("#scheme-search-text").val();
            console.log(searchText);
            if (typeof (searchText) == "undefined" || !searchText) {
                searchText = "";
            }

            if ((searchText)) {
                var params = {};
                params['searchTerm'] = searchText;
                loadPaginatedPreviousItems('/searchLeadPaginated', params,
                    'lead-close-paginated', 'close-lead-table',
                    'lead-close-container');
            } else {
                loadPaginatedPreviousItems('/getPaginatedClosedLeads',
                    null, 'lead-close-paginated', 'close-lead-table',
                    'lead-close-container');
            }
            $(this).blur();
        });

    $(document).on('click', "#close-lead-search-button", function () {
        var searchText = $("#authUser").val();
        if (typeof (searchText) == "undefined" || !searchText) {
            searchText = "";
        }
        loadLeadSearchInfo(searchText);
    });

    $(document).on("keyup", "#authUser", function (e) {
        var keyCode = e.keyCode || e.which;
        if (keyCode == 13) {
            $("#close-lead-search-button").click();
        }
    });
    $(document).on('click', ".view",
        function () {
            var id = $(this).data('requestid');
            console.log(id);
            doGetAjaxRequestHandler(context + "/getLeadActivity?leadId="
                + id, function (response) {

                console.log(response)

                $('#fetchLeadActivityData .modal-content').html(response);

            });
        });

    $(document).on('click', ".newLead", function () {
        $('#newEntryLeadModal').modal('show');
        $("#scheduleTime").hide();
    });

    $(document).on('click', ".show-lead", function () {
        var status = $("#statusFilter").val();
        doGetAjaxRequestHandler(context + "/getOpenLead?leadStatus=" + status, function (response) {
            $('#' + 'main-content').html(response);
        });
    });


    $(document).on('click', ".show-colowise-lead", function () {
        var status = $("#statusFilter").val();
        var color = $("#colorFilter").val();
        doGetAjaxRequestHandler(context + "/getOpenLead?leadStatus=" + status + "&color=" + color, function (response) {
            $('#' + 'main-content').html(response);
        });
    });

    $(document).on('click', "#uploadIvoryLead", function () {

        window.location.href = context + "/downloadIvoryLead";
    });

    $(document).on('click', ".submitLeadGenerate", function () {

        console.log("hello");
        if (confirm('Confirm upload ?')) {
            var fileSelector = $(this)[0];
            if (fileSelector != undefined) {
                var url = `${context}/csvFileAndSetLead`;
                console.log(url);
                var file = $(".fileLeadGenerate")[0].files[0];
                let fileInput = $(this);
                console.log("file" + file);
                console.log("fileInput" + fileInput);
                doAjaxUploadRequestHandler(
                    url,
                    'POST',
                    file, function (response) {

                        console.log("reponse" + response);

                        if (response == true) {
                            alert("successfully uploaded");


                        }
                    });

            }
        } else {
            // Do nothing!
        }
    });


    $(document).on('click', ".lead-request",
        function () {

            var firstName = $('input[name="firstName"]').val();
            var lastName = $('input[name="lastName"]').val();
            var mobile = $('input[name="mobile"]').val();
            var address = $('input[name="address"]').val();
            var status = $("#status").val();
            var city = $('input[name="city"]').val();
            var state = $("#state").val();
            var remark = $("#createRemark").val();
            var assignTo = $("#createAssignTo").val();
            var source = $("#leadSource").val();
            var communicationType = $("#communicationTye").val();

            var conversionprobability = $("#conversionprobabilit").val();


            var outletName = $('input[name="leadoutletName"]').val();
            var counterSize = $('input[name="leadcounterSize"]').val();
            var table = document.getElementById('brandtable');
            var brandValueJson = [];
            var leadBrands;

            console.log(conversionprobability)


            if (firstName === "" && lastName === "" && mobile === ""
                && address === "" && status === "" && city === ""
                && state === "" && remark === "" && source === "") {
                alert("Field can't be empty");
                return;
            }


            if (firstName === "") {
                alert("First Name is required");
                return;
            }
            if (lastName === "") {
                alert("Last Name is required");
                return;
            }
            if (mobile === "") {
                alert("Mobile is required");
                return;
            }
            if (status === "") {
                alert("Status is required");
                return;
            }
            if (address === "") {
                alert("address is required");
                return;
            }
            if (city === "") {
                alert("city is required");
                return;
            }

            if (state === "") {
                alert("state is required");
                return;
            }
            if (source === "") {
                alert("Source is required")
                return;
            }

            if (remark === "") {
                alert("Remark is required");
                return;
            }

            if (conversionprobability === "") {
                alert("Conversion Probability is required");
                return;
            }
            if (status == "followUp" || status == "pending" || status == "finalized") {
                if (outletName === "") {
                    alert("Outlet Name is required");
                    return;
                }

                if (counterSize === "") {
                    alert("Counter Size is required");
                    return;
                }

                if (localStorage.getItem("frontph") == "undefined" && localStorage.getItem("frontph") == null) {
                    alert("Front Document is required");
                    return;
                }

                if (localStorage.getItem("internalMarketh") == "undefined" || localStorage.getItem("internalMarketh") == null) {
                    alert("Front With Market Document is required");
                    return;
                }

                if (localStorage.getItem("leftShoth") == "undefined" || localStorage.getItem("leftShoth") == null) {
                    alert("Internal Left Shot Document is required");
                    return;
                }

                if (localStorage.getItem("leftWallh") == "undefined" || localStorage.getItem("leftWallh") == null) {
                    alert("Internal Left Wall Document is required");
                    return;
                }


                if (localStorage.getItem("rightWallh") == "undefined" || localStorage.getItem("rightWallh") == null) {
                    alert("Internal Right Wall Document is required");
                    return;
                }


                for (i = 1; i < table.rows.length; i++) {

                    var objCells = table.rows[i].cells;

                    leadBrands = {
                        brand: objCells[0].innerText,
                        value: objCells[1].getElementsByTagName('input')[0].value
                    }
                    brandValueJson.push(leadBrands);
                }


            }


            var leaddetailData = {}
            leaddetailData['firstName'] = firstName;
            leaddetailData['lastName'] = lastName
            leaddetailData['mobile'] = mobile
            leaddetailData['address'] = address
            leaddetailData['city'] = city
            leaddetailData['state'] = state
            leaddetailData['status'] = status
            leaddetailData['remark'] = remark
            leaddetailData['assignTo'] = assignTo
            leaddetailData['source'] = source
            leaddetailData['colorCheck'] = conversionprobability


            if (status == "followUp") {
                leaddetailData['schelduleTimestamp'] = getDatesFromPicker('#scheduleTime').startDate;

                leaddetailData['communicationType'] = communicationType
            }


            leaddetailData['outletName'] = outletName;

            leaddetailData['counterSize'] = counterSize;


            leaddetailData['leadBrands'] = brandValueJson;

            console.log(localStorage.getItem("frontp"));


            leaddetailData['frontp'] = localStorage
                .getItem("frontph");


            leaddetailData['frontWithMarket'] = localStorage
                .getItem("internalMarketh");


            leaddetailData['internalLongShot'] = localStorage
                .getItem("leftShoth");


            leaddetailData['internalLeftWall'] = localStorage
                .getItem("leftWallh");


            leaddetailData['internalRightWall'] = localStorage
                .getItem("rightWallh");

            console.log(leaddetailData);

            if (confirm("Are you sure you want to add lead!") == true) {
                doPostAjaxRequestWithJsonHandler(context + "/createLead",
                    JSON.stringify(leaddetailData), function (response) {
                        if (response == 'true') {
                            alert("successfully Add");
                            $('#newEntryLeadModal').modal('hide');
                            $('.modal-backdrop').remove();
                            loadLead("main-content");
                        } else {
                            alert(response);
                        }
                    });

                return false;
            }
        });
    window.leadId = null;
    var row = null;
    // Turn Assign To into a search-select. We attempt initialisation at 3 points to be
    // robust against ordering / DOM-timing issues:
    //   1. Immediately at load time (element is in DOM per lead.vm)
    //   2. On the modal's shown.bs.modal event (post-transition)
    //   3. As a fallback in the click handler with a small delay
    function initAssignToSelect2() {
        if (!$.fn.select2) {
            console.warn('[lead.js] select2 not loaded — falling back to native <select>');
            return;
        }
        var $assign = $('#assignTo');
        if ($assign.length === 0) return;
        if ($assign.hasClass('select2-hidden-accessible')) return; // already applied
        $assign.select2({
            placeholder: 'Assign To',
            allowClear: true,
            width: '100%',
            dropdownParent: $('#editLeadData'),
            // Hide disabled options — VISIT/TELEPHONIC filter uses .prop('disabled', true).
            matcher: function (params, data) {
                if (data.element && $(data.element).prop('disabled')) return null;
                if (!params.term || $.trim(params.term) === '') return data;
                if (data.text && data.text.toLowerCase().indexOf(params.term.toLowerCase()) > -1) return data;
                return null;
            }
        });
        console.log('[lead.js] select2 applied to #assignTo');
    }

    initAssignToSelect2();
    $(document).on('shown.bs.modal', '#editLeadData', initAssignToSelect2);

    $(document).on('click', ".editLead", function () {
        $('#editLeadData').modal('show');
        // Belt-and-braces: also try after the modal transition completes.
        setTimeout(initAssignToSelect2, 300);

        $("#remark").val("");
        $("#assignTo").val("").trigger('change');
        $("#editStatus").val("");
        $("#reason").val("");
        $("#editCity").val("");
        $("#editState").val("");
        $("#editSource").val("");
        $("#editScheduleTime").hide();


        localStorage.removeItem("frontph");
        localStorage.removeItem("leftShoth");
        localStorage.removeItem("rightWallh");
        localStorage.removeItem("leftWallh");
        localStorage.removeItem("internalMarketh");

        row = $(this).closest("tr");
        leadId = $(this).data('leadid');

        doAjaxRequestHandler(
            context + "/getLeadDetailByLeadId?leadId=" + leadId,
            "GET",
            function (response) {

                var data = response.response;
                if (!data) return;
                console.log(data);
                $("#editCity").val(data.city);
                $("#editState").val(data.state);
                $("input[name='outletName']").val(data.outletName);
                $("input[name='counterSize']").val(data.counterSize);
            }
        );
    });


    $(document).on('click', ".lead-edit-request",
        function () {

            // Gate the assign/status submit on approved geo. Modal stays open so the
            // user can still work the other sub-forms (lead detail, etc.).
            var clickedBtn = $(this);
            // notInterested is a close-out — no geo / no beat / no assignee
            // needed. Skip the geo gate and submit straight through with just
            // the activity (status + reason + remark).
            var currentStatus = $('#editStatus').val();
            if (currentStatus === 'notInterested') {
                submitLeadEdit();
                return;
            }
            // Non-sales assignees (BGC / other internal hand-offs) don't need
            // geo or a beat-day — the lead just routes to their queue. Skip the
            // geo gate and submit straight through, same as the legacy flow.
            var assigneeId = parseInt($('#assignTo').val(), 10);
            var isSalesAssignee = !isNaN(assigneeId)
                && typeof salesUserIds !== 'undefined'
                && salesUserIds.indexOf(assigneeId) !== -1;
            if (!isSalesAssignee) {
                submitLeadEdit();
                return;
            }
            if (clickedBtn.data('geoChecking')) return;
            clickedBtn.data('geoChecking', true);
            doAjaxRequestHandler(
                context + "/lead-geo/check/" + leadId,
                "GET",
                function (response) {
                    clickedBtn.removeData('geoChecking');
                    var hasGeo = response && response.response && response.response.hasApprovedGeo;
                    if (!hasGeo) {
                        alert('Live geo-location for this lead has not been approved yet. Please approve the geo-location before assigning / updating status.');
                        return;
                    }
                    submitLeadEdit();
                }
            );
        });

    function submitLeadEdit() {

            console.log(row);
            var remark = $('input[name="remark"]').val();
            var assignTo = $("#assignTo").val();
            var editStatus = $("#editStatus").val();
            var city = $('input[name="editCity"]').val();
            var state = $("#editState").val();
            var reason = $("#reason").val();

            var startDate = $("#startDate").val();
            var endDate = $("#endDate").val();
            var leadStatus = $("#statusFilter").val();
            var color = $("#colorFilter").val();
            var communicationType = $("#communicationType").val();

            var conversionprobability = $("#conversionprobability").val();
            var editSource = $("#editSource").val();

            console.log(conversionprobability)


            console.log(startDate)
            console.log(leadStatus)

            console.log(color)
            console.log(reason)

            if (remark === "" && assignTo === "" && editStatus === "") {
                alert("All fields is required");
                return;
            }

        // For notInterested (close-out) the lead doesn't need an assignee
        // — it's just a status + reason + remark write. Only enforce
        // assignTo for the other statuses where scheduling matters.
        if (assignTo === "" && editStatus !== "notInterested") {
                alert("assignTo is required");
                return;
            }

            if (remark === "") {
                alert("Remark is required");
                return;
            }


            if (editStatus === "") {
                alert("status is required");
                return;
            }

            if (editStatus === "notInterested") {
                if (reason == null || reason === "") {
                    alert("Reason  is required");
                    return;
                }
            }
            var leadActivityData = {}
            leadActivityData['id'] = leadId;
            leadActivityData['remark'] = remark;
            leadActivityData['assignTo'] = assignTo
            leadActivityData['status'] = editStatus
            leadActivityData['reason'] = reason
            leadActivityData['colorCheck'] = (conversionprobability === "true" || conversionprobability === true)
            if (city && city.trim() !== "") {
                leadActivityData.city = city;
            }

            if (state && state.trim() !== "") {
                leadActivityData.state = state;
            }

            if (editSource && editSource.trim() !== "") {
                leadActivityData.source = editSource;
            }


            if (editStatus == "followUp") {
                leadActivityData['communicationType'] = communicationType
                var assigneeIdForBeat = parseInt(assignTo, 10);
                var isSalesAssigneeForBeat = !isNaN(assigneeIdForBeat)
                    && typeof salesUserIds !== 'undefined'
                    && salesUserIds.indexOf(assigneeIdForBeat) !== -1;
                var beatVal = $('#beatDate').val();
                // Beat-day gate only applies to sales assignees. Non-sales
                // (BGC / other) hand-offs are just routed to the user's queue
                // without a beat attachment — same as the legacy flow.
                if (isSalesAssigneeForBeat) {
                    if (!beatVal) {
                        var hasBadges = $('#beatBadges .beat-badge').length > 0;
                        if (!hasBadges) {
                            alert('No upcoming beat is available for this assignee. Cannot schedule the lead until they have a beat.');
                        } else {
                            alert('Please select a beat date for the assignee before submitting.');
                        }
                        return;
                    }
                    var beatDate = beatVal.split('|')[0];
                    leadActivityData['scheldule'] = beatDate + 'T12:00:00';
                    leadActivityData['beatSelection'] = beatVal;
                } else {
                    // Non-sales assignee: no beat-day panel. Fall back to the manual
                    // #editScheduleTime picker so the user's chosen date/time is still
                    // persisted on lead_activity.schedule_timestamp.
                    try {
                        var picker = $('#editScheduleTime').data('daterangepicker');
                        if (picker && picker.startDate) {
                            leadActivityData['scheldule'] = picker.startDate.format(moment.HTML5_FMT.DATETIME_LOCAL_SECONDS);
                        }
                    } catch (e) {
                        // no picker attached / no date — leave scheldule unset
                    }
                }
            }

            console.log(leadActivityData);
            if (confirm("Are you sure you want to add lead!") == true) {
                doPostAjaxRequestWithJsonHandler(context + "/editLead", JSON.stringify(leadActivityData), function (response) {
                    console.log(response);
                    $('#editLeadData').modal('hide');
                    $('.modal-backdrop').remove();
                    // Inline row replace only works when the row's column layout matches the
                    // main #lead-table (that's what edit-lead.vm renders for). The upper
                    // search-results table has fewer columns, so let the search re-run
                    // repaint it cleanly instead.
                    if (row && !row.closest('#global-search-results').length) {
                        row.html(response);
                    }
                    var activeTerm = $.trim($('#lead-table_filter input').val() || $('#lead-table-bottom-filter').val() || "");
                    if (activeTerm.length >= 2 && $('#global-search-results').children().length) {
                        runGlobalLeadSearch(activeTerm);
                    }
                });
            }

    }


    $(document).on('click', ".show-partner-health",
        function () {

            var email = $("#authUserFilter").val();

            console.log(email)
            doGetAjaxRequestHandler(context + "/partnerHealth?email="
                + email, function (response) {
                console.log(response)
                $('#' + 'main-content').html(response);

            });
        });


    $(document).on('click', ".lead-detail-entry",
        function () {

            console.log("hello");
            var outletName = $('input[name="outletName"]').val();
            var counterSize = $('input[name="counterSize"]').val();
            var table = document.getElementById('editbrandtable');
            var brandValueJson = [];
            var leadBrands;

            if (outletName === "") {
                alert("Outlet Name is required");
                return;
            }

            if (counterSize === "") {
                alert("Counter Size is required");
                return;
            }

            if (localStorage.getItem("frontph") == "undefined" && localStorage.getItem("frontph") == null) {
                alert("Front Document is required");
                return;
            }

            if (localStorage.getItem("internalMarketh") == "undefined" || localStorage.getItem("internalMarketh") == null) {
                alert("Front With Market Document is required");
                return;
            }

            if (localStorage.getItem("leftShoth") == "undefined" || localStorage.getItem("leftShoth") == null) {
                alert("Internal Left Shot Document is required");
                return;
            }

            if (localStorage.getItem("leftWallh") == "undefined" || localStorage.getItem("leftWallh") == null) {
                alert("Internal Left Wall Document is required");
                return;
            }


            if (localStorage.getItem("rightWallh") == "undefined" || localStorage.getItem("rightWallh") == null) {
                alert("Internal Right Wall Document is required");
                return;
            }


            for (i = 1; i < table.rows.length; i++) {

                var objCells = table.rows[i].cells;

                leadBrands = {
                    brand: objCells[0].innerText,
                    value: objCells[1].getElementsByTagName('input')[0].value
                }
                brandValueJson.push(leadBrands);
            }


            var leadDetailObject = {};

            leadDetailObject['leadId'] = leadId;


            leadDetailObject['outletName'] = outletName;

            leadDetailObject['counterSize'] = counterSize;

            leadDetailObject['leadBrands'] = brandValueJson;


            console.log(localStorage.getItem("frontp"));


            leadDetailObject['frontp'] = localStorage
                .getItem("frontph");


            leadDetailObject['frontWithMarket'] = localStorage
                .getItem("internalMarketh");


            leadDetailObject['internalLongShot'] = localStorage
                .getItem("leftShoth");


            leadDetailObject['internalLeftWall'] = localStorage
                .getItem("leftWallh");


            leadDetailObject['internalRightWall'] = localStorage
                .getItem("rightWallh");

            console.log(leadDetailObject);

            if (confirm("Are you sure you want to add lead detail!") == true) {
                doPostAjaxRequestWithJsonHandler(context + "/leadDetail", JSON.stringify(leadDetailObject), function (response) {
                    console.log(response);
                    if (response == 'true') {
                        alert("Submit Successfully");
                    }

                });
            }

        });


    $(document).on('change', '.frontp',
        function () {

            if (confirm('Document has been selected, Do you want to upload ?')) {

                var documentId = uploadImage(this, "frontph");


            } else {

            }
        });

    $(document).on('change', '.internalMarket',
        function () {

            if (confirm('Document has been selected, Do you want to upload ?')) {

                var documentId = uploadImage(this, "internalMarketh");

            } else {

            }
        });

    $(document).on('change', '.leftShot',

        function () {
            if (confirm('Document has been selected, Do you want to upload ?')) {
                var documentId = uploadImage(this, "leftShoth");
            } else {

            }
        });

    $(document).on('change', '.leftWall',
        function () {
            if (confirm('Document has been selected, Do you want to upload ?')) {
                var documentId = uploadImage(this, "leftWallh");
            } else {

            }
        });

    $(document).on('change', '.rightWall',
        function () {
            if (confirm('Document has been selected, Do you want to upload ?')) {
                var documentId = uploadImage(this, "rightWallh");
            } else {
            }
        });


});

function uploadImage(fileSelector, attrName) {
    var documentId;
    if (fileSelector != undefined
        && fileSelector.files[0] != undefined) {
        var url = context
            + '/document-upload';

        console.log(url);
        var file = fileSelector.files[0];

        console.log(file)
        doAjaxUploadRequestHandler(
            url,
            'POST',
            file,
            function (response) {
                console.log(response)
                documentId = response.response.document_id;
                console
                    .log("documentId : "
                        + documentId);


                localStorage
                    .setItem(
                        attrName,
                        documentId);

            });
        return documentId;
    }

}


function loadLead(domId) {
    doGetAjaxRequestHandler(context + "/getOpenLead", function (response) {
        $('#' + domId).html(response);
    });
}

function loadClosedLead(domId, searchTerm) {
    doGetAjaxRequestHandler(context + "/getClosedLead", function (response) {
        $('#' + domId).html(response);
    })
}

function statusAction() {
    var val = $('#status').val();
    if (val == "followUp") {
        $("#scheduleTime").show();
    } else {
        $("#scheduleTime").hide();
    }

}


function editStatusAction() {
    var val = $('#editStatus').val();
    if (val == "followUp") {
        // Show communication type and schedule date
        $("#communicationTypeSection").show();
        $("#editScheduleTime").show();
        $("#beatDateSelection").hide();

        // Reset communication type only; preserve the assignee the user picked.
        $('#communicationType').val('');
        $('#assignTo option').prop('disabled', false);

        // Check if lead has approved geolocation to decide VISIT option
        doAjaxRequestHandler(context + "/lead-geo/check/" + leadId, "GET", function (response) {
            var hasGeo = response.response.hasApprovedGeo;
            var commDropdown = $('#communicationType');
            commDropdown.empty();
            commDropdown.append('<option value="" disabled selected>Communication Type</option>');
            commDropdown.append('<option value="TELEPHONIC">TELEPHONIC</option>');
            if (hasGeo) {
                commDropdown.append('<option value="VISIT">VISIT</option>');
            }
        });
    } else {
        $("#communicationTypeSection").hide();
        $("#editScheduleTime").hide();
        $("#beatDateSelection").hide();
        $('#assignTo option').prop('disabled', false);
    }

}

function loadLeadSearchInfo(search_text) {
    loadSearchLead("main-content", search_text);
}

function loadTeamCommitment(domId) {
    doGetAjaxRequestHandler(context + "/teamCommitment",
        function (response) {
            $('#' + domId).html(response);
        });
}

function loadLeadDetail(domId) {
    doGetAjaxRequestHandler(context + "/getLeadDetail",
        function (response) {
            $('#' + domId).html(response);
        });
}

function loadPartnerHealth(domId) {
    doGetAjaxRequestHandler(context + "/partnerHealth",
        function (response) {
            $('#' + domId).html(response);
        });
}

function loadSearchLead(domId, search_text) {
    doGetAjaxRequestHandler(context + "/searchLeads?searchTerm=" + search_text,
        function (response) {
            $('#' + domId).html(response);
        });
}

$(document).on('click', ".arr-button-mk",
    function () {
        var startDate = $('.arr-start_date').val();
        doGetAjaxRequestHandler(context + "/rbmTodayArr?startDate=" + startDate, function (response) {
            $('#main-content').html(response);

        });
    });

$(document).on('click', ".rbm-today-arr",
    function () {
        doGetAjaxRequestHandler(context + "/rbmTodayArr", function (response) {
            $('#main-content').html(response);

        });
    });
$(document).on('click', '.reassign', function () {
    $('#bulkReassignFile').val(null);
    $('#bulkReassignFile').click();
});

$(document).on('change', '#bulkReassignFile', function () {

    if (!confirm("Confirm bulk reassign upload?")) {
        return;
    }

    var file = this.files[0];
    if (!file) {
        alert("No file selected");
        return;
    }

    doAjaxUploadRequestHandler(
        context + "/upload-assign-id",
        'POST',
        file,
        function (response) {
            alert("Bulk reassignment completed");
            loadLead("main-content");
        }
    );
});

// ==================== GEO LOCATION HANDLERS ====================

// Communication type change: filter assignTo based on type
$(document).on('change', '#communicationType', function () {
    var val = $(this).val();
    var assignDropdown = $('#assignTo');

    // Reset beat + restore manual date input
    $('#beatDate').val('');
    $('#beatBadges').empty();
    $("#beatDateSelection").hide();
    $("#editScheduleTime").show();

    if (val == 'VISIT') {
        // Filter assignTo to sales users only (no BGC). Uses .prop('disabled', ...)
        // instead of .hide()/.show() because select2 doesn't respect hidden <option>s
        // in its dropdown UI. Disabled options are filtered out by our matcher above.
        if (typeof salesUserIds !== 'undefined') {
            assignDropdown.find('option').each(function () {
                var optVal = parseInt($(this).val());
                if (optVal && salesUserIds.indexOf(optVal) === -1) {
                    $(this).prop('disabled', true);
                } else {
                    $(this).prop('disabled', false);
                }
            });
        }
    } else {
        // TELEPHONIC — enable all users
        assignDropdown.find('option').prop('disabled', false);
    }
    // Nudge select2 to re-render its dropdown with the new enabled/disabled state.
    if ($.fn.select2 && assignDropdown.hasClass('select2-hidden-accessible')) {
        assignDropdown.trigger('change.select2');
    }
    // Both VISIT and TELEPHONIC offer beat-day slots when an assignee is set
    // (TELEPHONIC just uses the beat date as the call slot; backend won't
    // attach a LeadRoute for it). Non-sales assignees simply get an empty list.
    if (val && assignDropdown.val()) {
        fetchBeatDates();
    }
});

// Fetch beats when assignTo changes (works for both VISIT and TELEPHONIC)
$(document).on('change', '#assignTo', function () {
    var commType = $('#communicationType').val();
    var salesAuthId = $('#assignTo').val();
    if (commType && salesAuthId && leadId) {
        fetchBeatDates();
    } else if (!commType) {
        $("#beatDateSelection").hide();
    }
});

function fetchBeatDates() {
    var salesAuthId = $('#assignTo').val();
    if (!salesAuthId || !leadId) return;

    // Beat slots only make sense for sales assignees. BGC / other internal
    // hand-offs skip the entire beat panel (and the visit-request CTA that
    // sits inside it). Mirrors the server-side carve-out in /editLead.
    var assigneeIntId = parseInt(salesAuthId, 10);
    var isSalesAssigneeFetch = !isNaN(assigneeIntId)
        && typeof salesUserIds !== 'undefined'
        && salesUserIds.indexOf(assigneeIntId) !== -1;
    if (!isSalesAssigneeFetch) {
        $('#beatBadges').empty();
        $('#beatDate').val('');
        $('#beatDateSelection').hide();
        return;
    }

    var badgesDiv = $('#beatBadges');
    badgesDiv.html('<span style="color:#999; font-size:12px;">Loading beats...</span>');
    $("#beatDateSelection").show();
    $('#beatDate').val('');

    var url = context + "/lead-geo/beat-dates?leadId=" + leadId + "&salesAuthId=" + salesAuthId;

    $.ajax({
        url: url,
        method: 'GET',
        success: function (response) {
            var data = response.response || response;
            badgesDiv.empty();

            // Stores within radius of the lead — show count + top 3 inline.
            var radius = (data && data.radiusKm) ? data.radiusKm : 30;
            var stores = (data && data.nearestStores) || [];
            if (stores.length > 0) {
                var preview = stores.slice(0, 3).map(function (s) {
                    return '<strong>' + s.code + ' - ' + s.name + '</strong> (' + s.distanceKm + ' km)';
                }).join(', ');
                var more = stores.length > 3 ? ' +' + (stores.length - 3) + ' more' : '';
                badgesDiv.append('<div style="font-size:12px; color:#333; margin-bottom:6px;">' +
                    stores.length + ' partner store(s) within ' + radius + ' km of this lead: ' +
                    preview + more + '</div>');
            }

            // All upcoming beat-dates for the assignee that touch any nearby store.
            if (data && data.beats && data.beats.length > 0) {
                badgesDiv.append('<div style="font-weight:bold; font-size:11px; color:#666; margin-bottom:4px;">Available Slots (near this lead):</div>');
                var beats = data.beats;
                for (var i = 0; i < beats.length; i++) {
                    var beat = beats[i];
                    var nearTxt = beat.nearStore ? ' &middot; near ' + beat.nearStore : '';
                    var badge = $('<span class="beat-badge" style="' +
                        'display:inline-block; background:#337ab7; color:#fff; padding:6px 12px; ' +
                        'margin:4px 6px 4px 0; border-radius:16px; cursor:pointer; font-size:12px; ' +
                        'border:2px solid #337ab7; transition:all 0.2s;">' +
                        beat.planDate + ' &middot; ' + beat.beatName + ' (' + beat.stops + ' stops)' + nearTxt +
                        '</span>');
                    badge.data('value', beat.planDate + '|' + beat.beatName + '|' + beat.planGroupId);
                    badgesDiv.append(badge);
                }
            } else {
                // No beat-days available for this assignee. Surface a CTA so the
                // user can fire a visit request to the assignee's hierarchy instead
                // of being stuck. The pre-existing 'beats > 0' branch above is
                // untouched — this only fires for the empty-beats case.
                var nearestId = (stores.length > 0 && stores[0].storeId) ? stores[0].storeId : '';
                badgesDiv.append(
                    '<div style="background:#fff8e1; border:1px solid #f0e0a0; border-radius:6px; padding:8px 10px; margin-top:4px;">'
                    + '<div style="font-size:12px; color:#7c5a00; margin-bottom:6px;">'
                    + 'No upcoming beat is available for this assignee.'
                    + '</div>'
                    + '<div style="display:flex; gap:8px; align-items:center;">'
                    + '<label style="font-size:11px; color:#666; margin:0;">Preferred date (optional):</label>'
                    + '<input type="date" id="vrPreferredDate" class="input-sm" style="font-size:12px; padding:3px 6px;">'
                    + '<button type="button" id="vrSendBtn" class="btn btn-warning btn-sm" '
                    + 'data-nearest="' + nearestId + '" style="font-size:12px;">Send Visit Request</button>'
                    + '</div>'
                    + '<div style="font-size:11px; color:#888; margin-top:6px;">'
                    + 'The request goes to the assignee\'s reporting head (and up). Once they approve and pick a beat-day, the lead lands on that beat.'
                    + '</div>'
                    + '</div>');
            }
        },
        error: function () {
            badgesDiv.html('<span style="color:#d9534f; font-size:12px;">Error loading beats</span>');
        }
    });
}

// Send Visit Request when no beats are available for the chosen assignee.
// Posts to /visitRequest/create. Existing beat-pick + Submit flow is unchanged.
$(document).on('click', '#vrSendBtn', function () {
    var $btn = $(this);
    var assigneeAuthId = parseInt($('#assignTo').val());
    var commType = $('#communicationType').val() || null;
    var nearestStoreId = parseInt($btn.data('nearest'));
    var preferred = $('#vrPreferredDate').val() || null;
    var selectedStatus = $('#editStatus').val() || null;
    if (!leadId || !assigneeAuthId) {
        alert('Pick an assignee first.');
        return;
    }
    $btn.prop('disabled', true).text('Sending...');
    var payload = {
        leadId: leadId,
        assigneeAuthId: assigneeAuthId,
        communicationType: commType,
        reason: 'No upcoming beats for assignee'
    };
    if (!isNaN(nearestStoreId) && nearestStoreId > 0) payload.nearestStoreId = nearestStoreId;
    if (preferred) payload.requestedDate = preferred;
    // Ship the picked status too — server (VisitRequestController.create) reads
    // it via parseLeadStatus and updates lead.status through reassignLeadAndLog.
    // Without it, the visit request is raised but the lead status never moves
    // off its previous value (e.g. stays notInterested while user picked followUp).
    if (selectedStatus) payload.status = selectedStatus;

    doPostAjaxRequestWithJsonHandler(context + '/visitRequest/create', JSON.stringify(payload),
        function (response) {
            $btn.prop('disabled', false).text('Send Visit Request');
            var data = (response && response.response) || response || {};
            if (data && data.id) {
                alert('Visit request sent. The assignee\'s manager has been notified.');
                $('#editLeadData').modal('hide');
                $('.modal-backdrop').remove();
                // Repaint the affected rows so the new status is visible without
                // a manual refresh. If a global search is active, re-run it (this
                // also refreshes the injected rows in #lead-table).
                var activeTerm = $.trim($('#lead-table_filter input').val() || $('#lead-table-bottom-filter').val() || "");
                if (activeTerm.length >= 2 && $('#global-search-results').children().length && typeof window.runGlobalLeadSearch === 'function') {
                    window.runGlobalLeadSearch(activeTerm);
                }
            } else {
                var msg = (data && data.message) || (data && data.error) || 'Could not send request.';
                alert(msg);
            }
        });
});

// Click on beat badge to select it. A picked beat becomes the schedule
// source — the manual date input is hidden (not needed when scheduling by beat).
$(document).on('click', '.beat-badge', function () {
    $('.beat-badge').css({'background': '#337ab7', 'border-color': '#337ab7'});
    $(this).css({'background': '#1a5276', 'border-color': '#f39c12', 'border-width': '2px'});
    $('#beatDate').val($(this).data('value'));
    $("#editScheduleTime").hide();
});

// Generate Geo Link for lead
$(document).on('click', '.generateGeoLink', function (e) {
    e.stopPropagation();
    var lid = $(this).data('leadid');
    doAjaxRequestHandler(context + "/lead-geo/generate-link?leadId=" + lid, "GET", function (response) {
        var url = response.response;
        if (navigator.clipboard) {
            navigator.clipboard.writeText(url).then(function () {
                alert("Link copied to clipboard:\n" + url);
            });
        } else {
            prompt("Share this link with the prospect:", url);
        }
    });
});

// Manual geo verification — for cases where the prospect refused to tap the
// verification link. Team-member confirms lat/lng over phone (or pastes a
// Maps URL the prospect shared) and writes it APPROVED directly.
function ensureManualVerifyModal() {
    if ($('#manualVerifyGeoModal').length) return;
    var html =
        '<div id="manualVerifyGeoModal" class="modal" role="dialog" tabindex="-1">' +
        '  <div class="modal-dialog modal-lg">' +
        '    <div class="modal-content">' +
        '      <div class="modal-header">' +
        '        <button type="button" class="close" data-dismiss="modal">&times;</button>' +
        '        <h4 class="modal-title">Verify Lead Location Manually</h4>' +
        '      </div>' +
        '      <div class="modal-body" style="max-height:75vh;overflow-y:auto;">' +
        '        <input type="hidden" id="manualVerifyLeadId">' +
        '        <div class="form-group">' +
        '          <label>Address <small class="text-muted">(include city, state, pincode for best result)</small></label>' +
        '          <div class="input-group">' +
        '            <input type="text" class="form-control" id="manualVerifyAddress" placeholder="e.g. Shop 12, Sector 18, Noida, UP, 201301">' +
        '            <span class="input-group-btn">' +
        '              <button type="button" class="btn btn-default" id="manualVerifyGeocodeBtn">Find on map</button>' +
        '            </span>' +
        '          </div>' +
        '        </div>' +
        '        <div class="form-group">' +
        '          <label>Latitude, Longitude</label>' +
        '          <div class="input-group">' +
        '            <input type="text" class="form-control" id="manualVerifyLatLng" placeholder="28.6139,77.2090">' +
        '            <span class="input-group-btn">' +
        '              <button type="button" class="btn btn-default" id="manualVerifyPreviewBtn">Show on map</button>' +
        '            </span>' +
        '          </div>' +
        '          <small class="text-muted">You can also paste a Google Maps URL containing coords.</small>' +
        '        </div>' +
        '        <div class="form-group" id="manualVerifyMapWrap" style="display:none;">' +
        '          <label>Map preview <small class="text-muted">(confirm the pin is right)</small></label>' +
        '          <div style="border:1px solid #ddd;border-radius:3px;overflow:hidden;">' +
        '            <iframe id="manualVerifyMapFrame" width="100%" height="260" frameborder="0" style="border:0;" allowfullscreen></iframe>' +
        '          </div>' +
        '          <small><a href="#" id="manualVerifyOpenMap" target="_blank">Open in Google Maps</a></small>' +
        '        </div>' +
        '        <div class="form-group">' +
        '          <label>Store-board photo <span class="text-danger">*</span> <small class="text-muted">(required &mdash; proves the verification)</small></label>' +
        '          <input type="file" id="manualVerifyPhoto" accept="image/jpeg,image/png" required>' +
        '          <div id="manualVerifyPhotoPreview" style="margin-top:6px;display:none;">' +
        '            <img id="manualVerifyPhotoImg" src="" style="max-height:120px;border:1px solid #ddd;border-radius:3px;padding:2px;">' +
        '          </div>' +
        '        </div>' +
        '        <div class="form-group">' +
        '          <label>Remark <small class="text-muted">(optional)</small></label>' +
        '          <input type="text" class="form-control" id="manualVerifyRemark" placeholder="e.g. Confirmed on call with prospect">' +
        '        </div>' +
        '        <div id="manualVerifyErr" class="text-danger" style="display:none;"></div>' +
        '      </div>' +
        '      <div class="modal-footer">' +
        '        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>' +
        '        <button type="button" class="btn btn-success" id="manualVerifySaveBtn">Save &amp; Verify</button>' +
        '      </div>' +
        '    </div>' +
        '  </div>' +
        '</div>';
    $('body').append(html);
}

function manualVerifyShowMap(lat, lng) {
    var src = 'https://www.google.com/maps?q=' + lat + ',' + lng + '&z=17&output=embed';
    $('#manualVerifyMapFrame').attr('src', src);
    $('#manualVerifyOpenMap').attr('href', 'https://www.google.com/maps?q=' + lat + ',' + lng);
    $('#manualVerifyMapWrap').show();
}

// Parses raw "lat,lng" or a Google Maps URL containing the coords.
// Maps formats covered: /@lat,lng, /maps?q=lat,lng, ?ll=lat,lng, ?destination=lat,lng.
function parseLatLngInput(raw) {
    if (!raw) return null;
    var s = String(raw).trim();
    // Strip any leading "lat:" / "lng:" tokens
    var direct = s.match(/(-?\d{1,3}\.\d+)\s*,\s*(-?\d{1,3}\.\d+)/);
    if (direct) return {lat: parseFloat(direct[1]), lng: parseFloat(direct[2])};
    return null;
}

$(document).on('click', '.verifyGeoManual', function (e) {
    e.stopPropagation();
    var lid = $(this).data('leadid');
    ensureManualVerifyModal();
    $('#manualVerifyLeadId').val(lid);
    $('#manualVerifyAddress').val('');
    $('#manualVerifyLatLng').val('');
    $('#manualVerifyRemark').val('');
    $('#manualVerifyErr').hide().text('');
    $('#manualVerifyMapWrap').hide();
    $('#manualVerifyMapFrame').attr('src', '');
    $('#manualVerifyPhoto').val('');
    $('#manualVerifyPhotoImg').attr('src', '');
    $('#manualVerifyPhotoPreview').hide();
    $('#manualVerifyGeoModal').modal('show');
});

// Local thumbnail preview as soon as the user picks a file (no upload yet —
// upload happens on Save so we don't orphan documents on cancel).
$(document).on('change', '#manualVerifyPhoto', function () {
    var f = this.files && this.files[0];
    if (!f) {
        $('#manualVerifyPhotoPreview').hide();
        return;
    }
    var reader = new FileReader();
    reader.onload = function (ev) {
        $('#manualVerifyPhotoImg').attr('src', ev.target.result);
        $('#manualVerifyPhotoPreview').show();
    };
    reader.readAsDataURL(f);
});

// Address -> coords via server (uses existing GeocodingService).
// On success, fills the lat/lng box and renders the map preview.
$(document).on('click', '#manualVerifyGeocodeBtn', function () {
    var addr = ($('#manualVerifyAddress').val() || '').trim();
    if (!addr) {
        $('#manualVerifyErr').text('Enter an address first.').show();
        return;
    }
    $('#manualVerifyErr').hide();
    var btn = $(this);
    btn.prop('disabled', true).text('Finding...');
    $.ajax({
        url: context + '/lead-geo/geocode-address',
        type: 'POST',
        data: {address: addr},
        success: function (resp) {
            btn.prop('disabled', false).text('Find on map');
            var r = resp && resp.response ? resp.response : resp;
            if (!r || !r.success) {
                $('#manualVerifyErr').text((r && r.message) || 'Could not geocode that address.').show();
                return;
            }
            $('#manualVerifyLatLng').val(r.latitude + ',' + r.longitude);
            manualVerifyShowMap(r.latitude, r.longitude);
        },
        error: function () {
            btn.prop('disabled', false).text('Find on map');
            $('#manualVerifyErr').text('Geocode request failed. Try again.').show();
        }
    });
});

// "Show on map" — re-render the iframe from whatever is in the lat/lng input.
// Useful after the user nudges the coords manually.
$(document).on('click', '#manualVerifyPreviewBtn', function () {
    var parsed = parseLatLngInput($('#manualVerifyLatLng').val());
    if (!parsed) {
        $('#manualVerifyErr').text('Enter latitude,longitude first.').show();
        return;
    }
    $('#manualVerifyErr').hide();
    manualVerifyShowMap(parsed.lat, parsed.lng);
});

$(document).on('click', '#manualVerifySaveBtn', function () {
    var lid = $('#manualVerifyLeadId').val();
    var raw = $('#manualVerifyLatLng').val();
    var remark = $('#manualVerifyRemark').val() || '';
    var parsed = parseLatLngInput(raw);
    if (!parsed) {
        $('#manualVerifyErr').text('Could not read latitude/longitude. Paste like 28.6139,77.2090').show();
        return;
    }
    if (parsed.lat < -90 || parsed.lat > 90 || parsed.lng < -180 || parsed.lng > 180
        || (parsed.lat === 0 && parsed.lng === 0)) {
        $('#manualVerifyErr').text('Latitude/longitude out of range.').show();
        return;
    }
    var fileInput = document.getElementById('manualVerifyPhoto');
    var pickedFile = fileInput && fileInput.files && fileInput.files[0];
    if (!pickedFile) {
        $('#manualVerifyErr').text('Please attach a store-board photo to verify.').show();
        return;
    }
    $('#manualVerifyErr').hide();
    var btn = $('#manualVerifySaveBtn');
    btn.prop('disabled', true).text('Verifying...');

    function callVerify(docId) {
        $.ajax({
            url: context + '/lead-geo/manual-verify',
            type: 'POST',
            data: {
                leadId: lid,
                latitude: parsed.lat,
                longitude: parsed.lng,
                remark: remark,
                imageDocumentId: docId || 0
            },
            success: function () {
                btn.prop('disabled', false).text('Save & Verify');
                $('#manualVerifyGeoModal').modal('hide');
                // Replace the cell of this lead row with the Verified badge so
                // the user sees the result without reloading the whole list.
                var $cell = $('.verifyGeoManual[data-leadid="' + lid + '"]').closest('td');
                if ($cell.length) {
                    var photoBtn = docId > 0
                        ? '  <a href="' + context + '/open-attachment?documentId=' + docId + '" target="_blank" class="btn btn-xs btn-default" style="margin-bottom:2px;">View Photo</a>'
                        : '';
                    $cell.html(
                        '<div class="btn-group-vertical" style="width:100%">' +
                        '  <span class="label label-success" style="margin-bottom:4px;">Verified</span>' +
                        '  <a href="https://www.google.com/maps?q=' + parsed.lat + ',' + parsed.lng + '" target="_blank" class="btn btn-xs btn-default" style="margin-bottom:2px;">View Map</a>' +
                        photoBtn +
                        '  <button class="btn btn-xs btn-danger reject-geo" data-leadid="' + lid + '">Revoke</button>' +
                        '</div>'
                    );
                }
            },
            error: function (xhr) {
                btn.prop('disabled', false).text('Save & Verify');
                var msg = 'Failed to verify. Please try again.';
                try {
                    var j = xhr.responseJSON || JSON.parse(xhr.responseText || '{}');
                    if (j && j.response) msg = j.response;
                    else if (j && j.message) msg = j.message;
                } catch (e) {
                }
                $('#manualVerifyErr').text(msg).show();
            }
        });
    }

    // Upload first, then verify with the returned document id. Photo is
    // required (gate at the top of the handler), so we always go through this.
    btn.text('Uploading photo...');
    var formData = new FormData();
    formData.append('file', pickedFile, pickedFile.name || 'store-photo.jpg');
    $.ajax({
        url: context + '/lead-geo/upload-image',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function (resp) {
            var r = resp && resp.response ? resp.response : resp;
            var docId = r && (r.document_id || r.documentId || r.id);
            if (!docId) {
                btn.prop('disabled', false).text('Save & Verify');
                $('#manualVerifyErr').text('Photo upload failed. Try again or remove the photo.').show();
                return;
            }
            btn.text('Verifying...');
            callVerify(docId);
        },
        error: function () {
            btn.prop('disabled', false).text('Save & Verify');
            $('#manualVerifyErr').text('Photo upload failed. Try again or remove the photo.').show();
        }
    });
});

// Geo Review navigation
$(document).on('click', '.geo-review', function () {
    doGetAjaxRequestHandler(context + "/lead-geo/pending-reviews", function (response) {
        $('#main-content').html(response);
    });
});

// Visit Approvals navigation
$(document).on('click', '.visit-approvals', function () {
    doGetAjaxRequestHandler(context + "/visit-approvals", function (response) {
        $('#main-content').html(response);
    });
});

// Beat Day View — load inline into dashboard
$(document).on('click', '.beat-plan-dayview', function (e) {
    e.preventDefault();
    doGetAjaxRequestHandler(context + '/beatPlan/dayView', function (response) {
        $('#main-content').html(response);
    });
});

// Base Location manager — load inline into dashboard
$(document).on('click', '.base-location', function (e) {
    e.preventDefault();
    doGetAjaxRequestHandler(context + '/beatPlan/baseLocationPage', function (response) {
        $('#main-content').html(response);
    });
});

// Deferred Partners — load inline into dashboard
$(document).on('click', '.beat-plan-deferred', function (e) {
    e.preventDefault();
    doGetAjaxRequestHandler(context + '/beatPlan/deferredView', function (response) {
        $('#main-content').html(response);
    });
});

// Approve geolocation from lead table
$(document).on('click', '.approve-geo', function (e) {
    e.stopPropagation();
    var lid = $(this).data('leadid');
    if (!confirm('Approve geolocation for Lead #' + lid + '?')) return;

    var btn = $(this);
    var cell = btn.closest('td');

    doPostAjaxRequestWithParamsHandler(
        context + '/lead-geo/review',
        {leadId: lid, status: 'APPROVED', remark: ''},
        function (response) {
            cell.html('<span class="label label-success">Verified</span>');
        }
    );
});

// Reject geolocation from lead table
$(document).on('click', '.reject-geo', function (e) {
    e.stopPropagation();
    var lid = $(this).data('leadid');
    var reason = prompt('Reason for rejection:');
    if (reason === null) return;

    var btn = $(this);
    var cell = btn.closest('td');

    doPostAjaxRequestWithParamsHandler(
        context + '/lead-geo/review',
        {leadId: lid, status: 'REJECTED', remark: reason},
        function (response) {
            cell.html('<button class="btn btn-xs btn-warning generateGeoLink" data-leadid="' + lid + '">Rejected - Resend</button>');
        }
    );
});