let selectedImage = "";
let selectedFile = null;
async function loadDark() {
    let singlePreference=null;    
    try {
        const sessionPreferences = sessionStorage.getItem("preferences");
        if(sessionPreferences){
            const preferencesData = await parseJSONData(sessionPreferences);
            singlePreference = preferencesData;
        }else {
            const preferences = await asyncGetPreferencesRequest({
                get_preferences_for_property_user: true,
                property_id: sessionStorage.getItem("propertyId"),
            });
            if(preferences&&preferences?.length>0){
                singlePreference= preferences[0];
                sessionStorage.setItem("preferences",JSON.stringify(singlePreference));
            }
        }

        let dark = singlePreference?.theme_mode// JSON.parse(localStorage.getItem("DarkMode"));
    
        var buttonElement = document.getElementById("darkIcon");
        var sidebar = document.getElementById("sidebar-con");

        if (dark === "light" || !dark) {
            $(".dark_logo").addClass('showHide');
            $(".light_logo").removeClass('showHide');
            localStorage.setItem("DarkMode", JSON.stringify(false));
            buttonElement?.classList.add("far");
            buttonElement?.classList.add("fa-sun");
            sidebar?.classList?.add("sidebar-light-primary");

            sidebar?.classList?.remove("sidebar-dark-primary");
        } else if (dark === "dark") {
            $(".nav-tabs .nav-link").css('color', '#fff');
            $(".dark_logo").removeClass('showHide');
            $(".light_logo").addClass('showHide');
            document.getElementById("body_body")?.classList.add("dark-mode");
            buttonElement?.classList.add("fa-moon");
            buttonElement?.classList.add("fas");
            sidebar?.classList?.remove("sidebar-light-primary");
            sidebar?.classList?.add("sidebar-dark-primary");
        }
        
    } catch (error) {

    }
}

function toggleDark() {
    var element = document.getElementById("body_body");
    element.classList.toggle("dark-mode");
    let dark = JSON.parse(localStorage.getItem("DarkMode"));
    var buttonElement = document.getElementById("darkIcon");
    var sidebar = document.getElementById("sidebar-con");
    if (dark) {
        localStorage.setItem("DarkMode", JSON.stringify(false));
        buttonElement.classList.toggle("far");
        buttonElement.classList.toggle("fa-sun");
        buttonElement.classList.toggle("fa-moon");
        buttonElement.classList.toggle("fas");
        sidebar.classList.remove("sidebar-dark-primary");
        sidebar.classList.add("sidebar-light-primary");
    } else {
        localStorage.setItem("DarkMode", JSON.stringify(true));
        buttonElement.classList.toggle("far");
        buttonElement.classList.toggle("fa-sun");
        buttonElement.classList.toggle("fa-moon");
        buttonElement.classList.toggle("fas");
        sidebar.classList.add("sidebar-dark-primary");
        sidebar.classList.remove("sidebar-light-primary");
    }
}

async function asyncGetPreferencesRequest(data) {
  return new Promise((resolve, reject) => {
    $.ajax({
      url: "/include/preferences/set_preferences.php",
      type: "post",
      data,
      success: function (resp1) {
        resolve(resp1.data);
      },
      error: function (xhr, status, error) {
        console.log("error : ", error);
        reject(error);
      },
    });
  });
}

window.onload = loadDark();

function check_door_key(){
    var door_key = $("#door_key").val();
    if (door_key.length > 1) {
        var set_key = door_key.slice(0, 1); // Keep only the first digit
        $("#door_key").val(set_key);
    }
}

function capitalizeWords(caps) {
    return caps
        .split('_')
        .map(word => word.charAt(0).toUpperCase() + word.slice(1))
        .join(' ');
}

function loadDealerSlots() {
    // Populate Dealer Slots dropdown
    if ($("#dealer").length) {
        $.ajax({
            url: 'include/admin/dealerslots.php',
            type: 'post',
            data: { getslots: 'yes' },
            success: function(response) {
                console.log(response);
                if (Array.isArray(response)) {
                    var dealerSelect = $('#dealer');
                    dealerSelect.empty();
                    if (response.length === 0) {
                        dealerSelect.append('<option value="">No dealers available</option>');
                    } else {
                        response.forEach(function(dealer) {
                            dealerSelect.append(DOMPurify.sanitize('<option value="' + dealer.dealer_id + '">' + dealer.firstname + ' ' + dealer.lastname + ' (' + dealer.slots_used + ' used of ' + dealer.slots_avail +')</option>'));
                        });

                        $("#ftpServerSlotContainer").empty();
                        loadFtpSlotsForDealer();
                        loadAvailableFtpServers(dealer.dealerId);
                    }
                } else {
                    console.error('Unexpected response format:', response);
                }
            },
            error: function(xhr, status, error) {
                console.error('Failed to fetch dealers:', status, error);
                var dealerSelect = $('#dealer');
                dealerSelect.empty();
                dealerSelect.append('<option value="">Failed to load dealers</option>');
            }
        });
    }
}

function escapeHtml(text) {
    if (typeof text !== "string") return text;
    return text
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

function safeVal(selector, value) {
    $(selector).val(escapeHtml(value));
}

function safeText(selector, value) {
    $(selector).text(escapeHtml(value));
}

function myOrganizations(orgs, properties) {
    let html = '';
    let orgtble = document.getElementById("orgtble");
    let admins = document.getElementById("adminsmodal");
    let editdealeradmins = document.getElementById("editAdminModal");

    let select = $('#organization_id');
    select.empty();
    orgs.forEach(function(org) {
        select.append('<option value="' + org.id + '">' + org.name + '</option>');
    });

    let select1 = $('#uorganization_id');
    select1.empty()
    orgs.forEach(function(org) {
        select1.append('<option value="' + org.id + '">' + org.name + ' - ' + org.company_name + '</option>');
    });

    if (orgtble) {
        if (orgs.length === 0) {
            html = "<tr><td colspan='10' class='text-center'>No organizations available</td></tr>";
        } else {
            for (let i = 0; i < orgs.length; i++) {
                const orgProperties = properties.filter(p => p.organization_id === orgs[i].id);
                var formatednumber = formatphoneNumber(orgs[i].contact_phone_number);

                if (orgs[i].admin === true) {
                    html += `
                        <tr data-widget="expandable-table" aria-expanded="false">
                            <td><i class="expandable-table-caret fas fa-caret-right fa-fw"></i></td>
                            <td>${orgs[i].name}</td>
                            <td>${orgs[i].address}</td>
                            <td>${orgs[i].city}</td>
                            <td>${orgs[i].state}</td>
                            <td>${orgs[i].zipcode}</td>
                            <td>${orgs[i].contact}</td>
                            <td>${formatednumber}</td>
                            <td>${orgs[i].created_at}</td>
                            <td>
                                <a class="fas fa-edit text-primary mx-1" style="cursor: pointer;" title="Edit Organization" onclick="editOrg(${orgs[i].id})"></a>
                            </td>
                        </tr>
                    `;
                    // <td>${orgs[i].id}</td>
                }else {

                    html += `
                        <tr data-widget="expandable-table" aria-expanded="false">
                            <td><i class="expandabFvle-table-caret fas fa-caret-right fa-fw"></i></td> 
                            <td>${orgs[i].name}</td>
                            <td>${orgs[i].address}</td>
                            <td>${orgs[i].city}</td>
                            <td>${orgs[i].state}</td>
                            <td>${orgs[i].zipcode}</td>
                            <td>${orgs[i].contact}</td>
                            <td>${formatednumber}</td>
                            <td>${orgs[i].created_at}</td>
                            <td>
                                <a class="fas fa-edit text-primary mx-1" style="cursor: pointer;" title="Edit Organization" onclick="editOrg(${orgs[i].id})"></a>
                            </td>
                        </tr>
                    `;
                    // <td>${orgs[i].id}</td>
                }
                // <th>ID</th>
                // <td>${p.id}</td>
                html += `
                    <tr class="expandable-body d-none">
                        <td colspan="10">
                            <div class="table-responsive">
                                <table class="table table-hover table-bordered">
                                    <thead>
                                        <tr>
                                            <th>Property Image</th>
                                            <th>Property Name</th>
                                            <th>Address</th>
                                            <th>City</th>
                                            <th>State</th>
                                            <th>Zip</th>
                                            <th>Contact</th>
                                            <th>Contact Phone</th>
                                            <th>Property Type</th>
                                            <th>Created</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        ${orgProperties.map(p => {
                                            let property_image = "/include/images/door_image.png";
                                            if (p.image_path && p.image_path !== "" && p.image_path !== undefined) {
                                                property_image = `/shared/serve_image.php?path=${p.image_path}&type=property`;
                                            }

                                            return `
                                                <tr>
                                                    <td>
                                                        <div onclick="show_property_image('property_image_modal', 'property_image', '${property_image}')">
                                                            <img src="${property_image}" alt="property image" class="img-thumbnail door-image-clickable" 
                                                             style="width: 60px; height: 60px; margin-right: 10px; cursor: pointer;" title="Click to view larger image" data-image='${property_image}' data-name='${p.name || 'Property'}'>
                                                        </div>
                                                    </td>
                                                    <td>${p.name}</td>
                                                    <td>${p.address}</td>
                                                    <td>${p.city}</td>
                                                    <td>${p.state}</td>
                                                    <td>${p.zipcode}</td>
                                                    <td>${p.contact}</td>
                                                    <td>${formatphoneNumber(p.contact_phone_number)}</td>
                                                    <td>${p.property_type}</td>
                                                    <td>${p.created_at}</td>
                                                    <td>
                                                        <a class="fas fa-edit text-primary" style="cursor: pointer;" 
                                                           title="Edit Property" onclick="editProp(${p.id})"></a>
                                                        ${p.check_voip === 0 
                                                            ? '<a class="fas fa-plus text-primary " style="cursor: pointer; font-size:25px;" title="Add VOIP Setting" onclick="add_voip_setting(' + p.id + ', `' + p.name + '`)"></a>' 
                                                            : ''}
                                                    </td>
                                                </tr>
                                            `;
                                        }).join('')}
                                    </tbody>
                                </table>
                            </div>
                        </td>
                    </tr>
                `;
            }
        }
        orgtble.innerHTML = html;
    }else if (admins.style.display !== "none" && document.body.contains(admins)) {
        let organizations = orgs;
        let props = properties;
        let orgToProps = {};

        props.forEach(prop => {
            if (!orgToProps[prop.organization_id]) {
                orgToProps[prop.organization_id] = [];
            }
            orgToProps[prop.organization_id].push(prop.id.toString());
        });

        let orgList = $("#orgList");
        let propList = $("#propList");

        if (!orgList) {
            console.warn("Edge issue: `orgList` not found in the DOM");
        } else {
            orgList.empty();
            organizations.forEach(org => {
                orgList.append(`
                    <li class="list-group-item">
                        <input type="checkbox" class="org-checkbox" data-org-id="${org.id}">
                        ${org.name}
                    </li>
                `);
            });
        }

        if (!propList) {
            console.warn("Edge issue: `propList` not found in the DOM");
        } else {
            propList.empty();
            props.forEach(prop => {
                propList.append(`
                    <li class="list-group-item">
                        <input type="checkbox" class="prop-checkbox" data-prop-id="${prop.id}" data-org-id="${prop.organization_id}">
                        ${prop.name}
                    </li>
                `);
            });
        }

        $(document).on("change", ".org-checkbox", function () {
            let orgId = $(this).data("org-id");
            let isChecked = $(this).is(":checked");

            $(".prop-checkbox[data-org-id='" + orgId + "']").prop("checked", isChecked);
        });

        $(document).on("change", ".prop-checkbox", function () {
            let orgId = $(this).data("org-id");
            let allPropsChecked = $(".prop-checkbox[data-org-id='" + orgId + "']:checked").length === $(".prop-checkbox[data-org-id='" + orgId + "']").length;

            $(".org-checkbox[data-org-id='" + orgId + "']").prop("checked", allPropsChecked);
        });

        $(document).on("change", ".org-checkbox", function () {
            let orgId = $(this).data("org-id");
            if (!$(this).is(":checked")) {
                $(".prop-checkbox[data-org-id='" + orgId + "']").prop("checked", false);
            }
        });

        $("#savePermissions").click(function () {
            let selectedOrgs = [];
            $(".org-checkbox:checked").each(function () {
                selectedOrgs.push($(this).data("org-id"));
            });

            let selectedProps = [];
            $(".prop-checkbox:checked").each(function () {
                selectedProps.push($(this).data("prop-id"));
            });

            $("#selectedOrganizations").val(selectedOrgs.join(","));
            $("#selectedProperties").val(selectedProps.join(","));

            $('#permissionsModal').modal('hide');
        });
    }else if (editdealeradmins.style.display !== "none" && document.body.contains(editdealeradmins)) {

        let organizations = orgs;
        let props = properties;
        let orgToProps = {};

        props.forEach(prop => {
            if (!orgToProps[prop.organization_id]) {
                orgToProps[prop.organization_id] = [];
            }
            orgToProps[prop.organization_id].push(prop.id.toString());
        });

        let orgList = $("#editOrgList");
        let propList = $("#editPropList");

        if (!orgList) {
            console.warn("Edge issue: `orgList` not found in the DOM");
        } else {
            orgList.empty();
            organizations.forEach(org => {
                orgList.append(`
                    <li class="list-group-item">
                        <input type="checkbox" class="org-checkbox" data-org-id="${org.id}">
                        ${org.name}
                    </li>
                `);
            });
        }

        if (!propList) {
            console.warn("Edge issue: `propList` not found in the DOM");
        } else {
            propList.empty();
            props.forEach(prop => {
                propList.append(`
                    <li class="list-group-item">
                        <input type="checkbox" class="prop-checkbox" data-prop-id="${prop.id}" data-org-id="${prop.organization_id}">
                        ${prop.name}
                    </li>
                `);
            });
        }

        $(document).on("change", ".org-checkbox", function () {
            let orgId = $(this).data("org-id");
            let isChecked = $(this).is(":checked");

            $(".prop-checkbox[data-org-id='" + orgId + "']").prop("checked", isChecked);
        });

        $(document).on("change", ".prop-checkbox", function () {
            let orgId = $(this).data("org-id");
            let allPropsChecked = $(".prop-checkbox[data-org-id='" + orgId + "']:checked").length === $(".prop-checkbox[data-org-id='" + orgId + "']").length;

            $(".org-checkbox[data-org-id='" + orgId + "']").prop("checked", allPropsChecked);
        });

        $(document).on("change", ".org-checkbox", function () {
            let orgId = $(this).data("org-id");
            if (!$(this).is(":checked")) {
                $(".prop-checkbox[data-org-id='" + orgId + "']").prop("checked", false);
            }
        });

        $("#saveEditPermissions").click(function () {
            let selectedOrgs = [];
            $(".org-checkbox:checked").each(function () {
                selectedOrgs.push($(this).data("org-id"));
            });

            let selectedProps = [];
            $(".prop-checkbox:checked").each(function () {
                selectedProps.push($(this).data("prop-id"));
            });

            $("#uselectedOrganizations").val(selectedOrgs.join(","));
            $("#uselectedProperties").val(selectedProps.join(","));

            $('#editPermissionsModal').modal('hide');
        });
    }else {
        console.error('Element with ID orgtble not found');
    }
}

function add_voip_setting(val, prop_name){
    $("#voip_property_name").text(prop_name);
    $("#voip_prop_id").val(val);
    $("#confirm_voip_modal").modal("show");
}

function show_property_image(model_id, image_id, image){
  document.getElementById(image_id).src = image;
  $("#"+model_id).modal('show');
}

function add_property_voip_setting(){
    var property_id = $("#voip_prop_id").val();
    $.ajax({
        url: 'include/properties/property.php',
        type: 'post',
        data: {add_voip_setting: 'yes', property_id:property_id},
        success: function(response) {
            if(response == 2){
                $("#confirm_voip_modal").modal("hide");
                $("#update_property_message").html("<p class='alert alert-danger'>VOIP setting not added</p>");
            }
            else if(response == 3){
                $("#confirm_voip_modal").modal("hide");
                $("#update_property_message").html("<p class='alert alert-danger'>No delaer assigned to this property</p>");
            }
            else{
                $("#confirm_voip_modal").modal("hide");
                $("#update_property_message").html("<p class='alert alert-success'>Property VOIP setting updated successfully</p>");
                myProperties();
            }

            setTimeout(function() {
                $("#update_property_message").hide();
            }, 2000);
            
        },
        error: function(xhr, status, error) {
            console.error('Failed to fetch data:', status, error);
        }
    }); 
}

function dealer_properties(dealer_id){
    let select = $('#dealer_properties');
    select.empty();
    select.append('<option value="">Please Select Property</option>');
    if(dealer_id != ""){
        $.ajax({
            url: 'include/signalwire/numbers.php',
            type: 'post',
            data: { dealerProperties: 'yes', dealer_id:dealer_id },
            success: function(response) {
                let data = JSON.parse(response);
                let properties = data.properties;
                properties.forEach(function(prop) {
                    select.append(DOMPurify.sanitize('<option value="' + prop.id + '">' + prop.name + '</option>'));
                });
            },
            error: function(xhr, status, error) {
                console.error('Failed to fetch data:', status, error);
            }
        });
    }    
}

function mySignalwireNumbers() {
    
    if (document.getElementById("dealerslotsbtn")) {
        loadDealerSlots();
    }

    $.ajax({
        url: 'include/signalwire/numbers.php',
        type: 'post',
        data: { getdata: 'yes' },
        success: function(response) {
            let data = JSON.parse(response);
            let purchased_numbers = data.purchased_numbers;
            let dealers = data.dealers;
            let user_role = data.user_layer;
            let html = '';
            let sgwnumbers = document.getElementById("sgwnumbers");
            let select = $('#numbers_dealers');
            select.empty();
            select.append('<option value="">Please Select Delaer</option>');
            dealers.forEach(function(dls) {

                select.append(DOMPurify.sanitize('<option value="' + dls.id + '">' + dls.firstname + ' ' + dls.lastname + '</option>'));
            });
            // if ($.fn.DataTable.isDataTable("#my_ii_purchased_numbers")) {
            //   $("#my_ii_purchased_numbers").DataTable().clear().draw();
            // }
            if (sgwnumbers) {
                if(purchased_numbers !== 0){
                    if (purchased_numbers.length != 0) {
                        if((user_role == 'super_admin') || (user_role == 'admin')){
                            for (var i = 0; i < purchased_numbers.length; i++) {
                                html += "<tr><td>" + purchased_numbers[i].phone_number + "</td><td>" + convertNullToEmptyString(purchased_numbers[i].property_name) + "</td><td>" + purchased_numbers[i].status + "</td><td>" + convertNullToEmptyString(purchased_numbers[i].firstname) + ' ' + convertNullToEmptyString(purchased_numbers[i].lastname) + "</td><td>" + purchased_numbers[i].phone_sid + "</td><td>" + convertNullToEmptyString(purchased_numbers[i].voice_url) + "</td><td>" + convertNullToEmptyString(purchased_numbers[i].sms_url) + "</td><td><button class='btn btn-primary mr-1' onclick=editSignalNumber('" + purchased_numbers[i].phone_number + "'," + purchased_numbers[i].dealer_id + "," + purchased_numbers[i].property_id + "," + purchased_numbers[i].id +")><i class='fa fa-pencil'></i></button><button class='btn btn-primary mr-1' onclick=applyNumberUrl('" + purchased_numbers[i].phone_sid + "')>Apply Url</button><button class='btn btn-danger mr-1' onclick=remove_number('" + purchased_numbers[i].phone_number + "') title='Release Number'><i class='fa fa-trash'></i></button></td></tr>";
                            }
                        }
                        else{
                            for (var i = 0; i < purchased_numbers.length; i++) {
                                html += "<tr><td>" + purchased_numbers[i].phone_number + "</td><td>" + convertNullToEmptyString(purchased_numbers[i].property_name) + "</td><td>" + purchased_numbers[i].status + "</td><td><button class='btn btn-danger mr-1' onclick=remove_number('" + purchased_numbers[i].phone_number + "') title='Release Number'><i class='fa fa-trash'></i></button></td></tr>";
                            }                    
                        }
                    }
                }
                else{
                    $("#success_message").show();
                        $("#success_message").html("<h4 class='alert alert-danger'>Please add VOIP credentials first</h4>");
                        setInterval(function(){ 
                            $("#success_message").hide();
                        }, 5000);
                    // html = "<tr><td colspan='7' class='text-center'>No numbers available</td></tr>";

                }
                if ($.fn.DataTable.isDataTable("#my_ii_purchased_numbers")) {
                    $("#my_ii_purchased_numbers").DataTable().destroy();
                }
                sgwnumbers.innerHTML = html;

                load_datatable("my_ii_purchased_numbers", "my_numbers");
            } else {
                console.error('Numbers not found');
            }

        },
        error: function(xhr, status, error) {
            console.error('Failed to fetch data:', status, error);
        }
    });
}

function remove_number(number){
    $("#delete_sg_number").html(number);
    $("#delete_number_val").val(number);
    $("#delete_number_modal").modal('show');
}

function delete_number(){
    var number = $("#delete_number_val").val();
    if(number != ""){
        $("#delete_number_modal").modal('hide');
        $.ajax({
            url: 'include/signalwire/numbers.php',
            type: 'post',
            data: {number:number, deletesgnumber:'yes3'},
            success: function(response) {
                
                $("#success_message").show();
                $("#success_message").html(response);
                setInterval(function(){ 
                    $("#success_message").hide();
                }, 8000);
            },
            error: function(xhr, status, error) {
                console.error('Failed to fetch data:', status, error);
            }

        });  
    }

}

function editSignalNumber(number, dealer_id, property_id, number_id){
    $("#assign_number_id").val(number_id);
    $("#assign_dealer_number").val(number);
    if((dealer_id != "") && (dealer_id != 0)){
        $("#numbers_dealers").val(dealer_id).change();
    }
    setTimeout(function() {
        if((property_id != "") && (property_id != 0)){
            $("#dealer_properties").val(property_id).change();
        }
        $("#dealer_assign_number").modal('show');    
    }, 400);
    
}

function applyNumberUrl(sid){
    if (document.getElementById("dealerslotsbtn")) {
        loadDealerSlots();
    }
    $.ajax({
        url: 'include/signalwire/apply_url.php',
        type: 'post',
        data: {sid:sid, act:'apply_url'},
        success: function(response) {
            if(response == 1){
                resumeTab('include/signalwire/my_numbers.php');
            }
            
        },
        error: function(xhr, status, error) {
            console.error('Failed to fetch data:', status, error);
        }
    });   
}

function searchNumbers(number_type, val=''){
    $("#sg_number_type").val(number_type);
    let contains = "";
    let in_region = "";
    let area_code = "";
    let number_terms = "";
    if(number_type == 'Local' && val == 'search'){
        contains = document.getElementById("search_number_type").value;
        in_region = document.getElementById("search_number_state").value;
        area_code = document.getElementById("search_number_areacode").value;
        number_terms = document.getElementById("search_number_term").value;
    }
    else if(number_type == 'TollFree' && val == 'search'){
        contains = document.getElementById("toll_search_number_type").value;
        number_terms = document.getElementById("toll_search_number_term").value;
    }
    $.ajax({
        url: 'include/signalwire/numbers.php',
        type: 'post',
        data: {seachNumber: number_type, contains:contains, number_terms:number_terms, in_region:in_region, area_code:area_code},
        success: function(response) {
            let data = JSON.parse(response);
            let html = '';
            let local_numbers_table = document.getElementById("localNumbers");
            // let toll_free_numbers_table = document.getElementById("tollFreeNumbers");

            if(data != 0){
                let searched_numbers = data.searched_numbers;
                let user_layer = data.layer;
                // toll_free_numbers_table.innerHTML = "";
                // if ($.fn.DataTable.isDataTable("#available_local_numbers")) {
                //   $("#available_local_numbers").DataTable().clear().draw();
                // }
                if (searched_numbers.length != 0){
                    for (var i = 0; i < searched_numbers.length; i++) {

                        html += "<tr><td>" + searched_numbers[i].friendly_name + "</td><td>" + searched_numbers[i].phone_number + "</td><td><button class='btn btn-primary' onclick=show_purchase_modal('" + searched_numbers[i].phone_number + "','" + user_layer + "')>Buy</button></td></tr>";
                    }
                }
                
                // else{
                //     toll_free_numbers_table.innerHTML = html;
                // } 
            }
            if ($.fn.DataTable.isDataTable("#available_local_numbers")) {
                $("#available_local_numbers").DataTable().destroy();
            }
            if(number_type == 'Local'){
                local_numbers_table.innerHTML = html;
            }
            
            if ($.fn.DataTable.isDataTable("#available_local_numbers")) {
                $("#available_local_numbers").DataTable().destroy();
            }
 
            $("#available_local_numbers").DataTable({
                "responsive": true,
                "order": [],
                "paging": false,
                "pageLength": -1,
                // "lengthMenu": [ [10, 25, 50, 100], [10, 25, 50, 100] ],
                "searching": false,
                
            });
            
            
        },
        error: function(xhr, status, error) {
            console.error('Failed to fetch data:', status, error);
        }
    });   
}

function convertNullToEmptyString(value) {
    return value === null ? '' : value;
}

function show_purchase_modal(number, layer){
    $("#admin_buy_number_message").hide();
    $("#dealer_buy_number_message").hide();

    // if(layer == "dealer"){
        $("#buy_number_property_menu").hide();
    
        let select = $('#buy_number_for_property');
        select.empty();
    
        $.ajax({
            url: 'include/signalwire/numbers.php',
            type: 'post',
            data: {check_limit_for_number: 'yes'},
            success: function(response) {
                let data = JSON.parse(response);
                if(data.user_role === "super_admin" || data.user_role === "admin"){
                    let properties = data.properties;
                    $("#dealer_buy_number_message").html("Please select property");
                    var s_prop = $("#selectproperty").val();
                    properties.forEach(function(pro) {
                        selected_p = "";
                        if(s_prop == pro.id){
                            selected_p = "selected";
                        }
                        select.append(DOMPurify.sanitize('<option value="' + pro.id + '"' + selected_p + '>' + pro.name + '</option>'));
                    });
                    $("#dealer_buy_number_message").show();
                    $("#buy_number_property_menu").show();
                    $("#purchase_number_modal").modal('show');
                    $("#puchase_number_val").val(number);
                }
                else if(data.user_role === "dealer"){
                    $("#admin_buy_number_message").hide();
                    if(data.calculate_number == 0){
                        $("#success_message").show();
                        $("#success_message").html("<h4 class='alert alert-danger'>Please contact with admin for additional numbers</h4>");
                        setInterval(function(){ 
                            $("#success_message").hide();
                        }, 5000);
                    }
                    else{
                        let properties = data.properties;
                        $("#dealer_buy_number_message").html(data.calculate_number);
                        properties.forEach(function(pro) {
                            let option = $('<option>', {
                                value: pro.id,  // Set the value attribute
                                text: pro.name  // Set the text of the option (text() auto-escapes to prevent XSS)
                            });
                            // if (selected_p) {
                            //     option.attr('selected', 'selected'); // Add the selected attribute if necessary
                            // }
                            select.append(option);
                            // select.append('<option value="' + pro.id + '">' + pro.name + '</option>');
                        });
                        $("#dealer_buy_number_message").show();
                        $("#buy_number_property_menu").show();
                        $("#purchase_number_modal").modal('show');
                        $("#puchase_number_val").val(number);
                    }
                }
                
            },
            error: function(xhr, status, error) {
                console.error('Failed to fetch data:', status, error);
            }
        });
    // } else {
    //     $("#admin_buy_number_message").show();
    //     $("#purchase_number_modal").modal('show');
    // }
}

function purchase_number(){
    var number_type = document.getElementById("sg_number_type").value;
    var number = document.getElementById("puchase_number_val").value;
    $("#purchase_number_modal").modal('hide');
    var number_user_layer = document.getElementById("number_user_layer").value;
    // if(number_user_layer == "dealer"){
        var property_id = document.getElementById("buy_number_for_property").value;
        $.ajax({
            url: 'include/signalwire/numbers.php',
            type: 'post',
            data: {purchase_number: 'yes', number:number, property_id:property_id, number_type:number_type},
            success: function(response) {
                $("#purchased-numbers-tab").click();
                $("#success_message").show();
                $("#success_message").html(response);
                setInterval(function(){ 
                    $("#success_message").hide();
                }, 5000);
            },
            error: function(xhr, status, error) {
                console.error('Failed to fetch data:', status, error);
            }
        });
    // }
    // else{

    //     $.ajax({
    //         url: 'include/signalwire/numbers.php',
    //         type: 'post',
    //         data: {purchase_number: 'yes', number:number},
    //         success: function(response) {
    //             $("#success_message").show();
    //             $("#success_message").html(response);
    //             setInterval(function(){ 
    //                 $("#success_message").hide();
    //             }, 5000);
    //         },
    //         error: function(xhr, status, error) {
    //             console.error('Failed to fetch data:', status, error);
    //         }
    //     });
    // }
    
}

function assignNumerToDealer(){
    let number_id = $("#assign_number_id").val();
    let phone_number = $("#assign_dealer_number").val();
    let dealer_id = $("#numbers_dealers").val();
    let property_id = $("#dealer_properties").val();
    $.ajax({
        url: 'include/signalwire/numbers.php',
        type: 'post',
        data: {assign_dealer_number: 'yes', phone_number:phone_number, dealer_id:dealer_id, number_id:number_id, property_id:property_id},
        success: function(response) {
            $("#dealer_assign_number").modal('hide');
            $("#success_message").show();
            $("#success_message").html(response);
            setInterval(function(){ 
                $("#success_message").hide();
            }, 3000);
        },
        error: function(xhr, status, error) {
            console.error('Failed to fetch data:', status, error);
        }
    });
}

function myProperties() {
    $.ajax({
        url: 'include/properties/property.php',
        type: 'post',
        data: { getdata: 'yes' },
        success: function(response) {
            let data = JSON.parse(response);
            let organizations = data.organizations;
            let properties = data.properties;
            console.log(organizations);
            myOrganizations(organizations, properties);
        },
        error: function(xhr, status, error) {
            console.error('Failed to fetch data:', status, error);
        }
    });
}


$(window).on('resize', function() {
    setTimeout(function() {
        $("#propertiesTable").DataTable().columns.adjust().responsive.recalc();
    }, 350);
});

$(window).on('resize', function() {
    setTimeout(function() {
        $("#operatorsTable").DataTable().columns.adjust().responsive.recalc();
    }, 350);
});

$(window).on('resize', function() {
    setTimeout(function() {
        $("#visitorsTable").DataTable().columns.adjust().responsive.recalc();
    }, 350);
});

$(window).on('resize', function() {
    setTimeout(function() {
        $("#vendorsTable").DataTable().columns.adjust().responsive.recalc();
    }, 350);
});

$(window).on('resize', function() {
    setTimeout(function() {
        $("#adminTable").DataTable().columns.adjust().responsive.recalc();
    }, 350);
});

$(window).on('resize', function() {
    setTimeout(function() {
        $("#dealersTable").DataTable().columns.adjust().responsive.recalc();
    }, 350);
});

$('#sidebarToggle').on('click', function () {
    setTimeout(function () {
        $('#adminTable').DataTable().columns.adjust().responsive.recalc();
        $('#dealersTable').DataTable().columns.adjust().responsive.recalc();
        $('#propertiesTable').DataTable().columns.adjust().responsive.recalc();
        $('#operatorsTable').DataTable().columns.adjust().responsive.recalc();
        $('#visitorsTable').DataTable().columns.adjust().responsive.recalc();
        $('#vendorsTable').DataTable().columns.adjust().responsive.recalc();
        $('#deletedOper').DataTable().columns.adjust().responsive.recalc();
        $('#deletedUser').DataTable().columns.adjust().responsive.recalc();
    }, 325);
});

$('#manage-tab').on('click', function () {
    setTimeout(function () {
        $('#deletedOper').DataTable().columns.adjust().responsive.recalc();
        $('#deletedUser').DataTable().columns.adjust().responsive.recalc();
    }, 325);
});
function adminSetup() {
    let html = "";
    document.getElementById("admintble").innerHTML = html;

    $.ajax({
        url: "include/admin/admin_db.php",
        type: "post",
        data: { getadmin: "yes" },
    }).done(function (data) {
        if (data) {
            var json = JSON.parse(data);
            var jsonc = json['current'];
            var jsoni = json['invited'];

            for (let i = 0; i < jsonc.length; i++) {

                html =
                        "<tr><td>" + jsonc[i].company_name + "</td>" +
                        "<td>" + jsonc[i].name + "</td>" +
                        "<td>" + jsonc[i].layer + "</td>" + 
                        "<td>" + jsonc[i].email + "</td>" + 
                        "<td>" + jsonc[i].slots_avail + "</td>" +
                        "<td>" + jsonc[i].slots_used + "</td>" +
                        "<td>" + jsonc[i].created + "</td>" + 
                        "<td>" + jsonc[i].id + "</td>";

                html += "<td>" +
                        "<a class='fas fa-edit text-primary mx-1 cursor_pointer editAdminButton' title='Edit User' data-id='" + jsonc[i].id + "'></a>" +
                        "</td></tr>";


                document.getElementById("admintble").innerHTML += DOMPurify.sanitize(html);

                let $adminTableContainer = $("#admintble");
                $adminTableContainer.off("click", ".editAdminButton");

                $container.on("click", ".editAdminButton", function () {
                    const id = $(this).data("id");
                    editAdmin(id);
                });
            }

            for (let i = 0; i < jsoni.length; i++) {
                html =
                        "<tr><td>" + jsoni[i].company_name + "</td>" +
                        "<td>Not Registered</td>" +
                        "<td>" + jsoni[i].role + "</td>" + 
                        "<td>" + jsoni[i].email + "</td>" + 
                        "<td>" + jsoni[i].dealer_slots + "</td>" +
                        "<td>0</td>" +
                        "<td>" + jsoni[i].created_at + "</td>" + 
                        "<td>" + jsoni[i].id + "</td>";
                        
                html += "<td>" +
                        "<form method='POST' action='include/admin/admin_db.php' style='display:inline;'>" +
                        "<input type='hidden' name='userid' value='" + jsoni[i].id + "'>" +
                        "<input type='hidden' name='resendInvite' value='yes'>" +
                        "<button type='submit' class='fa-regular fa-paper-plane' style='cursor: pointer; background: none; border: none;' title='Resend Invitation'></button>" +
                        "</form>" +
                        "</td></tr>";
                document.getElementById("admintble").innerHTML += html;
            }

            if (!$.fn.DataTable.isDataTable("#admintble")) {
                $("#admintble").parent().DataTable({
                    "responsive": true,
                    "autoWidth": false,
                    "scrollX": true,
                    "scrollY": "400px",
                    "scrollCollapse": true,
                    "ordering": true,
                    "order": [],
                    "orderFixed": [],
                    "columnDefs": [
                        { "orderable": false, "targets": -1 },
                    ],
                    "paging": true,
                    "pagingType": "full_numbers",
                    "pageLength": 10,
                    "lengthMenu": [ [10, 25, 50, 100], [10, 25, 50, 100] ],
                    "searching": false,
                    "createdRow": function(row, data, dataIndex) {
                        if (data[4] === "High") {
                            $(row).addClass('highlight');
                        }
                    },
                    "retrieve": true,
                    "drawCallback": function(settings) {
                        const api = this.api();
                        const pageInfo = api.page.info();

                        // Hide pagination controls if only one page
                        if (pageInfo.pages <= 1) {
                            $('.dataTables_paginate').hide();
                        } else {
                            $('.dataTables_paginate').show();
                        }
                    }
                
                });
            } else {
                $("#admintble").DataTable().order([]).draw(); // Ensure no initial order if already initialized
            }

        } else {
        return;
        }
    });
}

function doorsGates(status = "") {
    $.ajax({
        url: "include/property_builder/gate_doors.php",
        type: "post",
        data: { getDoorsGate: "yes" },
    }).done(async function (data) {
        let json = await parseJSONData(data);
        let my_phone_numbers = json.phone_numbers;
        let my_call_flow = json.my_call_flow;
        let property_users_numbers = json.property_users_numbers;
        list_property_numbers(property_users_numbers);
        let file_url = json.base_url;

        if (my_call_flow != 0) {
            $("#my_call_flow_content").removeClass('showHide');
            my_call_flow_data(my_call_flow, file_url);
        } else {
            $("#my_call_flow_content").addClass('showHide');
            $("#add_call_flow_btn").removeClass('showHide');
        }

        let select = $('#door_phone_number');
        select.empty();

        // Add default option
        select.append($('<option>', {
            value: '',
            text: 'Please select number'
        }));

        // Safely add each phone number
        my_phone_numbers.forEach(function (mn) {
            let option = $('<option>', {
                value: mn.id,
                text: mn.phone_number // text() escapes the value to prevent XSS
            });
            select.append(option);
        });
    }).fail(function (xhr, status, error) {
        console.error("Failed to fetch phone numbers:", status, error);
    });
}


function get_data_default($file_url, radio_id, aud_file, aud_attr){
    // var path_audio = $file_url;
    // var path_aud = "../../" + aud_file;
    $('#'+radio_id).click();
    // $('#'+aud_attr).attr('src', path_aud);
}

function get_data_upload_file_record($file_url, radio_id, aud_file, aud_attr_id, hid_val){
    var path_audio = $file_url;
    var path_aud = "/shared/serve_audios.php?path=" + aud_file;
    $('#'+radio_id).click();
    $('#'+aud_attr_id).attr('src', path_aud);
    $('#'+aud_attr_id).removeClass('showHide');
    $('#'+hid_val).val(aud_file);
}

function txt_to_speech_data($file_url, radio_id, text_id, txt, voice_id, voice_val){
    $('#'+voice_id+"_"+voice_val).click();
    $('#'+radio_id).click();
    $('#'+text_id).val(txt);
}
function list_property_numbers(property_users_numbers){
    // console.log(property_users_numbers);
    let select = $('#first_owner_number');
    select.empty();
    select.append('<option value="">Please select number</option>');
    let select2 = $('#second_owner_number');
    select2.empty();
    select2.append('<option value="">Please select number</option>');
    let select3 = $('#third_owner_number');
    select3.empty();
    select3.append('<option value="">Please select number</option>');

    if(property_users_numbers != 0){
        property_users_numbers.forEach(function(user_number) {  
            if(user_number.mobile_number != ""){
                select.append('<option value="' + user_number.mobile_number + '" data-icon="fas fa-mobile-button"> &nbsp;' + user_number.firstname + " " + user_number.lastname  + " / " + user_number.mobile_number + '</option>');
                select2.append('<option value="' + user_number.mobile_number + '" data-icon="fas fa-mobile-button"> &nbsp;' + user_number.firstname + " " + user_number.lastname  + " / " + user_number.mobile_number + '</option>');
                select3.append('<option value="' + user_number.mobile_number + '" data-icon="fas fa-mobile-button"> &nbsp;' + user_number.firstname + " " + user_number.lastname  + " / " + user_number.mobile_number + '</option>');
            }  

            var home_extension = "";
            if(user_number.home_extension != "" && user_number.home_extension != null){
                home_extension = user_number.home_extension;
            }
            if(user_number.home_number != ""){
                select.append('<option value="' + user_number.home_number + home_extension + '" data-icon="fas fa-phone"> ' + user_number.firstname + " " + user_number.lastname  + " / " + user_number.home_number + home_extension + '</option>'); 
                select2.append('<option value="' + user_number.home_number + home_extension + '" data-icon="fas fa-phone"> ' + user_number.firstname + " " + user_number.lastname  + " / " + user_number.home_number + home_extension + '</option>'); 
                select3.append('<option value="' + user_number.home_number + home_extension + '" data-icon="fas fa-phone"> ' + user_number.firstname + " " + user_number.lastname  + " / " + user_number.home_number + home_extension + '</option>'); 
            }
        });
        
        $('.select2_icon').select2({
            templateResult: formatOption, // For dropdown options
            templateSelection: formatOption // For selected option
        });

          
    }
}

function formatOption(option) {
    if (!option.id) {
      return option.text; // Return the default option (placeholder)
    }
    const icon = $(option.element).data('icon'); // Get icon from `data-icon`
    return $(`<span><i class="${icon}"></i> ${option.text}</span>`);
}

function my_call_flow_data(call_data, $file_url){
    if(call_data.is_first_default_message == 1){
        get_data_default($file_url, 'radioPrimary1', call_data.first_audio_file, 'first_default_message_audio');
    }
    else if(call_data.is_first_upload_audio == 1){
        get_data_upload_file_record($file_url, 'radioPrimary34', call_data.first_audio_file, 'is_first_upload_audio_field_audio', 'is_first_upload_audio_field_hidden');
    }
    else if(call_data.is_first_record_audio == 1){
        get_data_upload_file_record($file_url, 'radioPrimary2', call_data.first_audio_file, 'call_flow_first_audio_play_back', 'update_first_record_audio_field');
        
    }
    else if(call_data.is_first_textto_speech == 1){
        txt_to_speech_data($file_url, 'radioPrimary3', 'is_first_textto_speech_field', call_data.first_text, 'first_message_vocie_select', call_data.first_message_vocie_select);
    }

    if(call_data.is_no_response_default_message == 1){
        get_data_default($file_url, 'radioPrimary4', call_data.no_response_audio_file, 'no_response_default_message_audio');
    }
    else if(call_data.is_no_response_upload_audio == 1){
        get_data_upload_file_record($file_url, 'radioPrimary35', call_data.no_response_audio_file, 'is_no_response_upload_audio_field_audio', 'is_no_response_upload_audio_field_hidden');
    }
    else if(call_data.is_no_response_record_audio == 1){
        get_data_upload_file_record($file_url, 'radioPrimary5', call_data.no_response_audio_file, 'call_flow_first_end_audio_play_back', 'is_no_response_record_audio_field_hidden');
        
    }
    else if(call_data.is_no_response_textto_speech == 1){
        txt_to_speech_data($file_url, 'radioPrimary6', 'is_no_response_textto_speech_field', call_data.no_response_text, 'no_response_vocie_select', call_data.no_response_vocie_select);
    }

    if(call_data.is_hang_up_message == 1){
        $("#radioPrimary8").click();
    }

    if(call_data.press2_default_message == 1){
        get_data_default($file_url, 'radioPrimary41', call_data.press2_audio_file, 'press2_default_message_audio');
    }
    else if(call_data.press2_upload_audio == 1){
        get_data_upload_file_record($file_url, 'radioPrimary42', call_data.press2_audio_file, 'press2_upload_audio_field_audio', 'press2_upload_audio_field_hidden');
    }
    else if(call_data.press2_record_audio == 1){
        get_data_upload_file_record($file_url, 'radioPrimary43', call_data.press2_audio_file, 'press2_audio_play_back', 'press2_record_audio_field_hidden');
        
    }
    else if(call_data.press2_textto_speech == 1){
        txt_to_speech_data($file_url, 'radioPrimary44', 'press2_textto_speech_field', call_data.press2_text, 'press2_vocie_select', call_data.press2_vocie_select);
    }

    if(call_data.press2_auth_code_default_message == 1){
        get_data_default($file_url, 'radioPrimary45', call_data.press2_auth_code_audio_file, 'press2_auth_code_default_message_audio');
    }
    else if(call_data.press2_auth_code_upload_audio == 1){
        get_data_upload_file_record($file_url, 'radioPrimary46', call_data.press2_auth_code_audio_file, 'press2_auth_code_upload_audio_field_audio', 'press2_auth_code_upload_audio_field_hidden');
    }
    else if(call_data.press2_auth_code_record_audio == 1){
        get_data_upload_file_record($file_url, 'radioPrimary47', call_data.press2_auth_code_audio_file, 'press2_auth_code_audio_play_back', 'press2_auth_code_record_audio_field_hidden');
        
    }
    else if(call_data.press2_auth_code_textto_speech == 1){
        txt_to_speech_data($file_url, 'radioPrimary48', 'press2_auth_code_textto_speech_field', call_data.press2_auth_code_text, 'press2_auth_vocie_select', call_data.press2_auth_vocie_select);
    }

    if(call_data.press2_auth_code_ack_default_message == 1){
        get_data_default($file_url, 'radioPrimary49', call_data.press2_auth_code_ack_audio_file, 'press2_auth_code_ack_default_message_audio');
    }
    else if(call_data.press2_auth_code_ack_upload_audio == 1){
        get_data_upload_file_record($file_url, 'radioPrimary50', call_data.press2_auth_code_ack_audio_file, 'press2_auth_code_ack_upload_audio_field_audio', 'press2_auth_code_ack_upload_audio_field_hidden');
    }
    else if(call_data.press2_auth_code_ack_record_audio == 1){
        get_data_upload_file_record($file_url, 'radioPrimary51', call_data.press2_auth_code_ack_audio_file, 'press2_auth_code_ack_audio_play_back', 'press2_auth_code_ack_record_audio_field_hidden');       
    }
    else if(call_data.press2_auth_code_ack_textto_speech == 1){
        txt_to_speech_data($file_url, 'radioPrimary52', 'press2_auth_code_ack_textto_speech_field', call_data.press2_auth_code_ack_text, 'press2_auth_ack_vocie_select', call_data.press2_auth_ack_vocie_select);
    }

    if(call_data.press2_auth_code_access_default_message == 1){
        get_data_default($file_url, 'radioPrimary53', call_data.press2_auth_code_access_audio_file, 'press2_auth_code_access_default_message_audio');
    }
    else if(call_data.press2_auth_code_access_upload_audio == 1){
        get_data_upload_file_record($file_url, 'radioPrimary54', call_data.press2_auth_code_access_audio_file, 'press2_auth_code_access_upload_audio_field_audio', 'press2_auth_code_access_upload_audio_field_hidden');
    }
    else if(call_data.press2_auth_code_access_record_audio == 1){
        get_data_upload_file_record($file_url, 'radioPrimary55', call_data.press2_auth_code_access_audio_file, 'press2_auth_code_access_audio_play_back', 'press2_auth_code_access_record_audio_field_hidden');       
    }
    else if(call_data.press2_auth_code_access_textto_speech == 1){
        txt_to_speech_data($file_url, 'radioPrimary56', 'press2_auth_code_access_textto_speech_field', call_data.press2_auth_code_access_text, 'press2_auth_access_vocie_select', call_data.press2_auth_access_vocie_select);
    }

    if(call_data.press2_auth_code_denied_default_message == 1){
        get_data_default($file_url, 'radioPrimary57', call_data.press2_auth_code_denied_audio_file, 'press2_auth_code_denied_default_message_audio');
    }
    else if(call_data.press2_auth_code_denied_upload_audio == 1){
        get_data_upload_file_record($file_url, 'radioPrimary58', call_data.press2_auth_code_denied_audio_file, 'press2_auth_code_denied_upload_audio_field_audio', 'press2_auth_code_denied_upload_audio_field_hidden');
    }
    else if(call_data.press2_auth_code_denied_record_audio == 1){
        get_data_upload_file_record($file_url, 'radioPrimary59', call_data.press2_auth_code_denied_audio_file, 'press2_auth_code_denied_audio_play_back', 'press2_auth_code_denied_record_audio_field_hidden');       
    }
    else if(call_data.press2_auth_code_denied_textto_speech == 1){
        txt_to_speech_data($file_url, 'radioPrimary60', 'press2_auth_code_denied_textto_speech_field', call_data.press2_auth_code_denied_text, 'press2_auth_denied_vocie_select', call_data.press2_auth_denied_vocie_select);
    }


    if(call_data.is_authorized_message == 1){
        $("#radioPrimary10").click();
    }

    if(call_data.is_pre_notify_message == 1){
        $("#radioPrimary12").click();
    }

    if(call_data.is_advertisement_default_message == 1){
        get_data_default($file_url, 'radioPrimary13', call_data.advertisement_audio_file, 'adv_def_aud');
    }
    else if(call_data.is_advertisement_upload_audio == 1){
        get_data_upload_file_record($file_url, 'radioPrimary36', call_data.advertisement_audio_file, 'adv_upload_file_aud', 'adv_aud_file_hidden');
    }
    else if(call_data.is_advertisement_record_audio == 1){
        get_data_upload_file_record($file_url, 'radioPrimary14', call_data.advertisement_audio_file, 'advertisement_first_audio_play_back', 'adv_rec_hidden');
        
    }
    else if(call_data.is_advertisement_textto_speech == 1){
        txt_to_speech_data($file_url, 'radioPrimary15', 'is_advertisement_textto_speech_field', call_data.advertisement_text, 'advertisement_vocie_select', call_data.advertisement_vocie_select);
    }

    if(call_data.is_connected_no_answer_default_message == 1){
        get_data_default($file_url, 'radioPrimary16', call_data.connected_no_answer_audio_file, 'def_connect_aud');
    }
    else if(call_data.is_connected_no_answer_upload_audio == 1){
        get_data_upload_file_record($file_url, 'radioPrimary37', call_data.connected_no_answer_audio_file, 'connect_upload_file_aud', 'connect_aud_file_hidden');
    }
    else if(call_data.is_connected_no_answer_record_audio == 1){
        get_data_upload_file_record($file_url, 'radioPrimary17', call_data.connected_no_answer_audio_file, 'connect_me_first_audio_play_back', 'connect_rec_hidden');
        
    }
    else if(call_data.is_connected_no_answer_textto_speech == 1){
        txt_to_speech_data($file_url, 'radioPrimary18', 'is_connected_no_answer_textto_speech_field', call_data.connected_no_answer_text, 'connected_no_answer_vocie_select', call_data.connected_no_answer_vocie_select);
    }

    if(call_data.is_connected_hangeup_message == 1){
        $("#radioPrimary19").click();
        
        if(call_data.is_connected_hangeup_default_message == 1){
            get_data_default($file_url, 'radioPrimary21', call_data.connected_hangeup_audio_file, 'hang_def_aud');
        }
        else if(call_data.is_connected_hangeup_upload_audio == 1){
            get_data_upload_file_record($file_url, 'radioPrimary38', call_data.connected_hangeup_audio_file, 'hang_upload_file_aud', 'hang_aud_file_hidden');
        }
        else if(call_data.is_connected_hangeup_record_audio == 1){
            get_data_upload_file_record($file_url, 'radioPrimary22', call_data.connected_hangeup_audio_file, 'hang_up_first_audio_play_back', 'hang_rec_aud_hidden');
            
        }
        else if(call_data.is_connected_hangeup_textto_speech == 1){
            txt_to_speech_data($file_url, 'radioPrimary23', 'is_connected_hangeup_textto_speech_field', call_data.connected_hangeup_text, 'connected_hangup_vocie_select', call_data.connected_hangup_vocie_select);
        }
    }
    else{
        $("#radioPrimary20").click();
    }

    if(call_data.is_beep_default_message == 1){
        get_data_default($file_url, 'radioPrimary24', call_data.beep_audio_file, 'beep_def_aud');
    }
    else if(call_data.is_beep_upload_audio == 1){
        get_data_upload_file_record($file_url, 'radioPrimary39', call_data.beep_audio_file, 'beep_upload_file_aud', 'beep_aud_file_hidden');
    }
    else if(call_data.is_beep_record_audio == 1){
        get_data_upload_file_record($file_url, 'radioPrimary25', call_data.beep_audio_file, 'open_command_first_audio_play_back', 'beep_aud_rec_hidden');
        
    }
    else if(call_data.is_beep_textto_speech == 1){
        txt_to_speech_data($file_url, 'radioPrimary26', 'is_beep_textto_speech_field', call_data.beep_text, 'is_beep_vocie_select', call_data.is_beep_vocie_select);
    }

    if(call_data.is_access_default_message == 1){
        get_data_default($file_url, 'radioPrimary27', call_data.access_audio_file, 'access_def_aud');
    }
    else if(call_data.is_access_upload_audio == 1){
        get_data_upload_file_record($file_url, 'radioPrimary40', call_data.access_audio_file, 'access_upload_file_aud', 'access_aud_file_hidden');
    }
    else if(call_data.is_access_record_audio == 1){
        get_data_upload_file_record($file_url, 'radioPrimary28', call_data.access_audio_file, 'access_first_audio_play_back', 'access_rec_hidden');
        
    }
    else if(call_data.is_access_textto_speech == 1){
        txt_to_speech_data($file_url, 'radioPrimary29', 'is_access_textto_speech_field', call_data.access_text, 'is_access_vocie_select', call_data.is_access_vocie_select);
    }

    if(call_data.is_grant_access_detail_message == 1){
        $('#radioPrimary31').click();
    }

    if(call_data.door_key_option == 1){
        $("#radioPrimary61").click();
    }
    else{
        $("#radioPrimary62").click();   
    }

    if(call_data.is_hang_up_call_terminate == 1){
        $('#radioPrimary32').click();
        $("#end_call_time_div").addClass('showHide');
    }
    else{
        $("#end_call_time_div").removeClass('showHide');
        $('#radioPrimary33').click();
        $("#end_call_time_seconds").val(call_data.end_call_time);
    }
    $("#call_duration_after_user_connect").val(call_data.call_duration_after_user_connect);
    
    if(call_data.first_number_disturb == 1){
        $("#checkboxSuccess1").click();
    }
    if(call_data.second_number_disturb == 1){
        $("#checkboxSuccess2").click();
    }
    if(call_data.third_number_disturb == 1){
        $("#checkboxSuccess3").click();
    }
        
    $("#call_flow_id").val(call_data.id);
    $("#update_call_flow").val('1');
    if(call_data.first_number != null){
        $("#first_owner_number").val(call_data.first_number).trigger('change');
    }
    if(call_data.second_number != null){
        $("#second_owner_number").val(call_data.second_number).trigger('change');
    }
    if(call_data.third_number != null){
        $("#third_owner_number").val(call_data.third_number).trigger('change');
    }

}
function getDealerAdmins() {
    var orgadminsTd = document.getElementById('orgadminsTd');
    // if (orgadminsTd) {
    //     orgadminsTd.innerHTML = '';
    // }

    var dealeradminsTd = document.getElementById('dealeradminsTd');
    // if (dealeradminsTd) {
    //     dealeradminsTd.innerHTML = '';
    // }

    $.ajax({
        url: "include/users/admins_db.php",
        type: "POST",
        data: {getdealeradmins: "yes"}, 
    }).done(function(data){
        var combined = JSON.parse(data);
        var orgadmins = combined['orgadmins'];
        var dealeradmins = combined['dealeradmins'];;
        if(orgadmins != ""){
            if(orgadmins) {
                for (let i = 0; i < orgadmins.length; i ++) {
                    let html = "<tr>";
                    var oaStatus = '';
                    var inviteSend = '';
                    if (orgadmins[i].status === 'registered') {
                        oaStatus = '<i style="color: green;display: flex; justify-content: center; align-items: center;" class="fas fa-check-circle text-success"></i>';
                    }else {
                        oaStatus = '<i style="color: black;display: flex; justify-content: center; align-items: center;" class="fas fa-circle-xmark"></i>';
                        inviteSend = "<a class='fa-regular fa-paper-plane resendInviteBtn cursor_pointer' title='Resend Invitation' data-id='" + orgadmins[i].id + "'></a>";
                    }
                    if (orgadmins[i].last_logged_in) {
                        var logTime = orgadmins[i].last_logged_in;
                    }else {
                        var logTime = 'Never';
                    }
                    var profileLocation = orgadmins[i].photo_loc && typeof orgadmins[i].photo_loc === 'string' ? orgadmins[i].photo_loc : "";
                    var fileExtension = profileLocation ? profileLocation.substring(profileLocation.lastIndexOf('.') + 1).toLowerCase() : '';

                    var imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];

                    var profileHTML = '';
                    if (imageExtensions.includes(fileExtension)) {
                        var imagePath = "/shared/serve_image.php?path=" + encodeURIComponent(profileLocation) + "&type=profile";
                        profileHTML = `<img src="${imagePath}" alt="Profile Image" class="img-fluid rounded-circle" style="width: 50px; height: 50px; border: 1px solid #007bff; cursor:pointer;" onclick="show_property_image('user_image_modal', 'user_profile_image', '${imagePath}')">`;
                    } else if (profileLocation) {
                        profileHTML = '<i class="' + profileLocation + ' fa-2x"></i>';
                    } else {
                        profileHTML = '<i class="fas fa-user-circle fa-2x"></i>';
                    }
                    html += 
                        "<td class='text-center'>" + profileHTML + "</td>" +
                        "<td>" + orgadmins[i].firstname + " " + orgadmins[i].lastname + "</td>" +
                        "<td>" + orgadmins[i].layer + "</td>" + 
                        "<td>" + orgadmins[i].email + "</td>" + 
                        "<td>" + oaStatus + "</td>" +
                        "<td>" + orgadmins[i].last_logged_in + "</td>" +
                        "<td>" +
                        "<a class='fas fa-edit text-primary mx-1 editAdminBtn' style='cursor: pointer;' title='Edit User' data-id='" + orgadmins[i].id + "'></a>" +
                "<a class='fas fa-trash-alt text-danger mx-1 deleteAdminBtn' style='cursor: pointer;' title='Delete User' data-id='" + orgadmins[i].id + "' data-name='" + orgadmins[i].firstname + " " + orgadmins[i].lastname + "'></a>" +
                        inviteSend +
                        "</div>" +
                        "</div>" +
                        "</td></tr>";

                    if (orgadminsTd) {
                        orgadminsTd.innerHTML += html;
                    }
                    const $orgAdminContainer = $(orgadminsTd);
                    $orgAdminContainer.off("click", ".editAdminBtn, .deleteAdminBtn, .resendInviteBtn");
                    $orgAdminContainer.on("click", ".editAdminBtn", function () {
                        const id = $(this).data("id");
                        editdealeradmins(id);
                    });
                
                    $orgAdminContainer.on("click", ".deleteAdminBtn", function () {
                        const id = $(this).data("id");
                        const name = $(this).data("name");
                        deletedealeradmins(name, id);
                    });
                
                    $orgAdminContainer.on("click", ".resendInviteBtn", function () {
                        const inviteemail = $(this).data("email");
                        resendInvite(inviteemail);
                    });
                }
                
            }    
        }
        if(dealeradmins != ""){
            if(dealeradmins) {
                for (let i = 0; i < dealeradmins.length; i ++) {
                    let html = "<tr>";
                    var daStatus = '';
                    var inviteSend = '';
                    if (dealeradmins[i].status === 'registered') {
                        daStatus = '<i style="color: green;display: flex; justify-content: center; align-items: center;" class="fas fa-check-circle text-success"></i>';
                    }else {
                        daStatus = '<i style="color: black;display: flex; justify-content: center; align-items: center;" class="fas fa-circle-xmark"></i>';
                        inviteSend = "<a class='fa-regular fa-paper-plane' style='cursor: pointer;' title='Resend Invitation' onclick='resendInvite(\""+dealeradmins[i].email+"\")'></a>";
                    }
                    if (dealeradmins[i].last_logged_in) {
                        var logTime = dealeradmins[i].last_logged_in;
                    }else {
                        var logTime = 'Not Logged In Yet';
                    }

                    var profileLocation = dealeradmins[i].photo_loc && typeof dealeradmins[i].photo_loc === 'string' ? dealeradmins[i].photo_loc : "";
                    var fileExtension = profileLocation ? profileLocation.substring(profileLocation.lastIndexOf('.') + 1).toLowerCase() : '';

                    var imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];

                    var profileHTML = '';
                    if (imageExtensions.includes(fileExtension)) {
                        var imagePath = "/shared/serve_image.php?path=" + encodeURIComponent(profileLocation) + "&type=profile";
                        profileHTML = `<img src="${imagePath}" alt="Profile Image" class="img-fluid rounded-circle" style="width: 50px; height: 50px; border: 1px solid #007bff; cursor:pointer;" onclick="show_property_image('user_image_modal', 'user_profile_image', '${imagePath}')">
`;
                    } else if (profileLocation) {
                        profileHTML = '<i class="' + profileLocation + ' fa-2x"></i>';
                    } else {
                        profileHTML = '<i class="fas fa-user-circle fa-2x"></i>';
                    }

                    html += 
                        "<td class='text-center'>" + profileHTML + "</td>" +
                        "<td>" + dealeradmins[i].firstname + " " + dealeradmins[i].lastname + "</td>" +
                        "<td>" + dealeradmins[i].layer + "</td>" + 
                        "<td>" + dealeradmins[i].email + "</td>" + 
                        "<td>" + daStatus + "</td>"+
                        "<td>" + logTime + "</td>" +
                        "<td>" +
                        "<a class='fas fa-edit text-primary mx-1 editDealerBtn' style='cursor: pointer;' title='Edit User' data-id='" + dealeradmins[i].id + "'></a>" +
                        "<a class='fas fa-trash-alt text-danger mx-1 deleteDealerBtn' style='cursor: pointer;' title='Delete User' data-id='" + dealeradmins[i].id + "' data-name='" + dealeradmins[i].firstname + " " + dealeradmins[i].lastname + "'></a>" +
                        inviteSend +
                        "</div>" +
                        "</div>" +
                        "</td></tr>";
                    
                    if (dealeradminsTd) {
                        dealeradminsTd.innerHTML += html;
                    }
                }
                const $dealerAdminContainer = $(dealeradminsTd);
                $dealerAdminContainer.off("click", ".editDealerBtn, .deleteDealerBtn, .resendInviteBtn");

                $dealerAdminContainer.on("click", ".editDealerBtn", function () {
                    const id = $(this).data("id");
                    editdealeradmins(id);
                });

                $dealerAdminContainer.on("click", ".deleteDealerBtn", function () {
                    const id = $(this).data("id");
                    const name = $(this).data("name");
                    deletedealeradmins(name, id);
                });

                $dealerAdminContainer.on("click", ".resendInviteBtn", function () {
                    const inviteemail = $(this).data("email");
                    resendInvite(inviteemail);
                });
                
            }
        }

        load_datatable("orgadminsTbl");
        load_datatable("dealeradminsTbl");
    });

}

function editdealeradmins(dealeradminsid) {
    $('#editAdminModal').find('form')[0].reset();

    if (!document.querySelector('input[name="idstore"]')) {
        $("form").append('<input type="hidden" name="idstore" id="idstore">');
    }

    $.ajax({
        url: '../include/users/admins_db.php',
        method: 'POST',
        data: { editdealeradmins: 'yes', dealeradminsid: dealeradminsid },
        dataType: 'json',
    }).done(function(data) {
        console.log(data);
        if (data.error) {
            alert(data.error);
            return;
        }

        const roleSelect = $("select[name='adminsList']");
        $("input[name='idstore']").val(data.user[0].id);
        $("input[name='firstname']").val(data.user[0].firstname);
        $("input[name='lastname']").val(data.user[0].lastname);
        $("input[name='email']").val(data.user[0].email).prop('disabled', true);
        $("input[name='mobile']").val(formatphoneNumber(data.data[0].mobile_number));
        roleSelect.val(data.data[0].role);       

        $("#editPermissionsBtn").off("click").on("click", function() {

            $(".org-checkbox, .prop-checkbox").prop("checked", false);
            $("#permissionsUpdated").val("true");
            $("#editPermissionsModal").modal("show");

            $("#editPermissionsModal").on("shown.bs.modal", function() {
                data.access.forEach(access => {
                    if (access.access_type === 'organization') {
                        let checkbox = document.querySelector(`.org-checkbox[data-org-id="${access.access_id}"]`);
                        if (checkbox) {
                            checkbox.checked = true;
                        }
                    } else if (access.access_type === 'property') {
                        let checkbox = $(`.prop-checkbox[data-prop-id="${access.access_id}"]`);
                        if (checkbox) {
                            checkbox.prop("checked", true);
                        }
                    }
                });
            });
        });

        $("#editAdminModal").modal("show");
    });
}
function deletedealeradmins(name, id) {
    showConfirmModal(
        `Are you sure you want to delete the Admin: ${name} (AdminID: ${id})?`,
        function () {
            $.ajax({
                url: 'include/users/admins_db.php',
                type: 'post',
                data: { deleteDealerAdmin: 'yes', id: id }
            }).done(function (data) {
                if (data === 'Success') {
                    showAlertModal(`The Admin ${name} has been successfully deleted!`);
                    getUsers();
                    getOperators();
                    getDealerAdmins();
                } else {
                    showAlertModal('Something went wrong. Please try again.');
                }
            });
        }
    );

}
function dealerSetup() {
    let html = "";
    document.getElementById("dealertble").innerHTML = html;

    $.ajax({
        url: "include/admin/dealer_db.php",
        type: "post",
        data: { getdealer: "yes" },
    }).done(function (data) {
        console.log(data);
        if (data) {
        var json = JSON.parse(data);
        var jsonc = json['current'];
        var jsoni = json['invited'];
        console.log(json);
            for (let i = 0; i < jsonc.length; i++) {

                var logo_loc = jsonc[i].logo_loc;
                var profileLocation = logo_loc && typeof logo_loc === 'string' ? logo_loc : "";
                var fileExtension = profileLocation ? profileLocation.substring(profileLocation.lastIndexOf('.') + 1).toLowerCase() : '';

                var imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];

                var profileHTML = '';
                if (imageExtensions.includes(fileExtension)) {
                    var imagePath = "/shared/serve_image.php?path=" + encodeURIComponent(profileLocation) + "&type=profile";
                    profileHTML = `<img src="` + imagePath + `" alt="Logo" class="img-fluid rounded-circle" style="width: 50px; height: 50px; border: 1px solid #007bff; cursor:pointer;" onclick="show_property_image('dealer_logo_modal', 'dealer_logo_image', '${imagePath}')">`;
                } else if (profileLocation) {
                    profileHTML = '<i class="' + profileLocation + ' fa-2x"></i>';
                } else {
                    profileHTML = '<i class="fas fa-user-circle fa-2x"></i>';
                }
                

                html =
                        "<tr><td>" + profileHTML + "</td>" +
                        "<td>" + jsonc[i].company_name + "</td>" +
                        "<td>" + jsonc[i].name + "</td>" +
                        "<td>" + jsonc[i].layer + "</td>" + 
                        "<td>" + jsonc[i].email + "</td>" + 
                        "<td>" + jsonc[i].slots_avail + "</td>" +
                        "<td>" + jsonc[i].slots_used + "</td>" +
                        "<td>" + jsonc[i].created + "</td>" + 
                        "<td>" + jsonc[i].id + "</td><td>" +
                        "<a class='fas fa-edit text-primary mx-1 editDealerBtn' style='cursor: pointer;' title='Edit User' data-id='" + jsonc[i].id + "'></a>" +
                        "<a class='fa-solid fa-phone-volume text-success mx-1 dealerSignalBtn' style='cursor: pointer;' title='Voip Settings' data-id='" + jsonc[i].id + "'></a>" +
                        "<a class='fa-solid fa-envelope-open-text text-warning dealerBillingBtn' style='cursor: pointer;' title='Billing Info' data-id='" + jsonc[i].id + "'></a>" +
                        "</td></tr>";
                document.getElementById("dealertble").innerHTML += html;
                const $dealerTable = $("#dealertble");
                $dealerTable.off("click", ".editDealerBtn, .dealerSignalBtn, .dealerBillingBtn");

                $dealerTable.on("click", ".editDealerBtn", function () {
                    const id = $(this).data("id");
                    editDealer(id);
                });

                $dealerTable.on("click", ".dealerSignalBtn", function () {
                    const id = $(this).data("id");
                    DealerSignalSetting(id);
                });

                $dealerTable.on("click", ".dealerBillingBtn", function () {
                    const id = $(this).data("id");
                    dealerBilling(id);
                });
            }

            for (let i = 0; i < jsoni.length; i++) {
                var profileHTML = '<i class="fas fa-user-circle fa-2x"></i>';
                html =
                        "<tr><td>" + profileHTML + "</td>" +
                        "<td>" + jsoni[i].company_name + "</td>" +
                        "<td>Not Registered</td>" +
                        "<td>" + jsoni[i].role + "</td>" + 
                        "<td>" + jsoni[i].email + "</td>" + 
                        "<td>" + jsoni[i].dealer_slots + "</td>" +
                        "<td>0</td>" +
                        "<td>" + jsoni[i].created_at + "</td>" + 
                        "<td>" + jsoni[i].id + "</td><td>" +
                        "<form method='POST' action='include/admin/dealer_db.php' style='display:inline;'>" +
                        "<input type='hidden' name='userid' value='" + jsoni[i].id + "'>" +
                        "<input type='hidden' name='resendInvite' value='yes'>" +
                        "<button type='submit' class='fa-regular fa-paper-plane' style='cursor: pointer; background: none; border: none;' title='Resend Invitation'></button>" +
                        "</form>" +
                        "</td></tr>";
                document.getElementById("dealertble").innerHTML += html;
            }

            load_datatable("dealersTable");

        } else {
        return;
        }
    });
}
function DealerSignalSetting(id){

    $("#dealer_signal_setting_id").val(id);
    $.ajax({
        url: 'include/signalwire/numbers.php',
        type: 'post',
        data: { getSgProDt: 'yes', user_id:id},
        success: function(response) {
            var json = JSON.parse(response);
            if(json != 0){
                $("#dealer_sg_project_id").val(json.project_id);
                $("#dealer_sg_space_url").val(json.space_url);
                $("#dealer_sg_api_token").val(json.api_token);
                $("#dealer_sg_number_buy_limit").val(json.dealer_purchase_number_limit);
            }
            $("#dealer_signal_setting_modal").modal('show');
        },
        error: function(xhr, status, error) {
            console.error('Failed to fetch data:', status, error);
        }
    });
    
}

function dealerBilling(id) {

    if (!document.querySelector('input[name="bidstore"]')) {
        $("form").append('<input type="hidden" name="bidstore" id="bidstore">');
    }

    $.ajax({
        url: "include/admin/dealer_db.php",
        type: "post",
        data: { getbilling: "yes", userid: id},
    }).done(function (data) {
        
        var billingInfo = JSON.parse(data);

        safeVal("#bconame", billingInfo[0]['full_name']);
        safeVal("#billingaddress", billingInfo[0]['street_address']);
        safeVal("#billingapt", billingInfo[0]['apartment']);
        safeVal("#billingcity", billingInfo[0]['city']);
        safeVal("#billingstate", billingInfo[0]['state']);
        safeVal("#billingzip", billingInfo[0]['postal_code']);
        safeVal("#billingcontactphone", billingInfo[0]['phone_number']);
        safeVal("input[name='bidstore']", billingInfo[0]['id']);

    });

    $("#billingmodal").modal("show");
}

function assignDealerSgData(){
    let project_id = $("#dealer_sg_project_id").val();
    let space_url = $("#dealer_sg_space_url").val();
    let api_token = $("#dealer_sg_api_token").val();
    let number_limit = $("#dealer_sg_number_buy_limit").val();
    let dealer_id = $("#dealer_signal_setting_id").val();

    $.ajax({
        url: 'include/signalwire/numbers.php',
        type: 'post',
        data: { assignDealerProject: 'yes', project_id:project_id, space_url:space_url, api_token:api_token, number_limit:number_limit, dealer_id:dealer_id},
        success: function(response) {
            $("#dealer_signal_setting_modal").modal('hide');
            $("#dealer_setup_success_message").show();
            $("#dealer_setup_success_message").html(response);
            setInterval(function(){ 
                $("#dealer_setup_success_message").hide();
            }, 5000);
        },
        error: function(xhr, status, error) {
            console.error('Failed to fetch data:', status, error);
        }
    });
}
function addSlots() {
    var form = $("#dealerslotsform");
    $.ajax({
        url: "include/admin/dealerslots.php",
        type: "post",
        data: form.serialize() + "&addslots=yes",
        success: function (response) {
        if (response.error) {
            $("#dealerslotsresult").html(
            '<div class="alert alert-danger">' + escapeHtml(response.error) + "</div>"
            );
        } else if (response.success) {
            $("#dealerslotsresult").html(
            '<div class="alert alert-success">' + escapeHtml(response.success) + "</div>"
            );
            // Refresh dealer slots after adding
            loadDealerSlots();
            $("#slots").val("");
        } else {
            console.error("Unexpected response format:", response);
        }
        },
        error: function (xhr, status, error) {
        $("#dealerslotsresult").html(
            '<div class="alert alert-danger">Failed to add slots: ' +
            status +
            "</div>"
        );
        },
    });
}
function removeSlots() {
    var form = $("#dealerslotsform");
    $.ajax({
        url: "include/admin/dealerslots.php",
        type: "post",
        data: form.serialize() + "&removeslots=yes",
        success: function (response) {
        console.log("Response from removeSlots:", response);
        if (response.error) {
            $("#dealerslotsresult").html(
            '<div class="alert alert-danger">' + escapeHtml(response.error) + "</div>"
            );
        } else if (response.success) {
            $("#dealerslotsresult").html(
            '<div class="alert alert-success">' + escapeHtml(response.success) + "</div>"
            );
            // Refresh dealer slots after removing
            loadDealerSlots();
            $("#slots").val("");
        } else {
            console.error("Unexpected response format:", response);
        }
        },
        error: function (xhr, status, error) {
        console.error("Failed to remove slots:", status, error, xhr.responseText);
        $("#dealerslotsresult").html(
            '<div class="alert alert-danger">Failed to remove slots: ' +
            status +
            "</div>"
        );
        },
    });
}

function loadFtpSlotsForDealer() {
    const dealerId = document.getElementById("dealer").value;
    document.getElementById("cameraDealerId").value = dealerId;

    $.post("include/admin/dealerslots.php", { getDealerFtpSlots: "yes", dealer_id: dealerId }, function(response) {
        const container = document.getElementById("ftpServerSlotContainer");
        container.innerHTML = "";

        if (!Array.isArray(response.servers)) return;

        response.servers.forEach(server => {
            console.log(server);
            const div = document.createElement("div");
            div.className = "input-group mb-2";

            div.innerHTML = `
                <div class="input-group-prepend">
                    <span class="input-group-text">${server.label}</span>
                </div>
                <label class="form-control">Allowed</label>
                <input type="number" class="form-control" name="slots[${server.id}]" value="${server.camera_slots_allowed}" min="0">
                <label class="form-control">Used</label>
                <input type="number" class="form-control" name="slots[${server.id}]" value="${server.camera_slots_used}" min="0" disabled>
            `;

            container.appendChild(div);
        });
    });
}

function loadAvailableFtpServers(dealerId) {
    $.post("include/admin/dealerslots.php", {
        getAvailableFtpServers: 1,
        dealer_id: dealerId
    }, function (response) {
        if (response.servers && response.servers.length > 0) {
            const container = $("#ftpServerSlotContainer");

            response.servers.forEach(server => {
                const serverRow = `
                    <div class="form-group">
                        <label>${server.label}</label>
                        <input type="number" name="slots[${server.id}]" class="form-control" placeholder="Enter allowed camera slots for this server" min="0" />
                    </div>
                `;
                container.append(serverRow);
            });
        }
    });
}

function updateCameraSlots() {
    const data = $('#dealerCameraSlotForm').serializeArray();
    data.push({ name: "updateDealerCameraSlots", value: "yes" });

    $.post("include/admin/dealerslots.php", data, function(response) {
        if (response.success) {
            $('#dealerslotsresult').html(`<div class="alert alert-success">${response.success}</div>`);
        } else {
            $('#dealerslotsresult').html(`<div class="alert alert-danger">${response.error || "Failed to update."}</div>`);
        }
    });
}

function callFormatPhoneNumber(number) {

    let cleaned = number.replace(/[^0-9]/g, "");

    // If it starts with '1' and length is 11, remove the leading '1'
    if (cleaned.length === 11 && cleaned.startsWith('1')) {
        cleaned = cleaned.substring(1);
    }

    cleaned = cleaned.slice(0, 10);

    let formatted = "";
    if (cleaned.length > 0) {
        formatted = "(" + cleaned.substring(0, 3) + ") ";
    }
    if (cleaned.length > 3) {
        formatted += cleaned.substring(3, 6);
    }
    if (cleaned.length > 6) {
        formatted += "-" + cleaned.substring(6, 10);
    }

    return formatted;
}

function formatphoneNumber(input) {

    let cleaned = input.replace(/[^0-9]/g, "");
    cleaned = cleaned.slice(0, 10);

    let formatted = "";
    if (cleaned.length > 0) {
        formatted = "(" + cleaned.substring(0, 3) + ") ";
    }
    if (cleaned.length > 3) {
        formatted += cleaned.substring(3, 6);
    }
    if (cleaned.length > 6) {
        formatted += "-" + cleaned.substring(6, 10);
    }

    return formatted;
}

function formatPhoneNumber(input) {

    let cleaned = input.value.replace(/[^0-9]/g, "");
    cleaned = cleaned.slice(0, 10);

    let formatted = "";
    if (cleaned.length > 0) {
        formatted = "(" + cleaned.substring(0, 3) + ") ";
    }
    if (cleaned.length > 3) {
        formatted += cleaned.substring(3, 6);
    }
    if (cleaned.length > 6) {
        formatted += "-" + cleaned.substring(6, 10);
    }

    input.value = formatted;
}

function handlePaste(event) {

    event.preventDefault();

    const pastedData = (event.clipboardData || window.clipboardData).getData("text");

    let cleaned = pastedData.replace(/[^0-9]/g, "");
    cleaned = cleaned.slice(0, 10);

    let formatted = "";
    if (cleaned.length > 0) {
        formatted = "(" + cleaned.substring(0, 3) + ") ";
    }
    if (cleaned.length > 3) {
        formatted += cleaned.substring(3, 6);
    }
    if (cleaned.length > 6) {
        formatted += "-" + cleaned.substring(6, 10);
    }

    event.target.value = formatted;
}

document.addEventListener('DOMContentLoaded', function () {

    $('#profilemodal').on('shown.bs.modal', function () {
        const mphoneInput = document.getElementById('mphone');
        if (mphoneInput) {
            formatPhoneNumber(mphoneInput);
        }
    });
});

function directformatPhone(phoneNumber) {
    if (phoneNumber.length !== 10 || !/^\d+$/.test(phoneNumber)) {
        throw new Error("Invalid phone number. Must be exactly 10 digits.");
    }
    return phoneNumber.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
}


function resumeTab(page, status="") {
    $.ajax({
        url: page,
        method: "GET",
        success: function (data) {
            $("#display-div").html(data);
            switch (page) {
                case "include/signalwire/my_numbers.php":
                    mySignalwireNumbers();
                    break;
                case "include/properties/my_properties.php":
                    myProperties();
                    break;
                case "include/property_builder/property_builder.php":
                    doorsGates(status);
                    break;
                case "include/admin/admin_setup.php":
                    adminSetup();
                    break;
                case "include/admin/dealer_setup.php":
                    dealerSetup();
                    break;
                case "include/properties/rolestbl.php": 
                    getRoles();
                    break;
                case "include/payment_invoice/payment_invoice.php":
                    my_payments();
                    break;

                case "include/users/users.php":
                    getCreateRoles();
                    getOperatorRoles();
                    getProps();
                    getUsers()
                    // var usersContent = document.getElementById('usersContent');
                    // usersContent.style.display = 'none';
                    break;

                case "include/visitors/visitorstbl.php":
                    getVendors();
                    getVisitors(); 
                    break;
                default:
            }
        },
        error: function () {
            $("#display-div").html("<p>Error loading page. please refresh the page.</p>"); // Show an error message on failure
        },
    });
}

function customRoleBldr(selectedLayer) {

    console.log("in customRoleBldr");
    $.ajax({
        url: "include/properties/roles_db.php",
        type: 'post',
        data: {getResources: 'yes'}
    }).done(function(data) {

        var json = JSON.parse(data);

        var gridData = [];
        var resourceActionMap = {};

        // Find the correct layer based on the layer id field
        var selectedRole = null;
        $.each(json, function(key, role) {
            if (role.id == selectedLayer) {
                selectedRole = role;
                return false;
            }
        });

        if (selectedRole) {
            // Process the resources for the selected layer
            $.each(selectedRole.resources, function(index, resource) {
                var key = resource.resource_id;
                if (!resourceActionMap[key]) {
                    resourceActionMap[key] = {
                        Resource: resource.resource_name,
                        resource_id: resource.resource_id,
                        read: false,
                        write: false,
                        delete: false,
                        deny: false
                    };
                }
                if (resource.action_id === 1) resourceActionMap[key].read = true;
                if (resource.action_id === 2) resourceActionMap[key].write = true;
                if (resource.action_id === 3) resourceActionMap[key].delete = true;
                if (resource.action_id === 4) resourceActionMap[key].deny = true;
            });

            // Convert resourceActionMap to array for jsGrid
            $.each(resourceActionMap, function(key, value) {
                gridData.push(value);
            });

            if (!gridData.length) {
                confirm('The selected Template has no Permissions at this time. Please Select a different Template.');
                // Should change this to alert? or use this for confirm 
                // showConfirmModal(
                //     'The selected Template has no Permissions at this time. Please Select a different Template.',
                //     function () {
                //         // No action required, just displaying the modal as an alert-style confirmation
                //     }
                // );
                $("#jsGrid1").jsGrid("destroy");
                $("#jsGrid1").empty();
                return;
            }

            $("#jsGrid1").jsGrid({
                height: "400px",
                width: "100%",

                sorting: true,
                paging: true,
                autoload: true,

                data: gridData,

                fields: [
                    { name: "Resource", type: "text", width: 150 },
                    {
                        name: "read",
                        type: "checkbox",
                        title: "Read",
                        itemTemplate: function(value, item) {
                            var $checkbox = $("<input>").attr("type", "checkbox")
                                                         .attr("name", `permissions[${item.resource_id}][read]`)
                                                         .prop("checked", value)
                                                         .prop("disabled", !value);
                            return $checkbox;
                        }
                    },
                    {
                        name: "write",
                        type: "checkbox",
                        title: "Write",
                        itemTemplate: function(value, item) {
                            var $checkbox = $("<input>").attr("type", "checkbox")
                                                         .attr("name", `permissions[${item.resource_id}][write]`)
                                                         .prop("checked", value)
                                                         .prop("disabled", !value);
                            return $checkbox;
                        }
                    },
                    {
                        name: "delete",
                        type: "checkbox",
                        title: "Delete",
                        itemTemplate: function(value, item) {
                            var $checkbox = $("<input>").attr("type", "checkbox")
                                                         .attr("name", `permissions[${item.resource_id}][delete]`)
                                                         .prop("checked", value)
                                                         .prop("disabled", !value);
                            return $checkbox;
                        }
                    },
                    {
                        name: "deny",
                        type: "checkbox",
                        title: "Deny",
                        itemTemplate: function(value, item) {
                            var $checkbox = $("<input>").attr("type", "checkbox")
                                                         .attr("name", `permissions[${item.resource_id}][deny]`)
                                                         .prop("checked", value);
                                                        //  .prop("disabled", !value);
                            return $checkbox;
                        }
                    }
                ]
            });
        } else {
            console.error("Selected layer not found in the data");
        }

    }).fail(function(jqXHR, textStatus, errorThrown) {
        console.error("Error fetching data: " + textStatus, errorThrown);
    });
}

function getProps() {
    document.getElementById("selectproperty").addEventListener("change", function() {
        const selectedValue = this.value;
        sessionStorage.setItem('propertyId', selectedValue)
    });
    document.getElementById("selectPropertyInModal").addEventListener("change", function() {
        const selectedValue = this.value;
        sessionStorage.setItem('propertyId', selectedValue)
    });

    $.ajax({
        url: "include/properties/roles_db.php",
        type: 'post',
        data: { getProps: 'yes' }
    }).done(function(data) {
        var json = JSON.parse(data);
        var current_site = null;
    
        json.forEach(function(item) {
            if (item.current_site) {
                current_site = item.current_site;
            }
        });
        
        document.getElementById("selectproperty").innerHTML = '';
        document.getElementById("selectproperty").innerHTML += '<option disabled selected>Please Select</option>';
        
        document.getElementById("selectPropertyInModal").innerHTML = '';
        document.getElementById("selectPropertyInModal").innerHTML += '<option disabled selected>Please Select</option>';
    
        json.forEach(function(prop) {

            if (!prop.id) return;
    
            var prop_id = prop.id;
            var prop_name = prop.name;
    
            var html = "<option value='" + prop_id + "'>" + prop_name + "</option>";
    
            if (document.getElementById("proplist")) {
                document.getElementById("proplist").innerHTML += html;
            }
    
            if (document.getElementById("nuProplist")) {
                document.getElementById("nuProplist").innerHTML += html;
            }
    
            if (document.getElementById("selectproperty")) {
                document.getElementById("selectproperty").innerHTML += html;
            }
    
            if (document.getElementById("selectPropertyInModal")) {
                document.getElementById("selectPropertyInModal").innerHTML += html;
            }
        });
    
        if (current_site) {
            sessionStorage.setItem("propertyId", current_site);
            var selectElement = document.getElementById("selectproperty");
            for (var i = 0; i < selectElement.options.length; i++) {
                if (selectElement.options[i].value == current_site) {
                    selectElement.options[i].selected = true;
                    break;
                }
            }
            loadDark();
            // getDashboardData();
        }else {
            $("#select_property_id_modal").modal("show");
        }
    });
}

function getStreets() {
    const deferred = $.Deferred();

    $.ajax({
        url: "include/users/users_db.php",
        type: 'post',
        data: { getStreets: 'yes' }
    }).done(function(data) {
        var json = JSON.parse(data);

        json.forEach(function(street) {
            var street_id = street.id;
            var street_name = street.name;

            var html =DOMPurify.sanitize("<option value='" + street_id + "'>" + street_name + "</option>");

            if (document.getElementById("streetlist")) {
                document.getElementById("streetlist").innerHTML += html;
            }
        });

        deferred.resolve(json);
    }).fail(function(err) {
        deferred.reject(err);
    });

    return deferred.promise();
}

function getCreateRoles() {

    return $.ajax({
        url: "include/properties/roles_db.php",
        type: 'post',
        data: { getcreateroles: 'yes', gettype: 0 }
    }).done(function (data) {

        if (data) {
            var json = JSON.parse(data);

            var rlist = document.getElementById('rolelist');

            if (rlist) {

                json.forEach(function (role) {
                    
                    var roleid = role.id;
                    var rolename = role.name;
                    if (role.is_custom) {
                        var htmllayer = DOMPurify.sanitize("<option value=" + "C" + roleid + ">" + rolename + "</option>");
                    }else {
                        var htmllayer = DOMPurify.sanitize("<option value=" + roleid + ">" + rolename + "</option>");
                    }
                    document.getElementById("rolelist").innerHTML += htmllayer;
                    
                });
                
            }
        }
    });
}

function getOperatorRoles() {

    $.ajax({
        url: "include/properties/roles_db.php",
        type: 'post',
        data: { getcreateroles: 'yes', gettype: 1}
    }).done(function (data) {

        if (data) {
            var json = JSON.parse(data);

            if (document.getElementById('oprolelist')) {

                json.forEach(function (role) {
                    
                    var roleid = role.id;
                    var rolename = role.name;
                    if (role.is_custom) {
                        var htmllayer = DOMPurify.sanitize("<option value=" + "C" + roleid + ">" + rolename + "</option>");
                    }else {
                        var htmllayer = DOMPurify.sanitize("<option value=" + roleid + ">" + rolename + "</option>");
                    }
                    document.getElementById("oprolelist").innerHTML += htmllayer;
                    
                });
                
            }
        }
    });
}

function getRoles() {

    $.ajax({
        url: "include/properties/roles_db.php",
        type: 'post',
        data: { getroles: 'yes' }
    }).done(function (data) {
        // console.log(data);
        // return;
        if (data) {
            var json = JSON.parse(data);

            if (document.getElementById('layerlist')) {
                console.log("see layerlist");
                json.forEach(function (role) {
                    if (!role.site_id) {
                        var roleid = role.id;
                        var rolename = role.name;
                        var htmllayer = "<option value=" + roleid + ">" + rolename + "</option>";
                        document.getElementById("layerlist").innerHTML += DOMPurify.sanitize(htmllayer);
                    }
                });
            }

            var htmlDefault = "";
            var htmlCustom = "";
            document.getElementById("roleTemplates").innerHTML = DOMPurify.sanitize(htmlDefault);
            document.getElementById("currentRoles").innerHTML = DOMPurify.sanitize(htmlCustom);

            json.forEach(function (role) {
                var roleid = role.id;
                var rolename = role.name;
                var roledesc = role.desc;
                var roletemp = role.layer;
                var rolecrea = role.created_by;
                var roleusage = 'add usage';
                var rolesite = role.site_id;

                // Maybe will move to php
                switch (roletemp) {
                    case 'property':
                        roletemp = 'Property Admin';
                        break;
                
                    default:
                        roletemp = roletemp;
                        break;
                }

                let cpRoles = capitalizeWords(rolename);

                if (role.site_id && document.getElementById('multi')) {

                    htmlCustom += "<tr><td>" + cpRoles + "</td><td>" + roletemp + "</td><td>" + rolecrea + "</td><td>" + roleusage + "</td><td>" + rolesite + "</td></tr>";

                } else if (role.site_id && document.getElementById('single')){

                    htmlCustom += "<tr><td>" + cpRoles + "</td><td>" + roletemp + "</td><td>" + roleusage + "</td></tr>";

                } else {

                    htmlDefault += "<tr data-widget='expandable-table' aria-expanded='false'><td>" + cpRoles + "</td><td>" + roledesc + "</td></tr>";
                    htmlDefault += "<tr class='expandable-body'><td colspan='2'><p>" + 'Test!!!' + "</p></td></tr>";
                }
            });

            document.getElementById("roleTemplates").innerHTML = DOMPurify.sanitize(htmlDefault);
            document.getElementById("currentRoles").innerHTML = DOMPurify.sanitize(htmlCustom);

            // Attach event listeners to the newly created rows for default roles
            document.querySelectorAll('#roleTemplates [data-widget="expandable-table"]').forEach(function (row) {
                row.addEventListener('click', function (event) {
                    event.stopPropagation(); // Prevent event bubbling
                    var nextRow = row.nextElementSibling;
                    var isExpanded = row.getAttribute('aria-expanded') === 'true';
                    row.setAttribute('aria-expanded', !isExpanded);
                    if (isExpanded) {
                        nextRow.classList.remove('show');
                    } else {
                        nextRow.classList.add('show');
                    }
                });
            });

            // Attach event listeners to the newly created rows for custom roles
            document.querySelectorAll('#currentRoles [data-widget="expandable-table"]').forEach(function (row) {
                row.addEventListener('click', function (event) {
                    event.stopPropagation(); // Prevent event bubbling
                    var nextRow = row.nextElementSibling;
                    var isExpanded = row.getAttribute('aria-expanded') === 'true';
                    row.setAttribute('aria-expanded', !isExpanded);
                    if (isExpanded) {
                        nextRow.classList.remove('show');
                    } else {
                        nextRow.classList.add('show');
                    }
                });
            });

        } else {
            return;
        }
    });
}

function variable_cost(page=""){
    $("#setting_loading_indicator").show();
    $("#myTab").hide();
    $(".tab-content").hide();
    var payment_date = $("#payment_date").val();
    var current_payment_date = $("#current_payment_date").val();

    $.ajax({
        url: 'include/payment_invoice/get_payment.php',
        type: 'post',
        data: { getvariablecostdata: 'yes', page:page, payment_date:payment_date },
        success: function(response) {

            var html = ""
            let data = JSON.parse(response);
            $("#payment_date_formatted").text(data['formatted_date']);
            $("#payment_date").val(data['payment_date']);
            $("#variable_invoice_property_name").val(data.property.name);
            if(data['payment_date'] == current_payment_date){
                $("#call_next_btn").hide();
            }
            else{
                $("#call_next_btn").show();
            }
            var calls_duration = data.calls_duration;
            var msrp_calls_amount = data.calls_amount * 2;
            var msrp_call_unit_price = data.call_unit_price * 2;
            
            var messages_count = data.messages_count;
            var msrp_messages_amount = data.messages_amount * 2;
            
            var msrp_message_unit_amount = data.message_unit_amount * 2;
            
            
            var property_d = data.property;        
            $("#to_invoice_name_property").html(property_d.name);                                  
            $("#to_invoice_property").html('Address: ' + property_d.address); 
            $("#to_invoice_contact").html('Contact: ' + property_d.contact); 
                    
            html = `
                <tr>
                  <td>` + calls_duration  + `</td>
                  <td>Voice Call</td>
                  <td>Voice call for accessing property</td>
                  <td>$` + msrp_call_unit_price + `/minute</td>
                  <td>$` + msrp_calls_amount + `</td>
                </tr>
                <tr>
                  <td>` + messages_count + `</td>
                  <td>SMS</td>
                  <td>Notification Property SMS  </td>
                  <td>$` + msrp_message_unit_amount + `/each</td>
                  <td>$` + msrp_messages_amount + `</td>
                </tr>`;   
                 

                var sub_total = parseFloat(msrp_calls_amount) + parseFloat(msrp_messages_amount);
            // var dealer_total = parseFloat(dealer_subscription) + parseFloat(dealer_door) + parseFloat(dealer_camera) + parseFloat(dealer_lpr) + parseFloat(dealer_number) + parseFloat(dealer_smsio) + parseFloat(dealer_warranty);
                $(".call_message_total").html("$" + sub_total);

            $("#payment_invoice_tbody_content").html(html);
            $("#setting_loading_indicator").hide();
            $("#myTab").show();
            $(".tab-content").show();
        },
        error: function(xhr, status, error) {
            console.error('Failed to fetch data:', status, error);
        }
    });
}

// function my_payments(page=""){
//     var payment_date = $("#payment_date").val();
//     var current_payment_date = $("#current_payment_date").val();

//     $.ajax({
//         url: 'include/payment_invoice/get_payment.php',
//         type: 'post',
//         data: { getdata: 'yes', page:page, payment_date:payment_date },
//         success: function(response) {

//             var html = ""
//             let data = JSON.parse(response);
//             $("#payment_date_formatted").text(data['formatted_date']);
//             $("#payment_date").val(data['payment_date']);
            
//             if(data['payment_date'] == current_payment_date){
//                 $("#call_next_btn").hide();
//             }
//             else{
//                 $("#call_next_btn").show();
//             }
//             var calls_duration = data.calls_duration;
//             var calls_amount = data.calls_amount * 2;
//             var msrp_calls_amount = calls_amount * 2;
//             var call_unit_price = data.call_unit_price * 2;
//             var msrp_call_unit_price = call_unit_price * 2;
//             var to_user = data.user;
//             var messages_count = data.messages_count;
//             var messages_amount = data.messages_amount * 2;
//             var msrp_messages_amount = messages_amount * 2;
//             var message_unit_amount = data.message_unit_amount * 2;
//             var msrp_message_unit_amount = message_unit_amount * 2;
//             var dealer = data.dealer;
//             var dealer_subscription = 15;
//             var dealer_subscription_total = 15;
//             var end_user_subscription = 30;
//             var end_user_subscription_total = 30;
//             var dealer_door = 3;
//             var dealer_door_total = 3;
//             var end_user_door = 6;
//             var end_user_door_total = 6;
//             var dealer_camera = 3;
//             var dealer_camera_total = 3;
//             var end_user_camera = 6;
//             var end_user_camera_total = 6;
//             var dealer_lpr = 100;
//             var dealer_lpr_total = 100;
//             var end_user_lpr = 200;
//             var end_user_lpr_total = 200;
//             var dealer_number = 0.50;
//             var dealer_number_total = 0.50;
//             var end_user_number = 1;
//             var end_user_number_total = 1;
//             var dealer_smsio = 6;
//             var dealer_smsio_total = 6;
//             var end_user_smsio = 12;
//             var end_user_smsio_total = 12;
//             var dealer_warranty = 15;
//             var dealer_warranty_total = 15;
//             var end_user_warranty = 30;
//             var end_user_warranty_total = 30;
//             var subscription_qty = 1;
//             var door_qty = 1;
//             var camera_qty = 1;
//             var lpr_qty = 1;
//             var number_qty = 1;
//             var smsio_qty = 1;
//             var warranty_qty = 1;
//             var local_numbers = "";
//             var toll_free_numbers = "";

//             var local_number_dealer_price = "";
//             var end_user_price = "";
//             var dealer_number_total_local = "";
//             var end_user_number_total_local = "";
        
//             var toll_free_number_dealer_price = "";
//             var toll_free_end_user_price = "";
//             var dealer_number_total_local = "";
//             var end_user_number_total_local = "";
                    
//             if(data.price_1 != ""){
//                 subscription_qty  = data.price_1.product_qty;
//                 dealer_subscription = data.price_1.dealer_price;
//                 end_user_subscription = data.price_1.end_user_price;
//                 dealer_subscription_total = parseFloat(dealer_subscription) * parseFloat(subscription_qty);
//                 end_user_subscription_total = parseFloat(end_user_subscription) * parseFloat(subscription_qty);
//             }
//             if(data.price_2 != ""){
//                 door_qty = data.price_2.product_qty;
//                 dealer_door = data.price_2.dealer_price;
//                 end_user_door = data.price_2.end_user_price;
//                 dealer_door_total = parseFloat(dealer_door) * parseFloat(door_qty);
//                 end_user_door_total = parseFloat(end_user_door) * parseFloat(door_qty);
//             }
//             if(data.price_3 != ""){
//                 camera_qty = data.price_3.product_qty;
//                 dealer_camera = data.price_3.dealer_price;
//                 end_user_camera = data.price_3.end_user_price;
//                 dealer_camera_total = parseFloat(dealer_camera) * parseFloat(camera_qty);
//                 end_user_camera_total = parseFloat(end_user_camera) * parseFloat(camera_qty);
//             }
//             if(data.price_4 != ""){
//                 lpr_qty = data.price_4.product_qty;
//                 dealer_lpr = data.price_4.dealer_price;
//                 end_user_lpr = data.price_4.end_user_price;
//                 dealer_lpr_total = parseFloat(dealer_lpr) * parseFloat(lpr_qty);
//                 end_user_lpr_total = parseFloat(end_user_lpr) * parseFloat(lpr_qty);
//             }
//             if(data.price_5 != ""){
//                 if(data.price_5.new_saved == 0){
//                     local_numbers = data.price_5.local_product_qty;
//                     toll_free_numbers = data.price_5.toll_free_product_qty;
//                     if(local_numbers != 0){
//                         local_number_dealer_price = data.price_5.local_number_dealer_price;
//                         end_user_price = data.price_5.end_user_price;
//                         dealer_number_total_local = parseFloat(local_number_dealer_price) * parseFloat(local_numbers);
//                         end_user_number_total_local = parseFloat(end_user_price) * parseFloat(local_numbers);
//                     }
//                     if(toll_free_numbers != 0){
//                         toll_free_number_dealer_price = data.price_5.toll_free_number_dealer_price;
//                         toll_free_end_user_price = data.price_5.toll_free_end_user_price;
//                         dealer_number_total_local = parseFloat(toll_free_number_dealer_price) * parseFloat(toll_free_numbers);
//                         end_user_number_total_local = parseFloat(end_user_number_total_toll_free) * parseFloat(toll_free_numbers);
//                     }
//                 }
//                 else{
//                     number_qty = data.price_5.product_qty;
//                     dealer_number = data.price_5.dealer_price;
//                     end_user_number = data.price_5.end_user_price;
//                     dealer_number_total = parseFloat(dealer_number) * parseFloat(number_qty);
//                     end_user_number_total = parseFloat(end_user_number) * parseFloat(number_qty);
//                 }
//             }
//             if(data.price_6 != ""){
//                 smsio_qty = data.price_6.product_qty;
//                 dealer_smsio = data.price_6.dealer_price;
//                 end_user_smsio = data.price_6.end_user_price;
//                 dealer_smsio_total = parseFloat(dealer_smsio) * parseFloat(smsio_qty);
//                 end_user_smsio_total = parseFloat(end_user_smsio) * parseFloat(smsio_qty);
//             }
//             if(data.price_7 != ""){
//                 warranty_qty = data.price_7.product_qty;
//                 dealer_warranty = data.price_7.dealer_price;
//                 end_user_warranty = data.price_7.end_user_price;
//                 dealer_warranty_total = parseFloat(dealer_warranty) * parseFloat(warranty_qty);
//                 end_user_warranty_total = parseFloat(end_user_warranty) * parseFloat(warranty_qty);
//             }
//             var dealer_d = data.dealer;
//             var property_d = data.property;        
//             $("#from_invoice_name").html('Invisible');                 
//             $("#from_invoice_address").html('795 Folsom Ave, Suite 600');                 
//             $("#from_invoice_phone").html('Phone: (804) 123-5432');                 
//             $("#from_invoice_email").html('Email: info@almasaeedstudio.com');
//             $("#to_invoice_name").html(dealer_d.firstname + " " + dealer_d.lastname);                                  
//             $("#to_invoice_email").html('Email: ' + dealer_d.email);
//             $("#to_invoice_name_property").html(property_d.name);                                  
//             $("#to_invoice_property").html('Address: ' + property_d.address); 
//             $("#to_invoice_contact").html('Contact: ' + property_d.contact); 
//             if((data.user_layer == "dealer") || (data.user_layer == "admin")){
//                 if(data.user_layer == "dealer"){
//                     html = `<tr>
//                           <td>`+subscription_qty+`</td>
//                           <td>Base Subscription</td>
//                           <td>Invisible Intercom Base Subscription (Include 1 Door or Gate)</td>
//                           <td>$`+ dealer_subscription +`/month</td>
//                           <td>$`+ dealer_subscription_total +`/month</td>
//                         </tr>
//                         <tr>
//                           <td>`+door_qty+`</td>
//                           <td>Additional Ad-on</td>
//                           <td>Additional Door or Gate Add-on</td>
//                           <td>$`+ dealer_door +`/month</td>
//                           <td>$`+ dealer_door_total +`/month</td>
//                         </tr>
//                         <tr>
//                           <td>`+camera_qty+`</td>
//                           <td>Camera</td>
//                           <td>Camera Add-on</td>
//                           <td>$`+ dealer_camera +`/month each</td>
//                           <td>$`+ dealer_camera_total +`/month each</td>
//                         </tr>
//                         <tr>
//                           <td>`+lpr_qty+`</td>
//                           <td>LPR</td>
//                           <td>LPR Access Control By License Plate Add-on</td>
//                           <td>$`+ dealer_lpr +`/month each</td>
//                           <td>$`+ dealer_lpr_total +`/month each</td>
//                         </tr>
//                         <tr>
//                           <td>`+number_qty+`</td>
//                           <td>Phone Number</td>
//                           <td>Invisible Intercom Dedicated Phone Number</td>
//                           <td>$`+ dealer_number +`/month each</td>
//                           <td>$`+ dealer_number_total +`/month each</td>
//                         </tr>
//                         <tr>
//                           <td>`+smsio_qty+`</td>
//                           <td>SMS IO</td>
//                           <td>SIM Card for SMS IO</td>
//                           <td>$`+ dealer_smsio +`/month each</td>
//                           <td>$`+ dealer_smsio_total +`/month each</td>
//                         </tr>
//                         <tr>
//                           <td>`+warranty_qty+`</td>
//                           <td>WARRANTY</td>
//                           <td>LIFETIME WARRANTY Add-on </td>
//                           <td>$`+ dealer_warranty +`/month/Controller</td>
//                           <td>$`+ dealer_warranty_total +`/month/Controller</td>
//                         </tr>
//                         <tr>
//                           <td colspan='5'><strong>Variable Costs</strong></td>
                          
//                         </tr>
//                         <tr>
//                           <td>` + calls_duration + `</td>
//                           <td>Voice Call</td>
//                           <td>Voice call for accessing property</td>
//                           <td>$` + call_unit_price + `/minute </td>
//                           <td>$` + calls_amount + `</td>
//                         </tr>
//                         <tr>
//                           <td>` + messages_count + `</td>
//                           <td>SMS</td>
//                           <td>Notification Property SMS  </td>
//                           <td>$` + message_unit_amount + `</td>
//                           <td>$` + messages_amount + `</td>
//                         </tr>`;
//                 }
//                 else if(data.user_layer == "admin"){
                    
//                     html = `<tr>
//                           <td>`+subscription_qty+`</td>
//                           <td>Base Subscription</td>
//                           <td>Invisible Intercom Base Subscription (Include 1 Door or Gate)</td>
//                           <td>$` + dealer_subscription + `/month</td>
//                           <td>$` + end_user_subscription + `/month</td>
//                           <td>$` + dealer_subscription_total + `/month</td>
//                           <td>$` + end_user_subscription_total + `/month</td>
//                           <td><button class="btn btn-primary" onclick="edit_price('1','` + page + `', '`+ dealer_subscription +`', '`+ end_user_subscription +`', '`+ subscription_qty +`')"><i class="fa fa-pencil"></i></button></td>
//                         </tr>
//                         <tr>
//                           <td>`+door_qty+`</td>
//                           <td>Additional Ad-on</td>
//                           <td>Additional Door or Gate Add-on</td>
//                           <td>$` + dealer_door + `/month</td>
//                           <td>$` + end_user_door + `/month</td>
//                           <td>$` + dealer_door_total + `/month</td>
//                           <td>$` + end_user_door_total + `/month</td>
//                           <td><button class="btn btn-primary" onclick="edit_price('2','` + page + `', '`+ dealer_door +`', '`+ end_user_door +`', '`+ door_qty +`')"><i class="fa fa-pencil"></i></button></td>
//                         </tr>
//                         <tr>
//                           <td>`+camera_qty+`</td>
//                           <td>Camera</td>
//                           <td>Camera Add-on</td>
//                           <td>$` + dealer_camera + `/month each</td>
//                           <td>$` + end_user_camera + `/month each</td>
//                           <td>$` + dealer_camera_total + `/month each</td>
//                           <td>$` + end_user_camera_total + `/month each</td>
//                           <td><button class="btn btn-primary" onclick="edit_price('3','` + page + `', '`+ dealer_camera +`', '`+ end_user_camera +`', '`+ camera_qty +`')"><i class="fa fa-pencil"></i></button></td>
//                         </tr>
//                         <tr>
//                           <td>`+lpr_qty+`</td>
//                           <td>LPR</td>
//                           <td>LPR Access Control By License Plate Add-on</td>
//                           <td>$` + dealer_lpr + `/month each</td>
//                           <td>$` + end_user_lpr + `/month each</td>
//                           <td>$` + dealer_lpr_total + `/month each</td>
//                           <td>$` + end_user_lpr_total + `/month each</td>
//                           <td><button class="btn btn-primary" onclick="edit_price('4','` + page + `', '`+ dealer_lpr +`', '`+ end_user_lpr +`', '`+ lpr_qty +`')"><i class="fa fa-pencil"></i></button></td>
//                         </tr>
//                         <tr>
//                           <td>`+number_qty+`</td>
//                           <td>Phone Number</td>
//                           <td>Invisible Intercom Dedicated Phone Number</td>
//                           <td>$` + dealer_number + `/month each</td>
//                           <td>$` + end_user_number + `/month each</td>
//                           <td>$` + dealer_number_total + `/month each</td>
//                           <td>$` + end_user_number_total + `/month each</td>
//                           <td><button class="btn btn-primary" onclick="edit_price('5','` + page + `', '`+ dealer_number +`', '`+ end_user_number +`', '`+ number_qty +`')"><i class="fa fa-pencil"></i></button></td>
//                         </tr>
//                         <tr>
//                           <td>`+smsio_qty+`</td>
//                           <td>SMS IO</td>
//                           <td>SIM Card for SMS IO</td>
//                           <td>$` + dealer_smsio + `/month each</td>
//                           <td>$` + end_user_smsio + `/month each</td>
//                           <td>$` + dealer_smsio_total + `/month each</td>
//                           <td>$` + end_user_smsio_total + `/month each</td>
//                           <td><button class="btn btn-primary" onclick="edit_price('6','` + page + `', '`+ dealer_smsio +`', '`+ end_user_smsio +`', '`+ smsio_qty +`')"><i class="fa fa-pencil"></i></button></td>
//                         </tr>
//                         <tr>
//                           <td>`+warranty_qty+`</td>
//                           <td>WARRANTY</td>
//                           <td>LIFETIME WARRANTY Add-on </td>
//                           <td>$` + dealer_warranty + `/month/Controller</td>
//                           <td>$` + end_user_warranty + `/month/Controller</td>
//                           <td>$` + dealer_warranty_total + `/month/Controller</td>
//                           <td>$` + end_user_warranty_total + `/month/Controller</td>
//                           <td><button class="btn btn-primary" onclick="edit_price('7','` + page + `', '`+ dealer_warranty +`', '`+ end_user_warranty +`', '`+ warranty_qty +`')"><i class="fa fa-pencil"></i></button></td>
//                         </tr>
//                         <tr>
//                           <td colspan='5'><strong>Variable Costs</strong></td>
//                         </tr>
//                         <tr>
//                           <td>` + calls_duration  + `</td>
//                           <td>Voice Call</td>
//                           <td>Voice call for accessing property</td>
//                           <td>$` + call_unit_price + `/minute</td>
//                           <td>$` + msrp_call_unit_price + `/minute</td>
//                           <td>$` + calls_amount + `</td>
//                           <td>$` + msrp_calls_amount + `</td>
//                           <td><button class="btn btn-primary" onclick="edit_price('voice_call')"><i class="fa fa-pencil"></i></button></td>
//                         </tr>
//                         <tr>
//                           <td>` + messages_count + `</td>
//                           <td>SMS</td>
//                           <td>Notification Property SMS  </td>
//                           <td>$` + message_unit_amount + `</td>
//                           <td>$` + msrp_message_unit_amount + `/each</td>
//                           <td>$` + messages_amount + `</td>
//                           <td>$` + msrp_messages_amount + `</td>
//                           <td><button class="btn btn-primary" onclick="edit_price('sms')"><i class="fa fa-pencil"></i></button></td>
//                         </tr>`;   
//                 }            
//             }

//             var dealer_total = parseFloat(dealer_subscription) + parseFloat(dealer_door) + parseFloat(dealer_camera) + parseFloat(dealer_lpr) + parseFloat(dealer_number) + parseFloat(dealer_smsio) + parseFloat(dealer_warranty);
            
//             $("#payment_invoice_tbody_content").html(html);

//         },
//         error: function(xhr, status, error) {
//             console.error('Failed to fetch data:', status, error);
//         }
//     });
// }

function edit_price(pro_id, page, dealer_price, end_usser_price, qty){
    $("#product_qty_sg").val('');
    $("#product_unit_price").val('');
    $("#product_msrp_price").val('');
    $("#product_id_sg").val(pro_id);
    $("#product_qty_sg").val(qty);
    $("#product_unit_price").val(dealer_price);
    $("#product_msrp_price").val(end_usser_price);
    $("#edit_price_model").modal('show');

}

function update_product_price(){
    var prodct_unit_price = $("#product_unit_price").val();
    var msrp_price = $("#product_msrp_price").val();
    var product_id = $("#product_id_sg").val();
    var product_qty = $("#product_qty_sg").val();
    var page = $("#product_page_sg").val();
    $.ajax({
        url: 'include/payment_invoice/get_payment.php',
        type: 'post',
        data: { update_price: 'yes', prodct_unit_price:prodct_unit_price, msrp_price:msrp_price, product_id:product_id, product_qty:product_qty}
    }).done(function(data) {
        $("#edit_price_model").modal('hide');
        my_payments(page);
    });
}

function resetForm(form) {
    var element = document.getElementById(form);
    element.reset()
}

function load_datatable(id, val=""){
    if ($.fn.DataTable.isDataTable("#"+ id)) {
        $("#"+ id).DataTable().destroy();
    }

    if(val == "my_numbers"){
        $("#"+ id).DataTable({
            "responsive": true,
            "order": [],
            "paging": false,
            "pageLength": -1,
            "searching": false,
        });
    }
    else{
        $("#"+ id).DataTable({
            "responsive": true,
            "order": [],
            "paging": true,
            "pageLength": 10,
            "searching": false,
        });
    }
}

function clear_datatabe(table_id){
    if ($.fn.DataTable.isDataTable("#"+table_id)) {
        $('#'+table_id).DataTable().clear().destroy();
        // Remove all existing <tr> elements from <tbody>
        $('#'+table_id + ' tbody').empty();
    }
}

function fetchAndDisplayData(url, dataKey, tableId, type) {

    $.ajax({
        url: url,
        type: 'post',
        data: { [dataKey]: 'yes' }
    }).done(function(data) {
        if (data && data !== '[]') {
            var json = JSON.parse(data);
            document.getElementById(tableId).innerHTML = '';

            if (type === 'visitors') {
                clear_datatabe("visitorsTable");
                var status_visitor = "";
                var flag = json.flag.type;
                var html = "";
                for (let i = 0; i < json.data.length; i++) {
                    html = "<tr>";

                    switch (json.data[i].key_type) {

                        case 'Key_Code': 
                            json.data[i].key_type = 'Key Code';
                            break;
                        case 'Magic_Password':
                            json.data[i].key_type = 'Magic Password';
                            break;
                        default:
                            break;
                    }

                    status_visitor = "<span class='badge badge-primary'>"+ json.data[i].status +"</span>";
                    if(json.data[i].status == "Expired"){
                        status_visitor = "<span class='badge badge-danger'>"+ json.data[i].status +"</span>";
                    }
                    else if(json.data[i].status == "Inactive"){
                        status_visitor = "<span class='badge badge-warning'>"+ json.data[i].status +"</span>";   
                    }
                    if (flag === 'admin') {
                        html += "<td onclick='editVisitor(" + json.data[i].id + ")'>" + json.data[i].name + "</td>" +
                                // "<td onclick='editVisitor(" + json.data[i].id + ")'>" + json.data[i].door_name + "</td>" +
                                "<td onclick='editVisitor(" + json.data[i].id + ")'>" + json.data[i].key_type + "</td>" +
                                "<td onclick='editVisitor(" + json.data[i].id + ")'>" + status_visitor + "</td>" +
                                "<td onclick='editVisitor(" + json.data[i].id + ")'>" + json.data[i].user_assoc + "</td>" +
                                "<td onclick='editVisitor(" + json.data[i].id + ")'>" + json.data[i].property_id + "</td>";
                    } else if (flag === 'operator') {
                        html += "<td onclick='editVisitor(" + json.data[i].id + ")'>" + json.data[i].name + "</td>" +
                                // "<td onclick='editVisitor(" + json.data[i].id + ")'>" + json.data[i].door_name + "</td>" +
                                "<td onclick='editVisitor(" + json.data[i].id + ")'>" + json.data[i].key_type + "</td>" +
                                "<td onclick='editVisitor(" + json.data[i].id + ")'>" + status_visitor + "</td>" +
                                "<td onclick='editVisitor(" + json.data[i].id + ")'>" + json.data[i].user_assoc + "</td>";
                    } else if (flag === 'user') {
                        html += "<td onclick='editVisitor(" + json.data[i].id + ")'>" + json.data[i].name + "</td>" +
                                // "<td onclick='editVisitor(" + json.data[i].id + ")'>" + json.data[i].door_name + "</td>" +
                                "<td onclick='editVisitor(" + json.data[i].id + ")'>" + json.data[i].key_type + "</td>" +
                                "<td onclick='editVisitor(" + json.data[i].id + ")'>" + status_visitor + "</td>";
                    }

                    // if (flag === 'admin') {
                    //     html += "<td>" + json.data[i].name + "</td>" +
                    //             "<td>" + json.data[i].key_type + "</td>" +
                    //             "<td>" + json.data[i].status + "</td>" +
                    //             "<td>" + json.data[i].user_assoc + "</td>" +
                    //             "<td>" + json.data[i].property_id + "</td>";
                    // } else if (flag === 'user') {
                    //     html += "<td>" + json.data[i].name + "</td>" +
                    //             "<td>" + json.data[i].key_type + "</td>" +
                    //             "<td>" + json.data[i].status + "</td>";
                    // }

                    html += "<td>" +
                            // "<a class='fas fa-edit text-primary mx-1' style='cursor: pointer;' title='Edit Visitor' onclick='editVisitor(" + json.data[i].id + ")'></a>" +
                            "<a class='fas fa-trash-alt text-danger mx-1' style='cursor: pointer;' title='Delete Visitor' onclick='deleteVisitor(\"" + json.data[i].name + "\", \"" + json.data[i].id + "\", \"" + json.data[i].property_id + "\")'></a>" +
                            "</div>" +
                            "</div>" +
                            "</td></tr>";
                        
                    document.getElementById(tableId).innerHTML += html;  
                }
                
                // else{
                //     if (!$.fn.DataTable.isDataTable("#" + tableId)) {
                //         $("#" + tableId).parent().DataTable({
                //             "responsive": true,
                //             "autoWidth": false,
                //             "scrollX": true,
                //             "scrollY": "400px",
                //             "scrollCollapse": true,
                //             "ordering": true,
                //             "order": [],
                //             "orderFixed": [],
                //             "columnDefs": [
                //                 { "orderable": false, "targets": -1 },
                //             ],
                //             "paging": true,
                //             "pagingType": "full_numbers",
                //             "pageLength": 10,
                //             "lengthMenu": [ [10, 25, 50, 100], [10, 25, 50, 100] ],
                //             "searching": false,
                //             "createdRow": function(row, data, dataIndex) {
                //                 if (data[4] === "High") {
                //                     $(row).addClass('highlight');
                //                 }
                //             },
                //             "retrieve": true,
                //             "drawCallback": function(settings) {
                //                 const api = this.api();
                //                 const pageInfo = api.page.info();

                //                 // Hide pagination controls if only one page
                //                 if (pageInfo.pages <= 1) {
                //                     $('.dataTables_paginate').hide();
                //                 } else {
                //                     $('.dataTables_paginate').show();
                //                 }
                //             }
                        
                //         });
                //     } else {
                //         $("#" + tableId).DataTable().order([]).draw(); // Ensure no initial order if already initialized
                //     }
                // }
                
            }else {
                for (let i = 0; i < json.length; i++) {
                    let html = "<tr>";
                    if(json[i].key_type == 'Key_Code'){
                        json[i].key_type = 'Key Code';
                    }
                    switch (json[i].key_type) {
                        case 'Key_Code': 
                            json[i].key_type = 'Key Code';
                            break;
                        case 'Magic_Password':
                            json[i].key_type = 'Magic Password';
                            break;
                        default:
                            break;
                    }

                    var uStatus = '';
                    var inviteSend = '';
                    if (json[i].status === 'registered' || json[i].status === 'Active') {
                        uStatus = '<i style="color: green;display: flex; justify-content: center; align-items: center;" class="fas fa-check-circle text-success"></i>';
                    }else {
                        uStatus = '<i style="color: black;display: flex; justify-content: center; align-items: center;" class="fas fa-circle-xmark"></i>';
                        inviteSend = "<a class='fa-regular fa-paper-plane' style='cursor: pointer;' title='Resend Invitation' onclick='resendInvite(\""+json[i].email+"\")'></a>";
                    }
                    if (type === 'users' || type === 'dusers') {
                        var mNum = json[i].mobile_number.replace(/\D/g, '').replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
                        var hNum = json[i].home_number.replace(/\D/g, '').replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
                        var home_extension = "";
                        if(json[i].home_extension != "" && json[i].home_extension != null){
                            home_extension = json[i].home_extension;
                        }

                        var profileLocation = json[i].photo_loc && typeof json[i].photo_loc === 'string' ? json[i].photo_loc : "";
                        var fileExtension = profileLocation ? profileLocation.substring(profileLocation.lastIndexOf('.') + 1).toLowerCase() : '';

                        var imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];

                        var profileHTML = '';
                        if (imageExtensions.includes(fileExtension)) {
                            var imagePath = "/shared/serve_image.php?path=" + encodeURIComponent(profileLocation) + "&type=profile";
                            profileHTML = `<img src="` + imagePath + `" alt="Profile Image" class="img-fluid rounded-circle" style="width: 50px; height: 50px; border: 1px solid #007bff; cursor:pointer;" onclick="show_property_image('user_image_modal', 'user_profile_image', '${imagePath}')">`;
                        } else if (profileLocation) {
                            profileHTML = '<i class="' + profileLocation + ' fa-2x"></i>';
                        } else {
                            profileHTML = '<i class="fas fa-user-circle fa-2x"></i>';
                        }


                        html += 
                                "<td class='text-center'>" + profileHTML + "</td>" +
                                "<td onclick='editUser(" + json[i].id + ")'>" + json[i].firstname + " " + json[i].lastname + "</td>" +
                                "<td onclick='editUser(" + json[i].id + ")'>" + json[i].unit + " " + json[i].street + "</td>" +
                                "<td onclick='editUser(" + json[i].id + ")'>" + uStatus + "</td>" +
                                "<td onclick='editUser(" + json[i].id + ")'>" + "<i class='fas fa-mobile-button'></i> " + " " + mNum + "<i style='padding-left:5%;' class='fas fa-phone'></i>" + " " + hNum + home_extension + "</td>";
                    } else if (type === 'operators' || type === 'doperators') {
                        var profileLocation = json[i].photo_loc && typeof json[i].photo_loc === 'string' ? json[i].photo_loc : "";
                        var fileExtension = profileLocation ? profileLocation.substring(profileLocation.lastIndexOf('.') + 1).toLowerCase() : '';

                        var imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];

                        var profileHTML = '';
                        if (imageExtensions.includes(fileExtension)) {
                            var imagePath = "/shared/serve_image.php?path=" + encodeURIComponent(profileLocation) + "&type=profile";
                            profileHTML = `<img src="` + imagePath + `" alt="Profile Image" class="img-fluid rounded-circle" style="width: 50px; height: 50px; border: 1px solid #007bff; cursor:pointer;" onclick="show_property_image('user_image_modal', 'user_profile_image', '${imagePath}')">`;
                        } else if (profileLocation) {
                            profileHTML = '<i class="' + profileLocation + ' fa-2x"></i>';
                        } else {
                            profileHTML = '<i class="fas fa-user-circle fa-2x"></i>';
                        }
                        html += "<td class='text-center'>" + profileHTML + "</td>" +
                                "<td onclick='editOperator(" + json[i].id + ")'>" + json[i].firstname + " " + json[i].lastname + "</td>" +
                                "<td onclick='editOperator(" + json[i].id + ")'>" + json[i].role_name + "</td>" +
                                "<td onclick='editOperator(" + json[i].id + ")'>" + json[i].email + "</td>" +
                                "<td onclick='editOperator(" + json[i].id + ")'>" + uStatus + "</td>" +
                                "<td onclick='editOperator(" + json[i].id + ")'>" + json[i].created_by_name + "</td>" +
                                "<td onclick='editOperator(" + json[i].id + ")'>" + json[i].logged_time + "</td>";
                    // } else if (type === 'vendors') {
                    //     html += "<td>" + json[i].company + "</td>" +
                    //             "<td>" + json[i].name + "</td>" +
                    //             "<td>" + json[i].key_type + "</td>" +
                    //             "<td>" + json[i].status + "</td>" +
                    //             "<td>" + json[i].user_assoc + "</td>" +
                    //             "<td>" + json[i].property_id + "</td>";
                    // } 
                    } else if (type === 'vendors') {
                        clear_datatabe("vendorsTable");
                        var status_vendor = "<span class='badge badge-primary'>"+ json[i].status +"</span>"
                        if(json[i].status == "Expired"){
                            status_vendor = "<span class='badge badge-danger'>"+ json[i].status +"</span>"
                        }
                        else if(json[i].status == "Inactive"){
                            status_vendor = "<span class='badge badge-warning'>"+ json[i].status +"</span>"
                        }
                        html += "<td onclick='editVendor(" + json[i].id + ")'>" + json[i].company + "</td>" +
                                "<td onclick='editVendor(" + json[i].id + ")'>" + json[i].name + "</td>" +
                                // "<td onclick='editVendor(" + json[i].id + ")'>" + json[i].door_name + "</td>" +
                                "<td onclick='editVendor(" + json[i].id + ")'>" + json[i].key_type + "</td>" +
                                "<td onclick='editVendor(" + json[i].id + ")'>" + status_vendor + "</td>" +
                                "<td onclick='editVendor(" + json[i].id + ")'>" + json[i].user_assoc + "</td>" +
                                "<td onclick='editVendor(" + json[i].id + ")'>" + json[i].property_id + "</td>";
                    }

                    if (type === 'dusers' || type === 'doperators') {

                        html += "<td>" +
                            "<a class='fa-solid fa-toolbox text-info' style='cursor: pointer;' title='Recover User'></a>" + // onclick='recover(\"" + json[i].firstname + " " + json[i].lastname + "\", \"" + json[i].id + "\", \"" + json[i].property_id + "\")'
                            "</div>" +
                            "</div>" +
                            "</td></tr>";
                    } else if (type === 'vendors') {
                        
                        html += "<td>" +
                            // "<a class='fas fa-edit text-primary mx-1' style='cursor: pointer;' title='Edit Vendor' onclick='editVendor(" + json[i].id + ")'></a>" +
                            "<a class='fas fa-trash-alt text-danger mx-1' style='cursor: pointer;' title='Delete Vendor' onclick='deleteVendor(\"" + json[i].name + "\", \"" + json[i].id + "\", \"" + json[i].property_id + "\")'></a>" +
                            "</div>" +
                            "</div>" +
                            "</td></tr>";
                    } else if (type === 'operators') {

                        var opName = json[i].firstname + " " + json[i].lastname;

                        html += "<td>" + 
                            "<a class='fas fa-edit text-primary mx-1' style='cursor: pointer;' title='Edit Operator' onclick='editOperator(" + json[i].id + ")'></a>" +
                            "<a class='fas fa-trash-alt text-danger mx-1' style='cursor: pointer;' title='Delete Operator' onclick='deleteOperator(\"" + opName + "\", \"" + json[i].id + "\", \"" + json[i].property_id + "\")'></a>" +
                            inviteSend +
                            "</div>" +
                            "</div>" +
                            "</td></tr>";
                    } else {
                        
                        html += "<td>" +
                            "<a class='fas fa-edit text-primary mx-1' style='cursor: pointer;' title='Edit User' onclick='editUser(" + json[i].id + ")'></a>" +
                            "<a class='fas fa-trash-alt text-danger mx-1' href='#' title='Delete User' title='Delete User' onclick='deleteUser(\"" + json[i].firstname + " " + json[i].lastname + "\", \"" + json[i].id + "\", \"" + json[i].property_id + "\")'></a>" +
                            inviteSend +
                            "</div>" +
                            "</div>" +
                            "</td></tr>";
                    }

                    document.getElementById(tableId).innerHTML += html;
                }
            }
        }
        if(tableId == "visitorsTableBody"){
            load_datatable("visitorsTable");
        }
        else if(tableId == "vendorsTableBody"){
            load_datatable("vendorsTable");
        }
        else {
            $("#" + tableId).parent().DataTable().destroy();
            $("#" + tableId).parent().DataTable({
                "responsive": true,
                "order": [],
                "paging": true,
                "pageLength": 10,
                "searching": false,
                "createdRow": function(row, data, dataIndex) {
                    if (data[4] === "High") {
                        $(row).addClass('highlight');
                    }
                },
            });
        }
        return;
    });
}

// Fetch and display users
function getUsers() {
    fetchAndDisplayData("include/users/users_db.php", "getUsers", "propertyUsers", "users");
}

// Fetch and display operators
function getOperators() {
    fetchAndDisplayData("include/users/operators_db.php", "getOperators", "propertyOperators", "operators");
}

function getVisitors() {
    fetchAndDisplayData("include/visitors/visitors.php", "getVisitors", "visitorsTableBody", "visitors");
}

function getVendors() {
    fetchAndDisplayData("include/visitors/visitors.php", "getVendors", "vendorsTableBody", "vendors");
}

function getdeleted() {
    fetchAndDisplayData("include/users/operators_db.php", "getDeleted", "deletedOperators", "doperators");
    fetchAndDisplayData("include/users/users_db.php", "getDeleted", "deletedpropertyUsers", "dusers");
}

// function updateOrganization(orgId) {
//     const orgData = {
//         id: $("input[name='idstore']").val(),
//         name: $("input[name='orgname']").val(),
//         address: $("input[name='orgaddress']").val(),
//         city: $("input[name='orgcity']").val(),
//         state: $("select[name='orgstate']").val(),
//         zipcode: $("input[name='orgzip']").val(),
//         contact: $("input[name='orgcontact']").val(),
//         contact_phone_number: $("input[name='orgcontactphone']").val()
//     };

//     $.ajax({
//         url: 'include/properties/organization.php',
//         method: 'POST',
//         data: { updateorg: 'yes', orgData: orgData },
//     }).done(function(data) {
//         console.log(data);
//         if (data === "Success") {
//             $("#orgmodal").modal('hide');
//             location.reload();
//         } else {
//             alert('Failed to update Organization.');
//         }
//     }).fail(function() {
//         alert('An error occurred while updating the Organization.');
//     });
// }

// original
// function editProp(propId) {
//     const idstore = `
//         <input type="hidden" name="idstore" id="idstore">
//     `;

//     if (!document.querySelector('input[name="idstore"]')) {
//         $("form").append(idstore);
//     }

//     $.ajax({
//         url: '../include/properties/property.php',
//         method: 'POST',
//         data: { editprop: 'yes', propid: propId },
//         dataType: 'json',
//     }).done(function (data) {
//         console.log(data);

//         if (data) {
//             const propData = data;

//             const imgElement = $("#imagePreview");
//             if (imgElement.length === 0) {
//                 console.error("Image element #imagePreview not found in the DOM.");
//                 return;
//             }

//             function clearModal() {
//                 $('#propertyForm')[0].reset();
//                 $('#propImage').val('');
//                 imgElement.attr('src', '#').hide();
//                 $("#deleteImageButton").remove();
//             }

//             clearModal();

//             if (propData.image_path && propData.image_path.trim() !== "") {
//                 const imagePath = `/shared/serve_image.php?path=${propData.image_path}&type=property`;
//                 imgElement.attr('src', imagePath).show();

//                 const deleteButtonHTML = `
//                     <button type="button" class="btn btn-danger mb-2" id="deleteImageButton">
//                         Delete Current Image
//                     </button>
//                 `;

//                 if (!document.querySelector('#deleteImageButton')) {
//                     $("#propImage").before(deleteButtonHTML);
//                 }

//                 $("#deleteImageButton").off("click").on("click", function () {
//                     $.ajax({
//                         url: '../include/properties/property.php',
//                         method: 'POST',
//                         data: { deleteImage: 'yes', propid: propId },
//                         success: function (response) {
//                             alert("Image deleted successfully!");
//                             imgElement.attr('src', '#').hide();
//                             $("#deleteImageButton").remove();
//                         },
//                         error: function () {
//                             alert("Failed to delete the image.");
//                         }
//                     });
//                 });
//             }

//             $("input[name='idstore']").val(propData.id);
//             $("select[name='proptype'] option").each(function () {
//                 if ($(this).text() === propData.property_type) {
//                     $(this).prop("selected", true);
//                 }
//             });
//             $("input[name='propname']").val(propData.name);
//             $("input[name='propaddress']").val(propData.address);
//             $("input[name='propcity']").val(propData.city);
//             $("select[name='propstate']").val(propData.state);
//             $("input[name='propzip']").val(propData.zipcode);
//             $("input[name='propCon']").val(propData.contact);
//             $("input[name='propConPh']").val(propData.contact_phone_number);
            
//             const orgSelect = $("select[name='organization_id']");
//             orgSelect.find("option").each(function() {
//                 if ($(this).val() === propData.organization_id) {
//                     $(this).prop("selected", true);
//                 }
//             });
            
//             $("input[name='propnotes']").val(propData.notes);

//             // Change the modal submit button for update
//             const submitButton = $("#propertyModalSubmitButton");
//             if (submitButton.length > 0) {
//                 submitButton.text("Update Property");
//                 submitButton.attr("id", "updatePropBtn");
//                 submitButton.attr("name", "updateprop");
//             }
//             $(".modal-header").html('<h5 class="modal-title" id="exampleModalCenterTitle">Update Property</h5>');
//             $("#propmodal").modal("show");
//         } else {
//             alert("Failed to fetch Property details.");
//         }
//     }).fail(function () {
//         alert("An error occurred while fetching Property details.");
//     });
// }

function editProp(propId) {
    const idstore = `
        <input type="hidden" name="idstore" id="idstore">
    `;

    if (!document.querySelector('input[name="idstore"]')) {
        $("form").append(idstore);
    }

    document.getElementById("upropmodal").addEventListener("show", function () {
        document.getElementById("upropertyForm").reset();
    });

    $.ajax({
        url: '../include/properties/property.php',
        method: 'POST',
        data: { editprop: 'yes', propid: propId },
        dataType: 'json',
    }).done(function (data) {

        if (data) {
            const propData = data;

            const imgElement = $("#uimagePreview");
            imgElement.attr('src', '/include/images/no-image.png');
            if (imgElement.length === 0) {
                console.error("Image element #imagePreview not found in the DOM.");
                return;
            }

            if (propData.image_path && propData.image_path.trim() !== "") {
                const imagePath = `/shared/serve_image.php?path=${propData.image_path}&type=property`;
                imgElement.attr('src', imagePath).show();

                const deleteButtonHTML = `
                    <button type="button" class="btn btn-danger mb-2" id="udeleteImageButton">
                        Delete Current Image
                    </button>
                `;

                if (!document.querySelector('#udeleteImageButton')) {
                    $("#upropImage").before(deleteButtonHTML);
                }

                $("#udeleteImageButton").off("click").on("click", function () {
                    $.ajax({
                        url: '../include/properties/property.php',
                        method: 'POST',
                        data: { deleteImage: 'yes', propid: propId },
                        success: function (response) {
                            showAlertModal("Image deleted successfully!");
                            imgElement.attr('src', '/include/images/no-image.png').hide();
                            $("#udeleteImageButton").remove();
                        },
                        error: function () {
                            showAlertModal("Failed to delete the image.");
                        }
                    });
                });
            }

            $("input[name='idstore']").val(propData.id);
            $("select[name='uproptype'] option").each(function () {
                if ($(this).text() === propData.property_type) {
                    $(this).prop("selected", true);
                }
            });
            $("input[name='upropname']").val(propData.name);
            $("input[name='upropaddress']").val(propData.address);
            $("input[name='upropcity']").val(propData.city);
            $("select[name='upropstate']").val(propData.state);
            $("input[name='upropzip']").val(propData.zipcode);
            $("input[name='upropCon']").val(propData.contact);
            $("input[name='upropConPh']").val(formatphoneNumber(propData.contact_phone_number));
            $("select[name='uorganization_id']").val(propData.organization_id);            
            $("input[name='upropnotes']").val(propData.notes);
            $("input[name='upropLink']").val(propData.property_link??null);

            // // Change the modal submit button for update
            // const submitButton = $("#propertyModalSubmitButton");
            // if (submitButton.length > 0) {
            //     submitButton.text("Update Property");
            //     submitButton.attr("id", "updatePropBtn");
            //     submitButton.attr("name", "updateprop");
            // }

            $("#upropmodal").modal("show");
        } else {
            showAlertModal("Failed to fetch Property details.");
        }
    }).fail(function () {
        showAlertModal("An error occurred while fetching Property details.");
    });
}


$("#propmodal").on("hidden.bs.modal", function () {
    $("#deleteImageCheckbox").remove();
});

function editOrg(orgId) {
    const idstore = `
        <input type="hidden" name="idstore" id="idstore">
    `;

    if (!document.querySelector('input[name="idstore"]')) {
        $("form").append(idstore);
    }

    $.ajax({
        url: '../include/properties/organization.php',
        method: 'POST',
        data: { editorg: 'yes', orgid: orgId },
        dataType: 'json',
    }).done(function(data) { 
        if (data) {
            const orgData = Object.values(data['orgs'])[0];
            const dealData = data['dealers'];
            const udealerid = document.getElementById("udealerid");

            $("input[name='idstore']").val(orgData.id);
            $("input[name='uorgname']").val(orgData.name);
            $("input[name='uorgaddress']").val(orgData.address);
            $("input[name='uorgcity']").val(orgData.city);
            $("select[name='uorgstate']").val(orgData.state);
            $("input[name='uorgzip']").val(orgData.zipcode);
            $("input[name='uorgcontact']").val(orgData.contact);
            $("input[name='uorgcontactphone']").val(formatphoneNumber(orgData.contact_phone_number));

            if (udealerid) {
                udealerid.innerHTML = "";

                for (let i = 0; i < dealData.length; i++) {
                    const dealer = dealData[i];

                    var option = document.createElement("option");
                    option.textContent = dealer.company_name + " - " + dealer.firstname + " " + dealer.lastname;
                    option.value = dealer.id;

                    udealerid.appendChild(option);
                }

                $("select[name='udealerid']").val(orgData.dealer_id);
            }else {
                $("form").append('<input type="hidden" name="udealerid" id="idstore">');
                $("input[name='udealerid']").val(orgData.dealer_id);
            }
            $("#uorgmodal").modal('show');
        } else {
            showAlertModal('Failed to fetch Organization details.');
        }
    }).fail(function() {
        showAlertModal('An error occurred while fetching Organization details.');
    });
}

function editUser(userId) {

    const idstore = `
        <input type="hidden" name="euidstore" id="euidstore">
    `;

    if (!document.querySelector('input[name="euidstore"]')) {
        $("form").append(idstore);
    }

    $.ajax({
        url: '../include/users/users_db.php',
        method: 'POST',
        data: { editUsers: 'yes', userid: userId },
        dataType: 'json',
    }).done(function(data) { 

        if (data) {
            const userData = data;

            if (!document.querySelector('input[name="euidstore"]')) {
                console.log("cant see it");
                $("form").append(idstore);
            }

            if (userData.user_assoc) {
                $("input[name='euidstore']").val(userData.user_assoc);
            }else {
                $("input[name='euidstore']").val(userData.id);
            }
            $("input[name='firstname']").val(userData.firstname);
            $("input[name='lastname']").val(userData.lastname);
            $("input[name='unit']").val(userData.unit);

            getCreateRoles().done(function(roleData) {
                roleDataJson = JSON.parse(roleData);
                const roleSelect = $("select[name='uroleList']");
                roleSelect.empty(); // Clear existing options

                if (roleDataJson) {
                    roleDataJson.forEach(function(role) {
                        const roleId = role.is_custom ? `C${role.id}` : role.id;
                        roleSelect.append(new Option(role.name, roleId));
                    });

                    // Set the selected role
                    if (userData.custom === 1) {
                        roleSelect.val("C"+userData.role);
                    }else {
                        roleSelect.val(userData.role);
                    }

                }
            }).fail(function() {
                showAlertModal('Failed to fetch roles.');
            });

            getStreets().done(function(streetData) {
                const streetSelect = $("select[name='streetList']");

                streetSelect.empty();

                streetData.forEach(function(street) {
                    streetSelect.append(new Option(street.name, street.id));
                });

                streetSelect.find("option").each(function() {
                    if ($(this).val() === userData.street) {
                        $(this).prop("selected", true);
                    }
                });
            }).fail(function() {
                showAlertModal('Failed to fetch streets.');
            });
            $("input[name='uemail']").val(userData.email);
            $("input[name='uroleList']").val(userData.role);

            var UMob = formatphoneNumber(userData.mobile_number);
            if (userData.home_number != '') {
                var UHom = formatphoneNumber(userData.home_number);
            }

            $("input[name='mobile']").val(UMob);
            $("input[name='home']").val(UHom);
            if(userData.home_extension != "" && userData.home_extension != null){
                $("#home_extension_user").val(userData.home_extension);
            }
            // $("select[name='roleList']").closest('.form-group').hide();
            $("input[name='form_id']").closest('div').remove();

            $("#editusermodal").modal('show');
        } else {
            showAlertModal('Failed to fetch User details.');
        }
    }).fail(function() {
        showAlertModal('An error occurred while fetching User details.');
    });
}
// orig
// function editOperator(userId) {

//     const idstore = `
//         <input type="hidden" name="idstore" id="idstore">
//     `;

//     if (!document.querySelector('input[name="idstore"]')) {
//         $("form").append(idstore);
//     }

//     $.ajax({
//         url: '../include/users/operators_db.php',
//         method: 'POST',
//         data: { editOperator: 'yes', userid: userId },
//         dataType: 'json',
//     }).done(function(data) { 
//         console.log(data);
//         if (data) {
//             const userData = data[0];

//             $("input[name='idstore']").val(userData.id);
//             $("input[name='ofirstname']").val(userData.firstname);
//             $("input[name='olastname']").val(userData.lastname);
//             $("input[name='ounit']").val(userData.unit);
//             $("input[name='oemail']").val(userData.email);

//             getStreets().done(function(streetData) {

//                 const streetSelect = $("select[name='ostreetList']");

//                 streetSelect.empty();

//                 streetData.forEach(function(street) {
//                     streetSelect.append(new Option(street.name, street.id));
//                 });

//                 streetSelect.find("option").each(function() {
//                     if ($(this).val() === userData.street) {
//                         $(this).prop("selected", true);
//                     }
//                 });
//             }).fail(function() {
//                 alert('Failed to fetch streets.');
//             });
            
//             var OpMob = directformatPhone(userData.mobile_number);
//             var OpHom = directformatPhone(userData.home_number);
//             $("input[name='omobile']").val(OpMob);
//             $("input[name='ohome']").val(OpHom);

//             $("#updateoperatormodal").modal('show');
//         } else {
//             alert('Failed to fetch Operator details.');
//         }
//     }).fail(function() {
//         alert('An error occurred while fetching Operator details.');
//     });
// }

function editOperator(operatorId) {

    if (!document.querySelector('input[name="euidstore"]')) {
        $("form").append('<input type="hidden" name="euidstore" id="euidstore">');
    }

    $.ajax({
        url: '../include/users/operators_db.php',
        method: 'POST',
        data: { editOperator: 'yes', userid: operatorId },
        dataType: 'json',
    }).done(function(data) {
        // console.log(data);
        if (data) {
            const operatorData = data;

            if (operatorData.user_assoc) {
                $("input[name='euidstore']").val(operatorData.user_assoc);
            } else {
                $("input[name='euidstore']").val(operatorData.id);
            }

            $("input[name='ofirstname']").val(operatorData.firstname);
            $("input[name='olastname']").val(operatorData.lastname);
            $("input[name='ounit']").val(operatorData.unit);
            $("input[name='oemail']").val(operatorData.email);

            getStreets().done(function(streetData) {
                const streetSelect = $("select[name='ostreetList']");
                streetSelect.empty();

                streetData.forEach(function(street) {
                    streetSelect.append(new Option(street.name, street.id));
                });

                streetSelect.find("option").each(function() {
                    if ($(this).val() === operatorData.street) {
                        $(this).prop("selected", true);
                    }
                });
            }).fail(function() {
                showAlertModal('Failed to fetch streets.');
            });

            $("input[name='oemail']").val(operatorData.email);

            $("input[name='omobile']").val(directformatPhone(operatorData.mobile_number));
            if (operatorData.home_number != '') {
                $("input[name='ohome']").val(directformatPhone(operatorData.home_number));
            }

            $("#updateoperatormodal").modal('show');
        } else {
            showAlertModal('Failed to fetch operator details.');
        }
    }).fail(function() {
        showAlertModal('An error occurred while fetching operator details.');
    });
}

// function showConfirmModal(message, confirmCallback) {
//     // Set the modal's message dynamically
//     document.querySelector('#reusableConfirmModal .modal-body').textContent = message;

//     // Show the modal
//     $('#reusableConfirmModal').modal('show');

//     // Remove any existing event listeners to avoid duplicate actions
//     const confirmButton = document.getElementById('reusableConfirmButton');
//     confirmButton.replaceWith(confirmButton.cloneNode(true));

//     // Add a new event listener for the confirm button
//     document.getElementById('reusableConfirmButton').addEventListener('click', function () {
//         $('#reusableConfirmModal').modal('hide'); // Close the modal
//         confirmCallback(); // Execute the callback function
//     });
// }

function showConfirmModal(message, confirmCallback, cancelCallback) {
    const modal = $("#reusableConfirmModal");

    // Set the modal's message dynamically
    modal.find(".modal-body").text(message);

    // ✅ Ensure confirm modal appears on top dynamically
    setTimeout(() => {
        const highestZIndex = Math.max(
            ...Array.from(document.querySelectorAll('.modal'))
            .map(el => parseFloat(window.getComputedStyle(el).zIndex) || 1050)
        ) + 10; // Ensure it's above the highest modal

        modal.css("z-index", highestZIndex);
    }, 50);

    // Show the modal
    modal.modal("show");

    // ✅ Use querySelector inside the modal to ensure correct button
    setTimeout(() => {
        // const confirmButton = modal.find("#reusableConfirmButton").get(0);
        // if (confirmButton) {
        //     confirmButton.removeEventListener("click", handleConfirmClick); // Prevent duplicate listeners
        //     confirmButton.addEventListener("click", handleConfirmClick);
        // } else {
        //     console.error("Error: Confirm button not found!");
        // }

        const confirmButton = modal.find("#reusableConfirmButton");
        confirmButton.off("click").on("click", function () { // Ensures only one event listener
            // console.log("Confirm clicked");
            modal.modal("hide"); // Close modal
            if (typeof confirmCallback === "function") {
                confirmCallback();
            }
        });

        modal.find(".btn-secondary")
            .off("click")  // ✅ Remove previous event listeners
            .on("click", function () {
                // console.log("Cancel clicked");
                modal.modal("hide");
                if (typeof cancelCallback === "function") {
                    cancelCallback();
                }
            });
        // const cancelButton = modal.find(".btn-secondary").get(0);
        // if (cancelButton) {
        //     cancelButton.removeEventListener("click", handleCancelClick);
        //     cancelButton.addEventListener("click", handleCancelClick);
        // } else {
        //     console.error("Error: Cancel button not found!");
        // }
    }, 100); // Delay ensures modal elements exist before accessing them

    // ✅ Callback handlers (Must be defined outside to avoid reassignments)
    // function handleConfirmClick() {
    //     console.log("Confirm clicked");
    //     modal.modal("hide"); // Close modal
    //     if (typeof confirmCallback === "function") {
    //         confirmCallback();
    //     }
    // }

    // function handleCancelClick() {
    //     console.log("Cancel clicked");
    //     modal.modal("hide"); // Close modal
    //     if (typeof cancelCallback === "function") {
    //         cancelCallback();
    //     }
    // }
}




// function showAlertModal(message, callback) {
//     const modal = $("#reusableAlertModal");
//     modal.find(".modal-body").text(message);

//     modal.find(".btn-primary").off("click").on("click", function () {
//         modal.modal("hide");
//         if (typeof callback === "function") {
//             callback();
//         }
//     });

//     modal.modal("show");
// }
function showAlertModal(message, callback) {
    const modal = $("#reusableAlertModal");

    modal.find(".modal-body").text(message);

    setTimeout(() => {
        const highestZIndex = Math.max(
            ...Array.from(document.querySelectorAll('.modal'))
            .map(el => parseFloat(window.getComputedStyle(el).zIndex) || 1050)
        ) + 10;

        modal.css("z-index", highestZIndex);
    }, 50);

    modal.find(".btn-primary").off("click").on("click", function () {
        modal.modal("hide");
        if (typeof callback === "function") {
            callback();
        }
    });

    modal.modal("show");
}

// function deleteUser(name, userId, propertyId) {

//     if (confirm('Are you sure you want to Delete this User: ' +name + " " + userId + " and property = " + propertyId) == true) {
//         // alert('true');

//         $.ajax({
//             url: 'include/users/users_db.php',
//             type: 'post',
//             data: { deleteUser: 'yes', userid: userId, property:  propertyId}
//         }).done(function(data) {
//             if (data === 'Success') {
//                 alert("The User " + name + " has been Succesfully Deleted!");
//                 getUsers();
//                 getOperators();
//             }else {
//                 alert("Something went wrong Please try again.");
//             }
//         });

//     }else {
//         // alert('false');
//     }

    
// }

function deleteUser(name, userId, propertyId) {
    showConfirmModal(
        `Are you sure you want to delete the user: ${name} (UserID: ${userId}) and property = ${propertyId}?`,
        function () {
            // Perform the delete action via AJAX
            $.ajax({
                url: 'include/users/users_db.php',
                type: 'post',
                data: { deleteUser: 'yes', userid: userId, property: propertyId }
            }).done(function (data) {
                let parsed = typeof data === 'string' ? JSON.parse(data) : data;

                if (parsed.status === 'redirect' && parsed.location) {
                    window.location.href = parsed.location;
                } else {
                    showAlertModal('Something went wrong. Please try again.');
                }
            });
        }
    );
}



function deleteOperator(name, userId, propertyId) {
    showConfirmModal(
        'Are you sure you want to delete this Operator: ' + name + ' (UserID: ' + userId + ')?',
        function () {
            $.ajax({
                url: 'include/users/operators_db.php',
                type: 'post',
                data: { deleteOperator: 'yes', userid: userId, property: propertyId }
            }).done(function (data) {
                if (data === 'Success') {
                    showAlertModal("The Operator " + name + " has been successfully deleted!");
                    window.location.reload();

                } else if (data === 'Current User') {
                    showAlertModal("Something went wrong. You can not delete yourself.");
                } else {
                    showAlertModal("Something went wrong. Please try again.");
                }
            });
        }
    );
}


function confirmDealerUpdate(event) {
    event.preventDefault();

    showConfirmModal(
        "Are you sure you want to update this Dealer?",
        function () {
            const form = document.getElementById("updateDealer");

            $('#reusableConfirmModal').modal('hide');

            setTimeout(() => {

                form.removeAttribute("onsubmit");

                const submitButton = form.querySelector("[type=submit]");
                if (submitButton) {
                    submitButton.click();
                } else {
                    console.warn("No submit button found. Forcing submission.");
                    HTMLFormElement.prototype.submit.call(form);
                }
            }, 300);
        }
    );

    return false;
}


// function confirmAdminUpdate(event) {
//     event.preventDefault();

//     showConfirmModal(
//         "Are you sure you want to update this System Admin?",
//         function () {
//             document.getElementById("updateAdmin").submit();
//         }
//     );

//     return false;
// }

function confirmAdminUpdate(event) {
    event.preventDefault();

    showConfirmModal(
        "Are you sure you want to update this System Admin?",
        function () {
            const form = document.getElementById("updateAdmin");

            if (!form) {
                console.error("Error: #updateAdmin does not exist at execution time.");
                return;
            }

            if (form.tagName !== "FORM") {
                console.error("Error: #updateAdmin is not a <form> element.");
                return;
            }

            console.log("Submitting form:", form);

            $('#reusableConfirmModal').modal('hide');

            setTimeout(() => {

                form.removeAttribute("onsubmit");

                const submitButton = form.querySelector("[type=submit]");
                if (submitButton) {
                    submitButton.click();
                } else {
                    console.warn("No submit button found. Forcing submission.");
                    HTMLFormElement.prototype.submit.call(form);
                }
            }, 300);
        }
    );

    return false;
}

function editDealer(userId) {

    const idstore = `
        <input type="hidden" name="idstore" id="idstore">
    `;

    if (!document.querySelector('input[name="idstore"]')) {
        $("form").append(DOMPurify.sanitize(idstore));
    }

    $.ajax({
        url: '../include/admin/dealer_db.php',
        method: 'POST',
        data: { updatedealer: 'yes', userid: userId, getslots: 'yes'},
        dataType: 'json',
    }).done(function(data) { 
        if (data) {
            const userData = data[0];

            $("input[name='idstore']").val(userData.id);
            $("input[name='companyname']").val(userData.company_name);
            $("input[name='dFname']").val(userData.firstname);
            $("input[name='dLname']").val(userData.lastname);
            $("input[name='email']").val(userData.email);
            $("input[name='dealerslots']").val(userData.slots_avail);
            $("input[name='dealerUslots']").val(userData.slots_used);
            $("#dealer_logo").attr('src', '');
            $(".dealer_logo").addClass('showHide');
            if(userData.logo_loc != "" && userData.logo_loc != null && userData.logo_loc != undefined){
                
                var imagePath = "/shared/serve_image.php?path=" + encodeURIComponent(userData.logo_loc) + "&type=profile";
                $("#dealer_logo").attr('src', imagePath);
                $(".dealer_logo").removeClass('showHide');

            }
            // const updateButton = `
            //     <button type="button" class="btn btn-primary" id="updateDealerBtn">Update Dealer</button>
            // `;
            // const closeButton = `
            //     <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            // `;

            // $(".modal-footer").html(updateButton + closeButton);

            $("#updatedealermodal").modal('show');
        } else {
            showAlertModal('Failed to fetch Dealers details.');
        }
    }).fail(function() {
        showAlertModal('An error occurred while fetching Dealers details.');
    });
}

function editAdmin(userId) {

    const idstore = `
        <input type="hidden" name="idstore" id="idstore">
    `;

    if (!document.querySelector('input[name="idstore"]')) {
        $("form").append(DOMPurify.sanitize(idstore));
    }

    $.ajax({
        url: '../include/admin/admin_db.php',
        method: 'POST',
        data: { updateadmin: 'yes', userid: userId},
        dataType: 'json',
    }).done(function(data) { 

        if (data) {
            const userData = data[0];

            $("input[name='idstore']").val(userData.id);
            $("input[name='companyname']").val(userData.company_name);
            $("input[name='aFname']").val(userData.firstname);
            $("input[name='aLname']").val(userData.lastname);
            $("input[name='email']").val(userData.email);
            $("input[name='dealerslots']").val(userData.slots_avail);
            $("input[name='dealerUslots']").val(userData.slots_used);

            // const updateButton = `
            //     <button type="button" class="btn btn-primary" id="updateAdminBtn">Update Admin</button>
            // `;
            // const closeButton = `
            //     <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            // `;

            // $(".modal-footer").html(updateButton + closeButton);

            $("#updateadminmodal").modal('show');
        } else {
            showAlertModal('Failed to fetch Dealers details.');
        }
    }).fail(function() {
        showAlertModal('An error occurred while fetching Dealers details.');
    });
}

function recover(name, userId, propertyId) {

    showConfirmModal(
        'Are you sure you want to recover this User: ' + name + ' (UserID: ' + userId + ') and property = ' + propertyId + '?',
        function () {

            $.ajax({
                url: 'include/users/users_db.php',
                type: 'post',
                data: { recoverUsers: 'yes', userid: userId, property:  propertyId}
            }).done(function(data) {
                if (data === 'Success') {
                    showAlertModal("The User " + name + " has been Succesfully Restored!");
                    window.location.reload();
                    // getdeleted();
                }else {
                    showAlertModal("Something went wrong Please try again.");
                }
            });

        }
    );
}

// function editVisitor(userId) {

//     $.ajax({
//         url: 'include/visitors/visitors.php',
//         method: 'POST',
//         data: { visitorId: userId, action: 'getVisitorDetails' },
//         dataType: 'json',
//         success: function(response) {
//             if (response.success) {

//                 window.keyTypeData = response.data;

//                 console.log(keyTypeData);

//                 $('#uvisitorId').val(response.data.id);
//                 $('#uvisitorName').val(response.data.name);

//                 var keyTypeSelect = $('#ukeytypelist');
//                 keyTypeSelect.empty();

//                 keyTypeSelect.append('<option disabled selected>Please Select a Key Type</option>');
//                 var ketypeData = [];

//                 response.data.key_types.forEach(function(keyType) {

//                     var visitorKeyType = response.data.key_type.replace(/_/g, ' ');
//                     var dropdownKeyType = keyType.name;

//                     var selected = (dropdownKeyType == visitorKeyType) ? 'selected' : '';

//                     if (keyType.id !== 3) { // Hiding Magic Password for now
//                         if ((dropdownKeyType == visitorKeyType === true)) {
//                             ketypeData = { id: keyType.id, name: keyType.name}; 
//                         }
                        
//                         keyTypeSelect.append('<option value="' + keyType.id + '" ' + selected + '>' + keyType.name + '</option>');
//                     }
//                 });

//                 $('#ukeytypelist').val(ketypeData.id).trigger('change');

//                 setTimeout(function() {
//                     if (response.data.key_type === 'CallerID+Code') {
//                         $('input[name="upcidphone"]').val(response.data.cidphone);
//                         $('input[name="upcidcode"]').val(response.data.cidcode);
//                     } else if (response.data.key_code) {
//                         $('input[name="upkeycode"]').val(response.data.key_code);
//                     } else if (response.data.phone) {
//                         $('input[name="upcallerid_phone"]').val(response.data.phone);
//                     } else if (response.data.magic_password) {
//                         $('textarea[name="upmagicpassword"]').val(response.data.magic_password);
//                     }
//                 }, 200);

//                 $('#ukeymode').val(response.data.key_mode).trigger('change');

//                 setTimeout(function() {
//                     if (response.data.uses) {
//                         $('#upuses').val(response.data.uses).trigger('change');
//                     }else if (response.data.start_date && response.data.end_date && (!response.data.start_time || !response.data.end_time)) {
//                         $('#upstart_date').val(response.data.start_date);
//                         $('#upend_date').val(response.data.end_date);
//                     }else if (response.data.start_time && response.data.end_time && (!response.data.start_date || !response.data.end_date)) {
//                         $('#upstart_time').val(response.data.start_time);
//                         $('#upend_time').val(response.data.end_time);
//                     }else if (response.data.start_time && response.data.end_time && response.data.start_date && response.data.end_date) {
//                         $('#upstart_time1').val(response.data.start_time);
//                         $('#upend_time1').val(response.data.end_time);
//                         $('#upstart_date1').val(response.data.start_date);
//                         $('#upend_date1').val(response.data.end_date);
//                     }else if (response.data.schedule) {
//                         $('#upschedule').val(response.data.schedule).trigger('change');
//                     }

//                 }, 200);

//                 $('#visitorupdatemodal').modal('show');

//             } else {
//                 alert('Failed to fetch visitor details.');
//             }
//         },
//         error: function(xhr, status, error) {
//             console.error('Error fetching visitor data:', error);
//         }
//     });
// }

function editVisitor(userId) {

    $.ajax({
        url: 'include/visitors/visitors.php',
        method: 'POST',
        data: { visitorId: userId, action: 'getVisitorDetails' },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                window.keyTypeData = response.data;
                var door_data = keyTypeData.door_data;

                $('#uvisitorId').val(response.data.id);
                $('#uvisitorName').val(response.data.name);
                // var uvisitor_door = $("#uvisitor_door");
                // uvisitor_door.empty();

                // uvisitor_door.append('<option disabled value="'+response.data.door_id+'" selected>'+door_data.door_name+'</option>');                

                var keyTypeSelect = $('#ukeytypelist');
                keyTypeSelect.empty();

                keyTypeSelect.append('<option disabled selected>Please Select a Key Type</option>');
                var ketypeData = [];

                response.data.key_types.forEach(function(keyType) {

                    var visitorKeyType = response.data.key_type.replace(/_/g, ' ');
                    var dropdownKeyType = keyType.name;

                    var selected = (dropdownKeyType == visitorKeyType) ? 'selected' : '';

                    if (keyType.id !== 3) { // Hiding Magic Password for now
                        if ((dropdownKeyType == visitorKeyType === true)) {
                            ketypeData = { id: keyType.id, name: keyType.name}; 
                        }
                        
                        const option = $('<option>')
                            .val(keyType.id)
                            .text(keyType.name);

                        if (dropdownKeyType === visitorKeyType) {
                            option.prop('selected', true);
                        }

                        keyTypeSelect.append(option);
                    }
                });

                $('#ukeytypelist').val(ketypeData.id).trigger('change');

                setTimeout(function() {
                    if (response.data.key_type === 'CallerID+Code') {
                        $('input[name="upcidphone"]').val(response.data.cidphone);
                        $('input[name="upcidcode"]').val(response.data.cidcode);
                    } else if (response.data.key_code) {
                        $('input[name="upkeycode"]').val(response.data.key_code);
                    } else if (response.data.phone) {
                        $('input[name="upcallerid_phone"]').val(response.data.phone);
                    } else if (response.data.magic_password) {
                        $('textarea[name="upmagicpassword"]').val(response.data.magic_password);
                    }
                }, 200);

                $('#ukeymode').val(response.data.key_mode).trigger('change');
                setTimeout(function() {
                    $("#remianing_uses").addClass('showHide');
                    if (response.data.uses !== null) {
                        $('#upuses').val(response.data.total_uses);
                        $("#remianing_uses").removeClass('showHide');
                        $('#remianing_uses').text(response.data.uses + " of " + response.data.total_uses + " remaining");
                    }else if (response.data.start_date && response.data.end_date && (!response.data.start_time || !response.data.end_time)) {
                        $('#upstart_date').val(response.data.start_date);
                        $('#upend_date').val(response.data.end_date);
                    }else if (response.data.start_time && response.data.end_time && (!response.data.start_date || !response.data.end_date)) {
                        $('#upstart_time').val(response.data.start_time);
                        $('#upend_time').val(response.data.end_time);
                    }else if (response.data.start_time && response.data.end_time && response.data.start_date && response.data.end_date) {
                        $('#upstart_time1').val(response.data.start_time);
                        $('#upend_time1').val(response.data.end_time);
                        $('#upstart_date1').val(response.data.start_date);
                        $('#upend_date1').val(response.data.end_date);
                    }else if (response.data.schedule) {
                        $('#upschedule').val(response.data.schedule).trigger('change');
                    }
                }, 300); // Increased timeout to ensure dynamic form generation completes

                $('#visitorupdatemodal').modal('show');

            } else {
                showAlertModal('Failed to fetch visitor details.');
            }
        },
        error: function(xhr, status, error) {
            console.error('Error fetching visitor data:', error);
        }
    });
}

function resendInvite(email) {

    $.ajax({
        url: 'include/users/users_db.php',
        type: 'post',
        data: { resendInvite: 'yes', email: email}
    }).done(function(data) {
        if (data === 'Success') {
            showAlertModal("Invite was Successfully Sent!");
        }else {
            showAlertModal("Something went wrong Please try again.");
        }
    });
}
function clearModal(modalId) {
    const modal = document.getElementById(modalId);

    modal.querySelectorAll('form').forEach((form) => {
        form.reset();
    });

    modal.querySelectorAll('#keytypeelements, #keytypeelements1, #dynamic-form-elements, #dynamic-form-elements1').forEach((container) => {
        container.innerHTML = '';
    });

    modal.querySelectorAll('#keytypelist, #keytypelist1, #keymode, #keymode1').forEach((dropdown) => {
        dropdown.selectedIndex = 0;
    });

    modal.querySelectorAll('.error-message').forEach((message) => {
        message.textContent = '';
    });

    modal.querySelectorAll('[data-modal-flag]').forEach((flag) => {
        flag.dataset.modalFlag = '';
    });
}

function editVendor(userId) {
    keyType('Uvendors');
    $.ajax({
        url: 'include/visitors/visitors.php',
        method: 'POST',
        data: { vendorId: userId, action: 'getVendorDetails' },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                setTimeout(function() {
                    window.keyTypeData = response.data;

                    $('#uvendorId').val(response.data.id);
                    $('#uvendorCompany').val(response.data.company);
                    $('#uvendorName').val(response.data.name);

                    var keyTypeSelect = $('#ukeytypelist12');
                    keyTypeSelect.empty();

                    keyTypeSelect.append('<option disabled selected>Please Select a Key Type</option>');
                    var ketypeData = [];
                    // $("#uvendor_door").val(response.data.door_id).trigger('change');
                    response.data.key_types.forEach(function(keyType) {

                        var visitorKeyType = response.data.key_type.replace(/_/g, ' ');
                        var dropdownKeyType = keyType.name;

                        var selected = (dropdownKeyType == visitorKeyType) ? 'selected' : '';
                        if (keyType.id !== 3) { // Hiding Magic Password for now

                            if ((dropdownKeyType == visitorKeyType === true)) {
                                ketypeData = { id: keyType.id, name: keyType.name}; 
                            }
        
                            const option = $('<option>')
                                .val(keyType.id)
                                .text(keyType.name);

                            if (dropdownKeyType === visitorKeyType) {
                                option.prop('selected', true);
                            }

                            keyTypeSelect.append(option);

                        }
                        
                    });
                    
                    $("#ukeytypeList12").val(ketypeData.id).trigger('change');
                    
                    if (response.data.key_type === 'CallerID+Code') {
                        $('input[name="ucidphone"]').val(response.data.cidphone);
                        $('input[name="ucidcode"]').val(response.data.cidcode);
                    } else if (response.data.key_code) {
                        $('input[name="ukeycode"]').val(response.data.key_code);
                    } else if (response.data.phone) {
                        $('input[name="ucallerid_phone"]').val(response.data.phone);
                    } else if (response.data.magic_password) {
                        $('textarea[name="umagicpassword"]').val(response.data.magic_password);
                    }

                    $('#ukeymode1').val(response.data.key_mode).trigger('change');
                    
                    // Wait for dynamic form elements to be generated before setting values
                    setTimeout(function() {
                        $("#vremianing_uses").addClass('showHide');
                        if (response.data.uses) {
                            $('#uuses').val(response.data.total_uses).trigger('change');
                            $("#vremianing_uses").removeClass('showHide');
                            $('#vremianing_uses').text(response.data.uses + " of " + response.data.total_uses + " remaining");
                        }else if (response.data.start_date && response.data.end_date && (!response.data.start_time || !response.data.end_time)) {
                            $('#ustart_date').val(response.data.start_date);
                            $('#uend_date').val(response.data.end_date);
                        }else if (response.data.start_time && response.data.end_time && (!response.data.start_date || !response.data.end_date)) {
                            $('#ustart_time').val(response.data.start_time);
                            $('#uend_time').val(response.data.end_time);
                        }else if (response.data.start_time && response.data.end_time && response.data.start_date && response.data.end_date) {
                            $('#ustart_time1').val(response.data.start_time);
                            $('#uend_time1').val(response.data.end_time);
                            $('#ustart_date1').val(response.data.start_date);
                            $('#uend_date1').val(response.data.end_date);
                        }else if (response.data.schedule) {
                            $('#uschedule').val(response.data.schedule).trigger('change');
                        }
                    }, 300); // Increased timeout to ensure dynamic form generation completes

                    $('#vendorUpdatemodal').modal('show');
                }, 100);

            } else {
                showAlertModal('Failed to fetch Vendor details.');
            }
        },
        error: function(xhr, status, error) {
            console.error('Error fetching Vendor data:', error);
        }
    });
}

function deleteVisitor(name, userId, propertyId) {
    showConfirmModal(
        'Are you sure you want to delete this Visitor: ' + name + ' (UserID: ' + userId + ') and property = ' + propertyId + '?',
        function () {
            $.ajax({
                url: 'include/visitors/visitors.php',
                type: 'post',
                data: { deleteVisitor: 'yes', userid: userId, property: propertyId }
            }).done(function (data) {
                if (data === 'Success') {
                    showAlertModal("The Visitor " + name + " has been successfully deleted!");
                    getVisitors();
                } else {
                    showAlertModal("Something went wrong. Please try again.");
                }
            });
        }
    );
}


function deleteVendor(name, userId, propertyId) {
    showConfirmModal(
        'Are you sure you want to delete this Vendor: ' + name + ' (UserID: ' + userId + ') and property = ' + propertyId + '?',
        function () {
            $.ajax({
                url: 'include/visitors/visitors.php',
                type: 'post',
                data: { deleteVendor: 'yes', userid: userId, property: propertyId }
            }).done(function (data) {
                if (data === 'Success') {
                    showAlertModal("The Vendor " + name + " has been successfully deleted!");
                    getVendors();
                } else {
                    showAlertModal("Something went wrong. Please try again.");
                }
            });
        }
    );
}


function keyType(flag) {
    $.ajax({
        url: 'include/visitors/visitors.php',
        type: 'post',
        data: { getKeyType: 'yes' }
    }).done(function(data) {
        var json_parse = JSON.parse(data);
        var kType = json_parse.keyType;
        var doors = json_parse.doors;
        var doors_dropdown = "";
        if (flag === 'visitors') {
            var dropdown = document.getElementById('keytypelist');
            // doors_dropdown = document.getElementById('visitor_door');
        }else if (flag === 'vendors') {
            var dropdown = document.getElementById('keytypelist1');
            // doors_dropdown = document.getElementById('vendor_door');
        }else if (flag === 'Uvisitors') {
            var dropdown = document.getElementById('ukeytypelist');
            // doors_dropdown = document.getElementById('uvisitor_door');
        }else if (flag === 'Uvendors') {
            var dropdown = document.getElementById('ukeytypeList12');
            // doors_dropdown = document.getElementById('uvendor_door');
        }
        // doors_dropdown.innerHTML = '';
        dropdown.innerHTML = '';

        var defaultOption = document.createElement('option');
        defaultOption.text = 'Please Select a Key Type';
        defaultOption.disabled = true;
        defaultOption.selected = true;
        dropdown.appendChild(defaultOption);

        // var defaultOption1 = document.createElement('option');
        // defaultOption1.text = 'Please Select a door';
        // defaultOption1.disabled = true;
        // defaultOption1.value = '';
        // defaultOption1.selected = true;
        // doors_dropdown.appendChild(defaultOption1);

        // doors.forEach(function(item1) {
        //     var option1 = document.createElement('option');
        //     option1.value = item1.id;
        //     option1.text = item1.door_name;
        //     doors_dropdown.appendChild(option1);
        // });

        kType.forEach(function(item) {

            if (item.name !== 'Magic Password') {
                var option = document.createElement('option');
                option.value = item.id;
                option.text = item.name; 
                option.title = item.desc;
                dropdown.appendChild(option);
            }
        });
    });
}

function searchTable(tableId, searchInputId) {
    var input, filter, table, tr, td, i, txtValue;
    input = document.getElementById(searchInputId);
    filter = input.value.toLowerCase();
    table = document.getElementById(tableId);
    tr = table.getElementsByTagName("tr");

    for (i = 1; i < tr.length; i++) {
        tr[i].style.display = "none";
        td = tr[i].getElementsByTagName("td");
        for (var j = 0; j < td.length; j++) {
            if (td[j]) {
                txtValue = td[j].textContent || td[j].innerText;
                if (txtValue.toLowerCase().indexOf(filter) > -1) {
                    tr[i].style.display = "";
                    break;
                }
            }
        }
    }
}

function searchExpandableTable(tableId, searchInputId) {
    const input = document.getElementById(searchInputId);
    const filter = input.value.toLowerCase();
    const table = document.getElementById(tableId);
    const tr = table.getElementsByTagName("tr");

    let currentOrgRow = null;

    for (let i = 0; i < tr.length; i++) {
        const row = tr[i];
        const isOrgRow = row.hasAttribute("data-widget");
        const isExpandableBody = row.classList.contains("expandable-body");

        if (isOrgRow) {
            currentOrgRow = row;
            row.style.display = "none";
        }

        if (isOrgRow || isExpandableBody) {
            const td = row.getElementsByTagName("td");
            let rowVisible = false;

            for (let j = 0; j < td.length; j++) {
                const txtValue = td[j].textContent || td[j].innerText;
                if (txtValue.toLowerCase().indexOf(filter) > -1) {
                    rowVisible = true;
                    break;
                }
            }

            if (rowVisible) {
                if (isOrgRow) {
                    row.style.display = "";
                } else if (currentOrgRow) {
                    currentOrgRow.style.display = "";
                    row.style.display = "";
                }
            } else if (isExpandableBody) {
                row.style.display = "none";
            }
        }
    }
}

function getHardware() {
    
    $.ajax({
        url: 'include/hardware/hardware.php',
        type: 'post',
        data: { getHardware: 'yes'}
    }).done(function(data) { 
        // console.log(data);
        var hwData = JSON.parse(data);

        hwData.forEach(function (data) {

            var hardname = data.hardware;
            var hwList = "<option value=" + hardname + ">" + hardname.toUpperCase() + "</option>";
            document.getElementById("hardwareType1").innerHTML += DOMPurify.sanitize(hwList);
            
        });
        

    });
}

$(document).on("change", "#dealer", function () {
    console.log("Change Detect");
    const dealerId = $(this).val();
    if (!dealerId) return;

    $("#ftpServerSlotContainer").empty();

    loadFtpSlotsForDealer();

    loadAvailableFtpServers(dealerId);
});

$(document).ready(function () {
    $(".sblink").click(function (e) {
        e.preventDefault();

        var page = $(this).data("page"); // Get the page to load from data attribute

        // Send an AJAX request to load the content page
        $.ajax({
        url: page,
        method: "GET",
        success: function (data) {
            $("#display-div").html(data); // Load the content page into the display div

            // Currently I have seperate calls for page and then for Data this may need to change????
            // Function to get the correct Data based on selected page
            switch (page) {

            case "include/signalwire/my_numbers.php":
                mySignalwireNumbers();
                break;
            case "include/properties/my_properties.php":
                myProperties();
                break;
            case "include/admin/admin_setup.php":
                adminSetup();
                break;
            case "include/admin/dealer_setup.php":
                dealerSetup();
                break;
            case "include/properties/rolestbl.php":
                getRoles();
                break;
            case "include/dashboard/dashboard.php":
                // getDashboardData();
                break;
            case "include/users/users.php":
                getCreateRoles();
                getOperatorRoles();
                // getProps();
                // var usersContent = document.getElementById('usersContent');
                // usersContent.style.display = 'none';
                break;
            case "include/visitors/visitorstbl.php":

                var property = $("#selectproperty").val();
                getVendors(property);
                getVisitors(property); 

                break;

            default:
            }
        },
        error: function () {
            $("#display-div").html("<p>Error loading page. please refresh the page.</p>"); // Show an error message on failure
        },
        });
    });

    if (!window.location.href.includes("?")) {
        var childCount = $("#display-div").children().length;
        if (childCount == 0) {
        loadDashboard();
        }
    }

    getProps();

});

function loadDashboard() {
    $.ajax({
        url: "include/dashboard/dashboard.php",
        method: "GET",
        success: function (data) {
        $("#display-div").html(data);
        // getDashboardData();
        // Additional actions specific to the dashboard can be added here if needed
        },
        error: function () {
        $("#display-div").html("<p>Error loading dashboard.</p>");
        },
    });
}

function getDashboardData() {
    $.ajax({
        url: "include/dashboard/dashboard_request.php",
        type: "post",
        data: {
            getDashboardData: "yes",
            property_id:sessionStorage.getItem("propertyId")
        },
        success: function (response) {
            var a = BaseCostData({ getBaseCost: "yes"}, "dashboard");
            // const cards_error=document.getElementById("cards_error");
            // if(!response?.property_id && cards_error){
            //     cards_error.style.display="block";
            //     cards_error.style.color="red";
            //     cards_error.innerHTML="Please select property id"
            // }else if(cards_error)cards_error.style.display="none";
            
            // var allIds = [
            //     "registered_users_container",
            //     "units_number_container",
            //     "Door_Gate_number_container",
            //     "invisible_keys_number_container",
            //     "calls_number_container",
            //     "voice_call_log_cost_container",
            //     "voice_calls_log_duration_container",
            //     "total_dashboard_sms_container",
            //     "total_dashboard_sms_amount_container"
            // ];

            // var propertyUserShow = [
            //     "invisible_keys_number_container",
            //     "calls_number_container",
            //     "total_dashboard_sms_container",
            //     // "total_dashboard_sms_amount_container"
            // ];

            // if (response && response.is_property_user) {
            //     toggleDisplay(allIds, false);
            //     toggleDisplay(propertyUserShow, true);
            // } else {
            //     toggleDisplay(allIds, true);
            // }
            if(response?.Property_id) console.log(response?.Property_id);
            // $("#registered_users").text(response?.usersLength || 0);
            // $("#units_number").text(response?.unitsLength || 0);
            // $("#Door_Gate_number").text(response?.doorsLength || 0);
            // $("#invisible_keys_number").text(response?.activeKeysLength || 0);
            $("#calls_number").text(response?.callsLength || 0);
            $("#voice_call_log_cost").text(response?.voice_calls_cost || 0);
            $("#voice_calls_log_duration").text(response?.voice_calls_duration || 0);
            $("#total_dashboard_sms").text(response?.total_messages);
            $("#total_dashboard_sms_amount").text(response?.messages_amount || 0);

        },
        error: function (xhr, status, error) {
            console.log("got error in dashboar cards ", error);
        },
    });
}

function BaseCostData(data, bit="", date="", is_invoice=""){
  $.ajax({
    url: "/include/subscription/subscription.php",
    type: "post",
    data,
    success: function (response) {
      var json_parse = JSON.parse(response);
      var user_layer = json_parse.user_layer;
      var base_sub = json_parse.base_sub;
      var property_sub = json_parse.property_sub;
      var property_cameras = json_parse.property_cameras;
      var property_numbers = json_parse.property_numbers;
      var property_doors = json_parse.property_doors;
      var property_cellular_sim = json_parse.property_cellular_sim;
      var property_users = json_parse.property_users;
      var minimum_balance = base_sub.minimum_balance;
      var property_balance = json_parse.property_balance;
      var balance = 0;
    
      var dealer_sub_fee = base_sub.sub_fee;
      var dealer_camera_add = base_sub.camera_add;
      var dealer_number_add = base_sub.number_add;
      var dealer_door_add = base_sub.door_add;
      var dealer_cellular_sim = base_sub.cellular_sim;
      var msrp_sub_fee = base_sub.msrp_sub_fee;
      var msrp_camera_add = base_sub.msrp_camera_add;
      var msrp_number_add = base_sub.msrp_number_add;
      var msrp_door_add = base_sub.msrp_door_add;
      var msrp_cellular_sim = base_sub.msrp_cellular_sim;
      var total_dealer_users_fee_add_on = 0;
      var total_number_fee_add_on = 0;
      var dealer_total_cameras_fee = 0;
      var msrp_total_cameras_fee = 0;
      var total_number_fee_add_on = 0;
      var total_msrp_number_fee_add_on = 0;
      var total_dealer_door_fee_add_on = 0;
      var total_msrp_door_fee_add_on = 0;
      var total_dealer_cellular_sim_fee_add_on = 0;
      var total_msrp_cellular_sim_fee_add_on = 0;
      var total_dealer_users_fee_add_on = 0;
      var total_msrp_users_fee_add_on = 0;
      if(property_sub.sub_fee != 0 && property_sub.sub_fee != undefined){
        dealer_sub_fee = property_sub.sub_fee;
      }
      if(property_sub.camera_add != 0 && property_sub.camera_add != undefined){
        dealer_camera_add = property_sub.camera_add;
      }
      if(property_sub.number_add != 0 && property_sub.number_add != undefined){
        dealer_number_add = property_sub.number_add;
      }
      if(property_sub.door_add != 0 && property_sub.door_add != undefined){
        dealer_door_add = property_sub.door_add;
      }
      if(property_sub.cellular_sim != 0 && property_sub.cellular_sim != undefined){
        dealer_cellular_sim = property_sub.cellular_sim;
      }
      if(property_sub.msrp_sub_fee != 0 && property_sub.msrp_sub_fee != undefined){
        msrp_sub_fee = property_sub.msrp_sub_fee;
      }
      if(property_sub.msrp_camera_add != 0 && property_sub.msrp_camera_add != undefined){
        msrp_number_add = property_sub.msrp_camera_add;
      }
      if(property_sub.msrp_number_add != 0 && property_sub.msrp_number_add != undefined){
        msrp_number_add = property_sub.msrp_number_add;
      }
      if(property_sub.msrp_door_add != 0 && property_sub.msrp_door_add != undefined){
        msrp_door_add = property_sub.msrp_door_add;
      }
      if(property_sub.msrp_cellular_sim != 0 && property_sub.msrp_cellular_sim != undefined){
        msrp_cellular_sim = property_sub.msrp_cellular_sim;
      }
      if(property_balance != 0){
        if(property_balance.balance != 0 && property_balance.balance != undefined){
          balance = property_balance.balance;
        }
        if(property_balance.minimum_balance != 0 && property_balance.minimum_balance != undefined){
          minimum_balance = property_balance.minimum_balance;
        }
      }

      if(property_cameras != undefined && property_cameras != null && property_cameras != 0){
        dealer_total_cameras_fee = property_cameras * dealer_camera_add;
        msrp_total_cameras_fee = property_cameras * msrp_camera_add;
        
      }
      if(property_numbers != undefined && property_numbers != null && property_numbers != 0){
        total_number_fee_add_on = property_numbers * dealer_number_add;
        total_msrp_number_fee_add_on = property_numbers * msrp_number_add;
      }
      if(property_doors != undefined && property_doors != null && property_doors != 0){
        total_dealer_door_fee_add_on = property_doors * dealer_door_add;
        total_msrp_door_fee_add_on = property_doors * msrp_door_add;
      }
      if(property_cellular_sim != undefined && property_cellular_sim != null && property_cellular_sim != 0){
        total_dealer_cellular_sim_fee_add_on = property_cellular_sim * dealer_cellular_sim;
        total_msrp_cellular_sim_fee_add_on = property_cellular_sim * msrp_cellular_sim;
      }

      if(property_users != undefined && property_users != null && property_users != 0){
        total_dealer_users_fee_add_on = Number(property_users) * 0.05;
        total_msrp_users_fee_add_on = Number(property_users) * 0.1;
        total_dealer_users_fee_add_on = total_dealer_users_fee_add_on.toFixed(2)
        total_msrp_users_fee_add_on = total_msrp_users_fee_add_on.toFixed(2)
      }      

      var main_sub_fee_for_dealer = Number(dealer_sub_fee) + Number(dealer_total_cameras_fee) + Number(total_number_fee_add_on) + Number(total_dealer_door_fee_add_on) + Number(total_dealer_users_fee_add_on) + Number(total_dealer_cellular_sim_fee_add_on);
      
      var main_msrp_fee = Number(msrp_sub_fee) + Number(msrp_total_cameras_fee) + Number(total_msrp_number_fee_add_on) + Number(total_msrp_door_fee_add_on) + Number(total_msrp_users_fee_add_on) + Number(total_msrp_cellular_sim_fee_add_on);
      
      if(bit == "dashboard"){
        $("#dashboard_dealer_cost").html("$" + main_sub_fee_for_dealer + "/month");
        $("#dashboard_msrp_cost").html("$" + main_msrp_fee + "/month");
        $("#dashboard_property_balance").html("$" + balance);
      }
      else{
        $(".base_cost_content_data").removeClass("showHide");
        $(".sub_fee_add_on").html("$" + dealer_sub_fee + "/month");
        $(".camera_fee_add_on").html("$" + dealer_camera_add + "/month");
        $(".number_fee_add_on").html("$" + dealer_number_add + "/month");
        $(".door_fee_add_on").html("$" + dealer_door_add + "/month");
        $(".sim_fee_add_on").html("$" + dealer_cellular_sim + "/month");
        if(is_invoice !== 1){
            $("#main_msrp_fee").html("$" + main_msrp_fee + "/month");
            $("#main_sub_fee_add_on").html("$" + main_sub_fee_for_dealer + "/month");
            $(".msrp_sub_fee_add_on").html("$" + msrp_sub_fee + "/month");
            $(".total_msrp_sub_fee").html(msrp_sub_fee);
            $(".msrp_camera_fee_add_on").html("$" + msrp_camera_add + "/month");
            $(".msrp_number_fee_add_on").html("$" + msrp_number_add + "/month");
            $(".msrp_door_fee_add_on").html("$" + msrp_door_add + "/month");
            $(".msrp_sim_fee_add_on").html("$" + msrp_cellular_sim + "/month");
            $(".total_msrp_camera_fee_add_on").html(msrp_total_cameras_fee);
            $(".total_msrp_number_fee_add_on").html(total_msrp_number_fee_add_on);
            $(".total_msrp_door_fee_add_on").html(total_msrp_door_fee_add_on);
            $(".total_msrp_sim_fee_add_on").html(total_msrp_cellular_sim_fee_add_on);
            $(".total_msrp_users_fee_add_on").html(total_msrp_users_fee_add_on);
        }
        else{
            $(".modal_dealer_subtotal").html("$" + main_sub_fee_for_dealer);
            $(".modal_dealer_total").html("$" + main_sub_fee_for_dealer);
            $(".invoice_date").html(json_parse.formatted_date);
            $(".invoice_formatted_date").val(json_parse.formatted_date);
            $(".invoice_property_name").val(json_parse.property.name);
        }
        $(".total_dealer_sub_fee").html(dealer_sub_fee);
        $(".total_camera_add_on").html(property_cameras);
        $(".total_dealer_camera_fee_add_on").html(dealer_total_cameras_fee);
        $(".total_number_add_on").html(property_numbers);
        $(".total_number_fee_add_on").html(total_number_fee_add_on);
        $(".total_door_add_on").html(property_doors);
        $(".total_sim_add_on").html(property_cellular_sim);
        $("#total_callular_sim").val(property_cellular_sim);
        $(".total_dealer_door_fee_add_on").html(total_dealer_door_fee_add_on);
        $(".total_dealer_sim_fee_add_on").html(total_dealer_cellular_sim_fee_add_on);
        $(".total_users_add_on").html(property_users);
        $(".total_dealer_users_fee_add_on").html(total_dealer_users_fee_add_on);

        if(balance != undefined && balance != null && balance != 0){  
          $("#property_remaining_balance").html("$" + balance);
        }
        if(minimum_balance != undefined && minimum_balance != null && minimum_balance != 0){
          $("#minimum_balance_variable_cost").html("$" + minimum_balance + ".00");
        }
        balance = Number(balance);
        minimum_balance = Number(minimum_balance);
        if(balance <= minimum_balance){
          $("#waller_progress_bar").css('background-color', '#dc3545');
          $("#waller_progress_bar").css('width', '10%');
        }
        else{
          $("#waller_progress_bar").css('background-color', '#007bff');
          $("#waller_progress_bar").css('width', '70%');
        }  
      }

      

    },
    error: function (xhr, status, error) {
      console.error("Failed to fetch data:", status, error);
    },
  }); 
}

function toggleDisplay(ids, show) {
    for (var i = 0; i < ids.length; i++) {
        var el = document.getElementById(ids[i]);
        if (el) el.style.display = show ? "block" : "none";
    }
}

var cropper;

function triggerImagePreviewAndCrop(event, type) {

    var inputImage = document.getElementById('propImage');
    
    if (type === 'prop') {
        var previewImage = document.getElementById('imagePreview');
        var image = document.getElementById('imageToCrop');

        var files = event.target.files;

        if (files && files.length > 0) {

            var reader = new FileReader();
            reader.onload = function(e) {

                previewImage.src = e.target.result;
                previewImage.style.display = 'block';          

                image.src = e.target.result;
                $('#cropModal').modal('show');
                
            };

            reader.readAsDataURL(files[0]);
            
        }
    }else {
        var previewImage = document.getElementById('uimagePreview');
        var image = document.getElementById('uimageToCrop');

        var files = event.target.files;

        if (files && files.length > 0) {

            var reader = new FileReader();
            reader.onload = function(e) {

                previewImage.src = e.target.result;
                previewImage.style.display = 'block';          

                image.src = e.target.result;
                $('#ucropModal').modal('show');
                
            };

            reader.readAsDataURL(files[0]);
            
        }
    }

}

var cropper = null; // Make sure Cropper is globally available

function cropImage(type) {
    var image = (type === 'prop') ? document.getElementById('imageToCrop') : document.getElementById('uimageToCrop');

    if (!image || image.naturalWidth === 0 || image.naturalHeight === 0) {
        console.error('Image not loaded or has zero size');
        return;
    }

    // Destroy any previous Cropper instance
    if (cropper) {
        cropper.destroy();
        cropper = null;
    }

    // Initialize Cropper
    cropper = new Cropper(image, {
        aspectRatio: 1,
        viewMode: 2,
        ready: function () {
            console.log("Cropper is ready");
        }
    });
}


function processCrop(type) {
    if (!cropper || !cropper.ready) {
        console.error("Cropper is not ready");
        return;
    }

    var canvas = cropper.getCroppedCanvas({
        width: 200,  // Adjust the output size as needed
        height: 200
    });

    if (!canvas) {
        console.error('Failed to generate canvas for cropped image');
        return;
    }

    canvas.toBlob(function (blob) {
        var fileInput = document.getElementById(type === 'prop' ? 'propImage' : 'upropImage');
        var previewImage = document.getElementById(type === 'prop' ? 'imagePreview' : 'uimagePreview');

        if (!fileInput || !previewImage) {
            console.error('Missing fileInput or previewImage element');
            return;
        }

        // Create a new File object and update the input
        var dataTransfer = new DataTransfer();
        var file = new File([blob], 'cropped_image.jpg', { type: 'image/jpeg' });
        dataTransfer.items.add(file);
        fileInput.files = dataTransfer.files;

        // Update the preview image
        previewImage.src = canvas.toDataURL('image/jpeg');
        previewImage.style.display = 'block';

        console.log("Cropped image set in input field");

        // Close the crop modal but keep the main modal open
        if (type === 'prop') {
            $('#cropModal').modal('hide');
        } else {
            $('#ucropModal').modal('hide');
        }

        // Ensure the main modal remains open
        setTimeout(function () {
            if ($('#propmodal').hasClass('show') || $('#upropmodal').hasClass('show')) {
                $('body').addClass('modal-open');
            }
        }, 500);
    }, 'image/jpeg');
}


document.addEventListener('click', function (event) {
    if (event.target.id === 'cropImage') {
        event.preventDefault();
        processCrop('prop');
    } else if (event.target.id === 'ucropImage') {
        event.preventDefault();
        processCrop('uprop');
    }else if (event.target.id === 'fullImage'){
        event.preventDefault();
        setTimeout(function () {
            if ($('#propmodal').hasClass('show') || $('#upropmodal').hasClass('show')) {
                $('body').addClass('modal-open');
            }
        }, 500);  
    }
});


const modalRestoreMap = {
    '#cropModal': '#propmodal',
    '#ucropModal': '#upropmodal',
    '#reusableAlertModal': '#upropmodal'
};

$.each(modalRestoreMap, function (closedModalId, parentModalId) {
    $(document).on('hidden.bs.modal', closedModalId, function () {
        if ($(parentModalId).hasClass('show')) {
            $('body').addClass('modal-open');
        }
    });
});




function getupdatedimage(currentProp) {
    $.ajax({
        url: "include/properties/property.php",
        type: "post",
        data: {getupdateimage: "yes", currentProp: currentProp},
        success: function (data) {

            var response = JSON.parse(data);

            document.getElementById('propImageSB').src = '';
            document.getElementById('propImageSB').src = '/shared/serve_image.php?path=' + response[0] + '&type=property';
            document.getElementById('propImageName').textContent = '';
            document.getElementById('propImageName').textContent = response[1];

        },
        error: function (xhr, status, error) {
            console.log("got error in", error);
        },
    });
}

document.addEventListener('DOMContentLoaded', function() {

    $(document).on('click', '[data-widget="expandable-table"]', function() {
        // console.log("Row clicked!");
        const $row = $(this);
        const $nextRow = $row.next('.expandable-body');
    
        if ($nextRow.length) {
            const isHidden = $nextRow.css('display') === 'none';
            $nextRow.css('display', isHidden ? 'table-row' : 'none');
            $row.attr('aria-expanded', isHidden ? 'true' : 'false');
            $row.find('.expandable-table-caret').toggleClass('fa-caret-right', !isHidden).toggleClass('fa-caret-down', isHidden);
            // console.log(isHidden ? "Expanded row" : "Collapsed row");
        } else {
            // console.warn("No expandable row found.");
        }
        
    });

    document.addEventListener('click', function(event) {
        const targetId = event.target.id;
    
        switch (targetId) {
            case 'slotModalBtn':
                $('#dealerslotsform')[0].reset();
                $('#dealerslotsresult').html('');
                loadDealerSlots();
                break;
    
            case 'addRole':
                resetForm('roleForm');
                $("#jsGrid1").jsGrid("destroy");
                $("#jsGrid1").empty();
                // getProps();
                
                const roleSelect = document.querySelector('#layerlist');
                if (roleSelect) {
                    roleSelect.addEventListener('change', function(event) {
                        customRoleBldr(event.target.value);
                    });
                }
                break;
    
            case 'addUser':
                resetForm('newUserForm');
                getUsers();
                // document.getElementById('streetlist').innerHTML= "<option value=''>Please Select</option>";
                document.getElementById('streetlist').innerHTML=DOMPurify.sanitize(`<option value=''>Please Select</option>
                <option style="color: blue;font-weight: 700;cursor: pointer;"  value='add_new'>Add new</option>`);
                getStreets();
                break;
    
            case 'users-tab':
                getUsers();
                break;
    
            case 'operators-tab':
                setTimeout(function() {
                    $("#operatorsTable").DataTable().columns.adjust().responsive.recalc();
                }, 300);
                getOperators();
                break;
    
            case 'manage-tab':
                setTimeout(function() {
                    $("#deletedOper").DataTable().columns.adjust().responsive.recalc();
                    $("#deletedUser").DataTable().columns.adjust().responsive.recalc();
                }, 300);
                getdeleted();
                break;

            case 'admins-tab':
                getDealerAdmins();
                break;
            case 'addAdmins':
                // $('#adminsmodal').on('shown.bs.modal', function () {
                //     $(this).find('input[name="email"]').prop('disabled', false);
                // })
                $('#adminsmodal').find('form')[0].reset();
                break;
            case 'setPermissions':
                myProperties();
                break;
            case 'editPermissionsBtn':
                myProperties();
                break;

            case 'addHardwareBtn':
                getHardware();
                break;

            case 'cropImage':
                cropImage('prop');
                break;

            case 'ucropImage':
                cropImage('uprop');
                break;

            case 'closeCropModal':

                if (cropper) {
                    cropper.destroy();
                    cropper = null;
                }
                $('#cropModal').modal('hide');

                break;

            case 'addvisitor':
                clearModal('visitormodal');
                keyType('visitors');
                break;

            case 'addvendor':
                clearModal('vendormodal');
                keyType('vendors');
                break;
    
            default:

                break;
        }
        var flashMessage = document.getElementById('flashMessage');
        if (flashMessage) {
            flashMessage.style.display = 'none';
        }
    });
    
    const selectPropertyElement = document.querySelector('#selectproperty');
    
    if (selectPropertyElement) {
        // Add a change event listener directly to the dropdown
        selectPropertyElement.addEventListener('change', function(event) {
            const selectedProperty = event.target.value; // Get the selected value
            console.log('Selected property:', selectedProperty);
            
            // Call your custom functions
            getupdatedimage(selectedProperty); // Update the image
            
            // Get the CSRF token
            const csrfTokenElement = document.querySelector('meta[name="csrf-token"]');
            if (!csrfTokenElement) {
                console.error('CSRF token meta tag is missing');
                return;
            }
            const csrfToken = csrfTokenElement.getAttribute('content');

            // Send the selected property to the server
            const xhr = new XMLHttpRequest();
            xhr.open('POST', 'include/users/session_variable.php', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function () {
                if (xhr.readyState === XMLHttpRequest.DONE) {
                    if (xhr.status === 200) {
                        console.log('Server response:', xhr.responseText);
                        location.reload(); // Reload the page
                    } else {
                        console.error('Request failed with status:', xhr.status);
                    }
                }
            };
            xhr.send(`selectedProperty=${encodeURIComponent(selectedProperty)}&csrf_token=${encodeURIComponent(csrfToken)}`);
        });
    } else {
        console.error('#selectproperty element not found');
    }

    // document.addEventListener('change', function(event) {
    //     // console.log("before change");
    //     if (event.target.matches('#selectproperty')) {

    //         // var currentProp = $("#selectproperty").val();
    //         var currentProp = event.target.value;
    //         getupdatedimage(currentProp);
    //         // console.log("in change");
    //         // return;

    //         var selectedProperty = event.target.value;

    //         var csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

    //         // to fix the url exposing file structure may need to create a location variable on server. 
    //         // Need to discuss or do more research on best approach.
    //         // This should be throughout not just here.

    //         // Send the selected value to the server
    //         var xhr = new XMLHttpRequest();
    //         xhr.open('POST', 'include/users/session_variable.php', true);
    //         xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    //         xhr.onreadystatechange = function () {
    //             if (xhr.readyState === XMLHttpRequest.DONE) {
    //                 console.log(xhr.responseText);
    //                 if (xhr.status === 200) {
    //                     // Refresh the page after the server response is successfully handled
    //                     location.reload();
    //                 }
    //             }
    //         };
    //         xhr.send('selectedProperty=' + encodeURIComponent(selectedProperty) + '&csrf_token=' + encodeURIComponent(csrfToken));
    //     }
    // });    
});

function generateKeyCode(type) {

    $.ajax({
        url: 'include/visitors/visitors.php',
        type: 'POST',
        data: { checkKeyCode: true},
        dataType: 'json',
        success: function(response) {
            // console.log(response);
            if (response) {
                if (type == 'keycode') {
                    $('input[name="keycode"]').val(response);
                }else if (type == 'upkeycode') {
                    $('input[name="upkeycode"]').val(response);
                }else if (type == 'upkeycode1') {
                    $('input[name="upkeycode1"]').val(response);
                }else if (type == 'ucidcode') {
                    $('input[name="ucidcode"]').val(response);
                }else if (type == 'upcidcode') {
                    $('input[name="upcidcode"]').val(response);
                }else {
                    $('input[name="keycode1"]').val(response);
                }
            }
        },
        error: function(xhr, status, error) {
            console.error('Error checking key code:', error);
        }
    });
}

$(document).on('change', '#keytypelist', function() {
    send_code_to_visitor();
    var selectedKeyType = $(this).val();
    var keyTypeElements = $('#keytypeelements');
    keyTypeElements.html('');

    if (selectedKeyType === '1') {
        keyTypeElements.html(`
        <div class="input-group mb-3">

            <input type="text" name="callerid_phone" id="callerid_phone" required class="form-control" oninput="formatPhoneNumber(this)" title="Phone Number" placeholder="Enter phone number" onpaste="handlePaste(event)">
            <div class="input-group-append">
                <div class="input-group-text">
                    <span class="fa-solid fa-phone" title="Phone Number"></span>
                </div>
            </div>
        </div>
        `);
    } else if (selectedKeyType === '2') {
        keyTypeElements.html(`
            <div class="input-group mb-3">
                <input type="text" name="keycode" required maxlength="4" class="form-control" title="KeyCode" placeholder="Enter key code" readonly>
                <div class="input-group-append">
                    <button type="button" id="generate4digit" class="btn btn-primary btn-block">Generate 4-digit PIN</button>
                </div>
                <div class="input-group-append">
                    <div class="input-group-text">
                        <span class="fa-solid fa-key" title="KeyCode"></span>
                    </div>
                </div>
            </div>
        `);

        $('#generate4digit').on('click', function() {
            generateKeyCode('keycode');
        });

    } else if (selectedKeyType === '3') {
        keyTypeElements.html(`
            <textarea name="magicpassword" rows="3" maxlength="100" required class="form-control" placeholder="Enter your magic password (This can be a single word or a phrase)"></textarea>`);
    }else if (selectedKeyType === '4') {
        keyTypeElements.html(`
            <div class="input-group mb-3">
                <input type="text" oninput="formatPhoneNumber(this)" onpaste="handlePaste(event)" name="cidphone" id="cidphone" required class="form-control" title="Phone" placeholder="Enter Phone Number">
                <div class="input-group-append">
                    <div class="input-group-text">
                        <span class="fa-solid fa-key" title="Phone Number"></span>
                    </div>
                </div>
            </div>
            <div class="input-group mb-3">
                <input type="text" name="cidcode" required class="form-control" maxlength="4" title="Code" placeholder="Enter Key Code">
                <div class="input-group-append">    
                    <button type="button" id="generate4digit1" class="btn btn-primary btn-block">Generate 4-digit PIN</button>
                </div>
                <div class="input-group-append">
                    <div class="input-group-text">
                        <span class="fa-solid fa-key" title="Key Code"></span>
                    </div>
                </div>
            </div>
        `);

        $('#generate4digit1').on('click', function() {
            $('input[name="cidcode"]').val(Math.floor(1000 + Math.random() * 9000));
        });
    }
});

$(document).on('change', '#keytypelist1', function() {
    send_code_to_vendor();
    var selectedKeyType = $(this).val();
    var keyTypeElements = $('#keytypeelements1');
    keyTypeElements.html('');

    if (selectedKeyType === '1') {
        keyTypeElements.html(`
            <div class="input-group mb-3">
                <input type="text" name="vcallerid_phone" id="vcallerid_phone" oninput="formatPhoneNumber(this)" onpaste="handlePaste(event)" required class="form-control" placeholder="Enter phone number">
                <div class="input-group-append">
                    <div class="input-group-text">
                        <span class="fa-solid fa-phone" title="Phone Number"></span>
                    </div>
                </div>
            </div>
        `);
    } else if (selectedKeyType === '2') {
        keyTypeElements.html(`
            <div class="input-group mb-3">
                <input type="text" name="keycode1" required class="form-control" maxlength="4" title="KeyCode" placeholder="Enter key code" readonly>
                <div class="input-group-append">
                    <button type="button" id="vgenerate4digit" class="btn btn-primary btn-block">Generate 4-digit PIN</button>
                </div>
                <div class="input-group-append">
                    <div class="input-group-text">
                        <span class="fa-solid fa-key" title="KeyCode"></span>
                    </div>
                </div>
            </div>
        `);

        $('#vgenerate4digit').on('click', function() {
            generateKeyCode('keycode1');
        });

    } else if (selectedKeyType === '3') {
        keyTypeElements.html(`
            <textarea name="vmagicpassword" rows="3" maxlength="100" required class="form-control" placeholder="Enter your magic password (This can be a single word or a phrase)"></textarea>
        `);
    }else if (selectedKeyType === '4') {
        keyTypeElements.html(`
            <div class="input-group mb-3">
                <input type="text" name="vcidphone" id="vcidphone" oninput="formatPhoneNumber(this)" required class="form-control" title="Phone" placeholder="Enter Phone Number">
                <div class="input-group-append">
                    <div class="input-group-text">
                        <span class="fa-solid fa-key" title="Phone Number"></span>
                    </div>
                </div>
            </div>
            <div class="input-group mb-3">
                <input type="text" name="vcidcode" required class="form-control" maxlength="4" title="Code" placeholder="Enter key code">
                <div class="input-group-append">
                    <button type="button" id="vgenerate4digit1" class="btn btn-primary btn-block">Generate 4-digit PIN</button>
                </div>
                <div class="input-group-append">
                    <div class="input-group-text">
                        <span class="fa-solid fa-key" title="Key Code"></span>
                    </div>
                </div>
            </div>
        `);
        $('#vgenerate4digit1').on('click', function() {
            $('input[name="vcidcode"]').val(Math.floor(1000 + Math.random() * 9000));
        });
    }

});

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

    var selectedKeyType = $(this).val();
    var keyTypeElements = $('#ukeytypeelements');
    keyTypeElements.html('');

    if (selectedKeyType === '1') {
        keyTypeElements.html(`
            <input type="tel" name="upcallerid_phone" class="form-control" title="Phone Number" placeholder="Enter phone number" disabled value="${window.keyTypeData.phone ?? ''}">
            <div class="input-group-append">
                <div class="input-group-text">
                    <span class="fa-solid fa-phone" title="Phone Number"></span>
                </div>
            </div>
        `);
    } else if (selectedKeyType === '2' && window.keyTypeData) {
        keyTypeElements.html(`
            <input type="text" name="upkeycode" maxlength="4" class="form-control" title="KeyCode" placeholder="Enter key code" disabled value="${window.keyTypeData.key_code ?? ''}">
            <div class="input-group-append">
                <div class="input-group-text">
                    <span class="fa-solid fa-key" title="KeyCode"></span>
                </div>
            </div>
        `);
        // removed from html to prevent edit.
        // <div class="input-group-append">
        //     <button type="button" id="ugenerate4digit" class="btn btn-primary">Generate 4-digit PIN</button>
        // </div>
        $('#ugenerate4digit').on('click', function() {
            generateKeyCode('upkeycode');
        });

    } else if (selectedKeyType === '3') {
        keyTypeElements.html(`
            <textarea name="upmagicpassword" rows="3" maxlength="100" required class="form-control" placeholder="Enter your magic password (This can be a single word or a phrase)"></textarea>
        `);
    }else if (selectedKeyType === '4') {
        keyTypeElements.html(`
            <input type="tel" name="upcidphone" class="form-control" title="CallerId+Code" placeholder="Enter Phone Number" disabled value="${window.keyTypeData.cidphone ?? ''}">
            <input type="text" name="upcidcode" class="form-control" maxlength="4" placeholder="Enter key code" disabled value="${window.keyTypeData.cidcode ?? ''}">
            <div class="input-group-append">
                <div class="input-group-text">
                    <span class="fa-solid fa-key" title="CallerId+Code"></span>
                </div>
            </div>
        `);
        // removed from html to prevent edit.
        // <div class="input-group-append">
        //     <button type="button" id="ugenerate4digit1" class="form-control btn-primary" >Generate 4-digit PIN</button>
        // </div>

        $('#ugenerate4digit1').on('click', function() {
            generateKeyCode('upcidcode');
        });
    }
});

$(document).on('change', '#ukeytypeList12', function() {
    var selectedKeyType = $(this).val();
    var keyTypeElements = $('#ukeytypeelements1');
    keyTypeElements.html('');

    if (selectedKeyType === '1') {
        keyTypeElements.html(`
            <input type="tel" name="ucallerid_phone" class="form-control" title="Phone Number" placeholder="Enter phone number" disabled value="${window.keyTypeData.phone ?? ''}">
            <div class="input-group-append">
                <div class="input-group-text">
                    <span class="fa-solid fa-phone" title="Phone Number"></span>
                </div>
            </div>
        `);
    } else if (selectedKeyType === '2') {
        keyTypeElements.html(`
            <input type="text" name="upkeycode1" maxlength="4" class="form-control" title="KeyCode" placeholder="Enter key code" disabled value="${window.keyTypeData.key_code ?? ''}">
            <div class="input-group-append">
                <div class="input-group-text">
                    <span class="fa-solid fa-key" title="KeyCode"></span>
                </div>
            </div>
        `);
        // removed from html to prevent edit. 
        // <div class="input-group-append">
        //     <button type="button" id="ugenerate4digitV" class="btn btn-primary">Generate 4-digit PIN</button>
        // </div>
        
        $('#ugenerate4digitV').on('click', function() {
            generateKeyCode('upkeycode1');
        });
        

    } else if (selectedKeyType === '3') {
        keyTypeElements.html(`
            <textarea name="umagicpassword" rows="3" maxlength="100" required class="form-control" placeholder="Enter your magic password (This can be a single word or a phrase)"></textarea>
        `);
    }else if (selectedKeyType === '4') {
        keyTypeElements.html(DOMPurify.sanitize(`
            <input type="tel" name="ucidphone" class="form-control" title="Phone" placeholder="Enter Phone Number" disabled value="${window.keyTypeData.cidphone ?? ''}">
            <input type="text" name="ucidcode" maxlength="4" class="form-control" title="Code" placeholder="Enter key code" disabled value="${window.keyTypeData.cidcode ?? ''}">
            <div class="input-group-append">
                <div class="input-group-text">
                    <span class="fa-solid fa-key" title="CallerId+Code"></span>
                </div>
            </div>
        `));
        // removed from html to prevent edit. 
        // <div class="input-group-append">
        //     <button type="button" id="ugenerate4digit1V" class="form-control btn-primary">Generate 4-digit PIN</button>
        // </div>
        $('#ugenerate4digit1V').on('click', function() {
            generateKeyCode('ucidcode');
        });
    }
});

$(document).on('change', '#keymode', function() {
    var selectedMode = $(this).val();
    var dynamicFormElements = document.getElementById('dynamic-form-elements');

    dynamicFormElements.innerHTML = '';

    if (selectedMode === 'uses') {
        dynamicFormElements.innerHTML = `
            <select id="uses" name="uses" class="form-control" title="Uses" required>
                <option value="1">1</option>
                <option value="5">5</option>
                <option value="10">10</option>
            </select>`;
    } else if (selectedMode === 'date') {
        dynamicFormElements.innerHTML = `
            <label for="start_date" class="form-control" style="max-width: 15%;">Start</label>
            <input type="date" id='start_date' name="start_date" class="form-control" title="Start Date" placeholder="Start Date" required>
            <label for="end_date" class="form-control" style="max-width: 15%;">End</label>
            <input type="date" id='end_date' name="end_date" class="form-control" title="End Date" placeholder="End Date" required>`;
    } else if (selectedMode === 'time') {
        dynamicFormElements.innerHTML = `
            <label for="start_time" class="form-control" style="max-width: 20%;">Start</label>
            <input type="time" id='start_time' name="start_time" class="form-control" title="Start Time" placeholder="Start Time" required>
            <label for="end_time" class="form-control" style="max-width: 20%;">End</label>
            <input type="time" id='end_time' name="end_time" class="form-control" title="End Time" placeholder="End Time" required>`;
    } else if (selectedMode === 'date_time') {
        dynamicFormElements.innerHTML = `
            <label for="start_date" class="form-control" style="max-width: 20%;">Start</label>
            <input type="date" id="start_date" name="start_date" class="form-control" title="Start Date" placeholder="Start Date" required>
            <input type="time" id="start_time" name="start_time" class="form-control" style="max-width: 30%;" title="Start Time" placeholder="Start Time" required>
            <div class="input-group-append">
                <div class="input-group-text">
                    <span class="fa-solid fa-calendar-week" title="Start Date/Time"></span>
                </div>
            </div>
        </div>
        <div class="input-group mb-3">
            <label for="end_date" class="form-control" style="max-width: 20%;">End</label>
            <input type="date" id='end_date' name="end_date" class="form-control" title="End Date" placeholder="End Date" required>
            <input type="time" id='end_time' name="end_time" class="form-control" style="max-width: 30%;" title="End Time" placeholder="End Time"required>
            <div class="input-group-append">
                <div class="input-group-text">
                    <span class="fa-solid fa-calendar-week" title="End Date/Time"></span>
                </div>`;
    } else if (selectedMode === 'schedule') {
        get_schedules_requests({ getScheduleRequest: true,type:'visitor',property_id:sessionStorage.getItem("propertyId") }).then(data => {
            let options = '';
            data.forEach(item => {
                options += `<option value="${item.id}">${item.title}</option>`;
            });
            dynamicFormElements.innerHTML = `
                <select id="schedule" name="schedule" class="form-control" required>
                    <option value="">Select a schedule</option>
                    ${options}
                </select>
            `;
        });
    }
});

$(document).on('change', '#keymode1', function() {
    var selectedMode = $(this).val();
    var dynamicFormElements = document.getElementById('dynamic-form-elements1');

    dynamicFormElements.innerHTML = '';

    if (selectedMode === 'uses') {
        dynamicFormElements.innerHTML = `
            <select id="vuses" name="vuses" class="form-control" required>
                <option value="1">1</option>
                <option value="5">5</option>
                <option value="10">10</option>
            </select>`;
    } else if (selectedMode === 'date') {
        dynamicFormElements.innerHTML = `
            <label for="vstart_date" class="form-control" style="max-width: 15%;">Start</label>
            <input type="date" id='vstart_date' name="vstart_date" class="form-control" placeholder="Start Date" required>
            <label for="vend_date" class="form-control" style="max-width: 15%;">End</label>
            <input type="date" id='vend_date' name="vend_date" class="form-control" placeholder="End Date" required>`;
    } else if (selectedMode === 'time') {
        dynamicFormElements.innerHTML = `
            <label for="vstart_time" class="form-control" style="max-width: 20%;">Start</label>
            <input type="time" id='vstart_time' name="vstart_time" class="form-control" placeholder="Start Time" required>
            <label for="vend_time" class="form-control" style="max-width: 20%;">End</label>
            <input type="time" id='vend_time' name="vend_time" class="form-control" placeholder="End Time" required>`;
    } else if (selectedMode === 'date_time') {
        dynamicFormElements.innerHTML = `
            <label for="vstart_date1" class="form-control" style="max-width: 20%;">Start</label>
            <input type="date" id="vstart_date1" name="vstart_date1" class="form-control" placeholder="Start Date" required>
            <input type="time" id="vstart_time1" name="vstart_time1" class="form-control" style="max-width: 30%;" placeholder="Start Time" required>
            <div class="input-group-append">
                <div class="input-group-text">
                    <span class="fa-solid fa-calendar-week" title="Start Date/Time"></span>
                </div>
            </div>
        </div>
        <div class="input-group mb-3">
            <label for="vend_date1" class="form-control" style="max-width: 20%;">End</label>
            <input type="date" id='vend_date1' name="vend_date1" class="form-control" placeholder="End Date" required>
            <input type="time" id='vend_time1' name="vend_time1" class="form-control" style="max-width: 30%;" placeholder="End Time"required>
            <div class="input-group-append">
                <div class="input-group-text">
                    <span class="fa-solid fa-calendar-week" title="End Date/Time"></span>
                </div>`;
    } else if (selectedMode === 'schedule') {
        get_schedules_requests({ getScheduleRequest: true,type:'visitor',property_id:sessionStorage.getItem("propertyId") }).then(data => {
            let options = '';
            data.forEach(item => {
                options += `<option value="${item.id}">${item.title}</option>`;
            });
            dynamicFormElements.innerHTML = `
                <select id="vschedule" name="vschedule" class="form-control" required>
                    <option value="">Select a schedule</option>
                    ${options}
                </select>
            `;
        });
    }
});

$(document).on('change', '#ukeymode', function() {
    var selectedMode = $(this).val();
    var dynamicFormElements = document.getElementById('udynamic-form-elements');

    dynamicFormElements.innerHTML = '';

    if (selectedMode === 'uses') {
        dynamicFormElements.innerHTML = `
            <input type = "text" id ="upuses" name="upuses" class="form-control" title="Uses" readonly>`;
    } else if (selectedMode === 'date') {
        dynamicFormElements.innerHTML = `
            <label for="upstart_date" class="form-control" style="max-width: 15%;">Start</label>
            <input type="date" id='upstart_date' name="upstart_date" class="form-control" title="Start Date" placeholder="Start Date" disabled>
            <label for="upend_date" class="form-control" style="max-width: 15%;">End</label>
            <input type="date" id='upend_date' name="upend_date" class="form-control" title="End Date" placeholder="End Date" disabled>`;
    } else if (selectedMode === 'time') {
        dynamicFormElements.innerHTML = `
            <label for="upstart_time" class="form-control" style="max-width: 20%;">Start</label>
            <input type="time" id='upstart_time' name="upstart_time" class="form-control" title="Start Time" placeholder="Start Time" disabled>
            <label for="upend_time" class="form-control" style="max-width: 20%;">End</label>
            <input type="time" id='upend_time' name="upend_time" class="form-control" title="End Time" placeholder="End Time" disabled>`;
    } else if (selectedMode === 'date_time') {
        dynamicFormElements.innerHTML = `
            <label for="upstart_date1" class="form-control" style="max-width: 20%;">Start</label>
            <input type="date" id="upstart_date1" name="upstart_date1" class="form-control" placeholder="Start Date" disabled>
            <input type="time" id="upstart_time1" name="upstart_time1" class="form-control" style="max-width: 30%;" placeholder="Start Time" disabled>
            <div class="input-group-append">
                <div class="input-group-text">
                    <span class="fa-solid fa-calendar-week" title="Start Date/Time"></span>
                </div>
            </div>
        </div>
        <div class="input-group mb-3">
            <label for="upend_date1" class="form-control" style="max-width: 20%;">End</label>
            <input type="date" id='upend_date1' name="upend_date1" class="form-control" title="End Date" placeholder="End Date" disabled>
            <input type="time" id='upend_time1' name="upend_time1" class="form-control" style="max-width: 30%;" title="End Time" placeholder="End Time"disabled>
            <div class="input-group-append">
                <div class="input-group-text">
                    <span class="fa-solid fa-calendar-week" title="End Date/Time"></span>
                </div>`;
    } else if (selectedMode === 'schedule') {
        get_schedules_requests({ getScheduleRequest: true,type:'visitor',property_id:sessionStorage.getItem("propertyId") }).then(data => {
            let options = '';
            data.forEach(item => {
                options += `<option value="${item.id}">${item.title}</option>`;
            });
            dynamicFormElements.innerHTML = `
                <select id="upschedule" name="upschedule" class="form-control" required disabled>
                    <option value="">Select a schedule</option>
                    ${options}
                </select>
            `;
        });
    }
});

$(document).on('change', '#ukeymode1', function() {
    var selectedMode = $(this).val();
    var dynamicFormElements = document.getElementById('udynamic-form-elements1');

    dynamicFormElements.innerHTML = '';

    if (selectedMode === 'uses') {
        dynamicFormElements.innerHTML = `
            <select id="uuses" name="uuses" class="form-control" title="Uses" placeholder="Select Number of Uses" disabled>
                <option value="1">1</option>
                <option value="5">5</option>
                <option value="10">10</option>
            </select>`;
    } else if (selectedMode === 'date') {
        dynamicFormElements.innerHTML = `
            <label for="ustart_date" class="form-control" style="max-width: 15%;">Start</label>
            <input type="date" id='ustart_date' name="ustart_date" class="form-control" title="Start Date" placeholder="Start Date" disabled>
            <label for="uend_date" class="form-control" style="max-width: 15%;">End</label>
            <input type="date" id='uend_date' name="uend_date" class="form-control" title="End Date" placeholder="End Date" disabled>`;
    } else if (selectedMode === 'time') {
        dynamicFormElements.innerHTML = `
            <label for="ustart_time" class="form-control" style="max-width: 20%;">Start</label>
            <input type="time" id='ustart_time' name="ustart_time" class="form-control" title="Start Time" placeholder="Start Time" disabled>
            <label for="uend_time" class="form-control" style="max-width: 20%;">End</label>
            <input type="time" id='uend_time' name="uend_time" class="form-control" title="End Time" placeholder="End Time" disabled>`;
    } else if (selectedMode === 'date_time') {
        dynamicFormElements.innerHTML = `
            <label for="ustart_date1" class="form-control" style="max-width: 20%;">Start</label>
            <input type="date" id='ustart_date1' name="ustart_date1" class="form-control" title="Start Date" placeholder="Start Date" disabled>
            <input type="time" id='ustart_time1' name="ustart_time1" class="form-control" title="Start Time" placeholder="Start Time" disabled>
            <div class="input-group-append">
                <div class="input-group-text">
                    <span class="fa-solid fa-calendar-week" title="Start Date/Time"></span>
                </div>
            </div>
        </div>
        <div class="input-group mb-3">
            <label for="uend_date1" class="form-control" style="max-width: 20%;">End</label>
            <input type="date" id='uend_date1' name="uend_date1" class="form-control" title="End Date" placeholder="End Date" disabled>
            <input type="time" id='uend_time1' name="uend_time1" class="form-control" title="End Time" placeholder="End Time" disabled>
            <div class="input-group-append">
                <div class="input-group-text">
                    <span class="fa-solid fa-calendar-week" title="End Date/Time"></span>
                </div>`;
    } else if (selectedMode === 'schedule') {
        get_schedules_requests({ getScheduleRequest: true,type:'visitor',property_id:sessionStorage.getItem("propertyId") }).then(data => {
            let options = '';
            data.forEach(item => {
                options += `<option value="${item.id}">${item.title}</option>`;
            });
            dynamicFormElements.innerHTML = `
                <select id="uschedule" name="uschedule" class="form-control" required disabled>
                    <option value="">Select a schedule</option>
                    ${options}
                </select>
            `;
        });
    }
});

document.getElementById('changePasswordForm').addEventListener('submit', function (event) {
    const newPassword = document.getElementById('newPassword').value;
    const confirmPassword = document.getElementById('confirmPassword').value;

    const passwordPattern = /^(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+|~=`{}\[\]:";'<>,.\/]).{8,}$/;

    if (newPassword !== confirmPassword) {
        event.preventDefault();
        showAlertModal("Passwords do not match.");
    } else if (!passwordPattern.test(newPassword)) {
        event.preventDefault();
        showAlertModal("Password must be at least 8 characters, include 1 uppercase letter, 1 number, and 1 special character.");
    }
});

function get_schedules_requests(data) {
    return new Promise((resolve, reject) => {
      $.ajax({
        url: "/include/property_builder/hardwares/hardwares_request.php",
        type: "post",
        data,
        success: function (resp) {
            // all_schedules_command = resp.data;
            resolve(resp.data);
        },
        error: function (xhr, status, error) {
          if (xhr?.responseJSON?.error)
            globalErrorToastMessage(xhr?.responseJSON?.error);
          else globalErrorToastMessage(error);
          reject();
        },
      });
    });
}

const newPassword = document.getElementById('newPassword');
const passwordStrength = document.getElementById('passwordStrength');

newPassword.addEventListener('input', function () {
    const value = newPassword.value;
    let strength = 0;

    // Evaluate password strength
    if (value.length >= 8) strength += 25; // Minimum length
    if (/[A-Z]/.test(value)) strength += 25; // At least one uppercase letter
    if (/\d/.test(value)) strength += 25; // At least one number
    if (/[!@#$%^&*()_+|~=`{}\[\]:";'<>,.\/]/.test(value)) strength += 25; // At least one special character

    passwordStrength.value = strength;

    passwordStrength.classList.remove('red', 'yellow', 'blue', 'green');

    if (strength <= 25) {
        passwordStrength.classList.add('red');
    } else if (strength <= 50) {
        passwordStrength.classList.add('yellow');
    } else if (strength <= 75) {
        passwordStrength.classList.add('blue');
    } else if (strength === 100) {
        passwordStrength.classList.add('green');
    }
});

function selectAvatar(element) {
    // Reset border for all icons
    document.querySelectorAll('.avatar-option i').forEach(icon => {
        icon.style.border = '2px solid transparent';
    });

    // Highlight the selected icon
    element.style.border = '2px solid #007bff';

    // Update the hidden input with the selected icon's class
    const selectedIconClass = element.getAttribute('data-icon-class');
    document.getElementById('selectedAvatarIcon').value = selectedIconClass;
}

function deleteProfileImage() {
    showConfirmModal(
        "Are you sure you want to delete your profile image?",
        function () {
            document.getElementById('deleteImageForm').submit();
        }
    );
}

function send_code_to_visitor(){
    const check_box = document.getElementById("visitorMessageCheckBox");
    if (check_box.checked) {
       var keytypelist = $("#keytypelist").val();
       var visiotr_key_html = `<div class="input-group mb-3">
                <input type="text" maxlength="14" oninput="formatPhoneNumber(this)" onpaste="handlePaste(event)" name="visitor_phone" id="visitor_message_phone" required class="form-control" title="Phone Number" placeholder="Enter phone number">
            </div>`;
       if(keytypelist == 2){
        $("#key_visitor_number_field").html(visiotr_key_html);
       }
       else{
        $("#key_visitor_number_field").html('');
       }
    } else {
      $("#key_visitor_number_field").html('');
    }
}

function send_code_to_vendor(){
    const check_box = document.getElementById("vendorMessageCheckBox");
    if (check_box.checked) {
        var keytypelist = $("#keytypelist1").val();
        var vendor_key_html = `<div class="input-group mb-3">
                <input type="text" name="vendor_phone" id="vendor_message_phone" maxlength="14" oninput="formatPhoneNumber(this)" required class="form-control" title="Phone Number" placeholder="Enter phone number">
            </div>`;
        if(keytypelist == 2){
            $("#key_vendor_number_field").html(vendor_key_html);
        }
        else{
            $("#key_vendor_number_field").html('');
        }
    } else {
      $("#key_vendor_number_field").html('');
    }
}

function showRefferalCode(){
    $.ajax({
      url: "/include/referrals/get_referrals.php",
      type: "post",
      data: { get_referral_code: 'yes' },
      success: function (response) {
        console.log(response);
        var data = JSON.parse(response);
        $("#ref_property_name").text(data.property_name);
        $("#ref_code").val(data.code);
        $("#ref_link").val(data.invite_link);
        $("#referral_modal").modal('show');   
      },
    });
}

function check_submit_invisible_key(){

}

function validateAndLimitInput(input) {
    input.value = input.value.replace(/\D/g, '');
    if (input.value.length > 5) {
        input.value = input.value.slice(0, 5);
    }
}

document.querySelectorAll('.toggle-password').forEach(icon => {
    icon.addEventListener('click', function () {
        const targetInput = document.querySelector(this.getAttribute('data-target'));
        if (targetInput.type === 'password') {
            targetInput.type = 'text';
            this.classList.remove('fa-eye');
            this.classList.add('fa-eye-slash');
        } else {
            targetInput.type = 'password';
            this.classList.remove('fa-eye-slash');
            this.classList.add('fa-eye');
        }
    });
});



// Prevent modal offclick from closing modals
$.fn.modal.Constructor.Default.backdrop = 'static';
$.fn.modal.Constructor.Default.keyboard = false;

function encryptData(data) {
  try {
    const secretKey = window.SECRET_KEY;
    const dataString = typeof data === "string" ? data : JSON.stringify(data);
    const encrypted = CryptoJS.AES.encrypt(dataString, secretKey).toString();
    return encrypted;
  } catch (error) {
    console.log("Error in encryptionL ",error);
    return "Error encountered during encryption";
  }
}

function formatDateTime(dateString) {
  let date = null;
  if(dateString.includes("Z") || dateString.includes("z"))date = new Date(dateString); 
  else date = new Date(dateString + "Z"); 
  return date.toLocaleString("en-US", {
    year: "numeric",
    month: "long",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
    hour12: true,
  });
}

async function redirect_to(url,isDoor=false){
    if(isDoor){
        await update_property_builder_tab_to_door({
            set_active_property_tab: true,
            active_tab: 1,
        })
    }
    window.location.href=url;
}


async function update_property_builder_tab_to_door(data) {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: "/include/property_builder/property_settings/property_settings_request.php",
            method: "POST",
            data,
            success: function (resp) {
                resolve(resp.data);
            },
            error: function (xhr, status, error) {
                if (xhr?.responseJSON?.error) reject(xhr?.responseJSON?.error);
                else reject(error);
            },
        });
    });
}

function showSuccessGlobalToastMessage(errorMessage) {
    document.getElementById("globalSuccessToastMessage").style.display = "block";
    document.getElementById("globalSuccessMessage").textContent = errorMessage;
    var toastEl = document.getElementById("global_success_Toast");
    var toast = new bootstrap.Toast(toastEl, {
      delay: 3000,
      autohide: true,
    });
    toast.show();
  
    setTimeout(() => {
        closeSucessGlobalToastMessage();
    }, 4000);
}
function closeSucessGlobalToastMessage() {
    const toastEl = document.getElementById("globalSuccessToastMessage");
    toastEl.style.display = "none";
}

function showErrorGlobalToastMessage(errorMessage) {
    document.getElementById("globalErrorToastMessage").style.display = "block";
    document.getElementById("globalErrorMessage").textContent = errorMessage;
    const toastEl = document.getElementById("global_error_Toast");
    const toast = new bootstrap.Toast(toastEl, {
      delay: 3000,
      autohide: false,
    });
    toast.show();
  
    setTimeout(() => {
        closeErrorGlobalToastMessage();
    }, 4000);
}

function closeErrorGlobalToastMessage() {
    const toastEl = document.getElementById("globalErrorToastMessage");
    toastEl.style.display = "none";
}

async function handle_change_addNewStreet() {
    const selectEle = document.getElementById("streetlist");
    if (selectEle.value === "add_new") {
        await update_property_builder_tab_to_door({
            set_active_property_tab: true,
            active_tab: 8,
        })
      window.location.href="/dashboard.php?tab=property_builder"
    }
}

async function parseJSONData(stringifyData) {
    try {
      return JSON.parse(stringifyData);
    } catch (error) {
      return stringifyData;
    }
}

function handleChangePropertyInModal() {
    const selectPropertyElement = document.querySelector("#selectPropertyInModal");
    if (selectPropertyElement) {
      const selectedProperty = selectPropertyElement.value;
      getupdatedimage(selectedProperty);
      const csrfTokenElement = document.querySelector('meta[name="csrf-token"]');
      if (!csrfTokenElement) {
        console.error("CSRF token meta tag is missing");
        return;
      }
      const csrfToken = csrfTokenElement.getAttribute("content");
      const xhr = new XMLHttpRequest();
      xhr.open("POST", "include/users/session_variable.php", true);
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
          if (xhr.status === 200) {
            console.log("Server response:", xhr.responseText);
            location.reload();
          } else {
            console.error("Request failed with status:", xhr.status);
          }
        }
      };
      xhr.send(
        `selectedProperty=${encodeURIComponent(
          selectedProperty
        )}&csrf_token=${encodeURIComponent(csrfToken)}`
      );
    }
  }
  
  function add_new_invisible_key(){
    var key_type = document.getElementById("keytypelist").value;
    // var visitor_door = document.getElementById("visitor_door").value;
    var is_valid = 0;
    var visitor_number = "";

    if(key_type == 1){
        visitor_number = document.getElementById("callerid_phone").value;
    }
    else if(key_type == 2){
        const check_box = document.getElementById("visitorMessageCheckBox");
        if (check_box.checked) {
            visitor_number = document.getElementById("visitor_message_phone").value;
        }
        else{
            is_valid = 1;
        }
    }
    else if(key_type == 4){
        visitor_number = document.getElementById("cidphone").value;
    }
    // if(visitor_door == ""){
    //     showErrorGlobalToastMessage("Please select a door");    
    // }
    if(is_valid == 0){
        if(visitor_number != ""){
            var chk_length = visitor_number.length;
            if(chk_length < 14){
                showErrorGlobalToastMessage("Please enter valid phone number");    
            }
            else{
                $("#invisibleKeyForm").submit();        
            }
        }
        else{
            showErrorGlobalToastMessage("Please enter phone number");
        }
    }
    else{
        $("#invisibleKeyForm").submit();
    }
    
}

function add_new_vendor_key(){
    var key_type = document.getElementById("keytypelist1").value;
    // var vendor_door = document.getElementById("vendor_door").value;
    var is_valid = 0;
    var visitor_number = "";
    if(key_type == 1){
        visitor_number = document.getElementById("vcallerid_phone").value;
    }
    else if(key_type == 2){
        const check_box = document.getElementById("vendorMessageCheckBox");
        if (check_box.checked) {
            visitor_number = document.getElementById("vendor_message_phone").value;
        }
        else{
            is_valid = 1;
        }
    }
    else if(key_type == 4){
        visitor_number = document.getElementById("vcidphone").value;
    }
    // if(vendor_door == ""){
    //     showErrorGlobalToastMessage("Please select a door");    
    // }
    if(is_valid == 0){
        if(visitor_number != ""){
            var chk_length = visitor_number.length;
            if(chk_length < 14){
                showErrorGlobalToastMessage("Please enter valid phone number");    
            }
            else{
                $("#vendorKeyForm").submit();        
            }
        }
        else{
            showErrorGlobalToastMessage("Please enter phone number");
        }
    }
    else{
        $("#vendorKeyForm").submit();
    }
    
}

async function asyncGetPreferencesRequestForView(data) {
    return new Promise((resolve, reject) => {
      $.ajax({
        url: "/include/preferences/set_preferences.php",
        type: "post",
        data,
        success: function (resp1) {
          resolve(resp1.data);
        },
        error: function (xhr, status, error) {
          console.log("error : ", error);
          reject(error);
        },
      });
    });
}

function onFileChange(event, file_id) {
  const file = event.target.files[0]; // Get the selected file
  if (file) {
    // Show preview
    const reader = new FileReader();
    reader.onload = function (e) {
      const image = document.getElementById(file_id);
      // Remove hidden class if preview container is hidden
      document.querySelector("." + file_id)?.classList.remove("showHide");
      image.src = e.target.result; // Set the preview
    };
    reader.readAsDataURL(file);
  } else {
    // Reset if no file selected
    const image = document.getElementById(file_id);
    image.src = "";
    document.querySelector("." + file_id)?.classList.add("showHide");
  }
}