Plugin Directory

Changeset 3424497


Ignore:
Timestamp:
12/21/2025 07:43:27 AM (3 months ago)
Author:
revechat
Message:

woocommerce related update

Location:
revechat/trunk
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • revechat/trunk/assets/js/scripts.js

    r2605953 r3424497  
    11jQuery.noConflict();
    2 (function($) {
    3 $(document).ready(function() {
    4     var baseUrl = 'https://app.revechat.com/';
    5     // var baseUrl = 'https://staging-dev.revechat.com:5443/dashboard/';
    6     var ajaxMessage = $('.ajax_message');
    7    
    8     var newAccountInput = $('#newAccountInput');
    9     var newAccountForm = $("#newAccountForm");
    10     var newAccountBtn = $("#new-account-submit");
    11     var newAccountID = newAccountForm.find('input[name=revechat_aid]');
    12    
    13     var fullName = newAccountForm.find('#fullName');
    14     var emailAddress = newAccountForm.find('#emailAddress');
    15     var password = newAccountForm.find('#password');
    16     var phoneTaker = newAccountForm.find('#phoneTaker');
    17     var phoneNo = newAccountForm.find('#phoneNo');
    18     var companyWebsite = newAccountForm.find('#companyWebsite');
    19     var selectedCountryData = null;
    20 
    21     var existingAccountInput = $('#existingAccountInput');
    22     var existingAccountForm = $("#existingAccountForm");
    23     var existingAccountBtn = $("#existingAccountBtn");
    24     var existingAccountID = existingAccountForm.find('input[name=revechat_aid]');
    25     var existingAccountEmail = existingAccountForm.find('#existingAccountEmail');
    26 
    27 
    28     var toggleForms = function ()
    29     {
    30         if ( newAccountInput.is(':checked') )
    31         {
    32             existingAccountForm.hide();
    33             newAccountForm.show();
    34         }
    35         else if (existingAccountInput.is(':checked'))
    36         {
    37             newAccountForm.hide();
    38             existingAccountForm.show();
    39         }
    40     };
    41     toggleForms();
    42     $('#revechat_chooser input').click(toggleForms);
    43 
    44     var signInValidationRules = {
    45 
    46         rules: {
    47             existingAccountEmail: {
    48                 required: true,
    49                 isValidEmail: true
    50             }
    51         },
    52 
    53         messages: {
    54             existingAccountEmail: {
    55                 required: "Please provide your business email address",
    56                 isValidEmail: "Please provide your real email address"
    57             }
    58         },
    59 
    60         submitHandler: function(form) {
    61             console.log(`newAccountID.val()`,newAccountID.val());
    62             console.log(`form`,form);
    63 
    64             // if (parseInt((newAccountID.val()) > 0))     
     2(function ($) {
     3    $(document).ready(function () {
     4        var baseUrl = 'https://app.revechat.com/';
     5        // var baseUrl = 'https://staging-dev.revechat.com:5443/dashboard/';
     6        var ajaxMessage = $('.ajax_message');
     7
     8        var newAccountInput = $('#newAccountInput');
     9        var newAccountForm = $("#newAccountForm");
     10        var newAccountBtn = $("#new-account-submit");
     11        var newAccountID = newAccountForm.find('input[name=revechat_aid]');
     12
     13        var fullName = newAccountForm.find('#fullName');
     14        var emailAddress = newAccountForm.find('#emailAddress');
     15        var password = newAccountForm.find('#password');
     16        var phoneTaker = newAccountForm.find('#phoneTaker');
     17        var phoneNo = newAccountForm.find('#phoneNo');
     18        var companyWebsite = newAccountForm.find('#companyWebsite');
     19        var selectedCountryData = null;
     20
     21        var existingAccountInput = $('#existingAccountInput');
     22        var existingAccountForm = $("#existingAccountForm");
     23        var existingAccountBtn = $("#existingAccountBtn");
     24        var existingAccountID = existingAccountForm.find('input[name=revechat_aid]');
     25        var existingAccountEmail = existingAccountForm.find('#existingAccountEmail');
     26
     27        var disconnectBtn = $('#revechat_disconnect_btn');
     28
     29        disconnectBtn.on('click', function (e) {
     30            if (!confirm('Are you sure you want to disconnect REVE Chat from your wordpress store?')) {
     31                e.preventDefault();
     32                return false;
     33            }
     34            fetch(ajaxurl, {
     35                method: "POST",
     36                headers: {
     37                    "Content-Type": "application/x-www-form-urlencoded"
     38                },
     39                body: "action=revechat_disconnect"
     40            })
     41                .then(res => res.json())
     42                .then(data => {
     43                    if (data.success) {
     44                        alert("Disconnected successfully.");
     45                        location.reload(); // refresh page
     46                    } else {
     47                        alert("Failed to disconnect.");
     48                    }
     49                });
     50        });
     51
     52        var toggleForms = function () {
     53            if (newAccountInput.is(':checked')) {
     54                existingAccountForm.hide();
     55                newAccountForm.show();
     56            }
     57            else if (existingAccountInput.is(':checked')) {
     58                newAccountForm.hide();
     59                existingAccountForm.show();
     60            }
     61        };
     62        toggleForms();
     63        $('#revechat_chooser input').click(toggleForms);
     64
     65        var signInValidationRules = {
     66
     67            rules: {
     68                existingAccountEmail: {
     69                    required: true,
     70                    isValidEmail: true
     71                }
     72            },
     73
     74            messages: {
     75                existingAccountEmail: {
     76                    required: "Please provide your business email address",
     77                    isValidEmail: "Please provide your real email address"
     78                }
     79            },
     80
     81            submitHandler: function (form) {
     82                console.log(`newAccountID.val()`, newAccountID.val());
     83                console.log(`form`, form);
     84
     85                // if (parseInt((newAccountID.val()) > 0))     
    6586                form.submit();
    66         }
    67     }
    68 
    69     var validationRules = {
    70 
    71         rules: {
    72             password: {
    73                 required: true,
    74                 minlength: 6,
    75                 maxlength: 12
    76             },
    77             fullName: {
    78                 required: true
    79             },
    80             emailAddress: {
    81                 required: true
    82             },
    83             phoneTaker: {
    84                 required: true,
    85                 phoneMinLength: 6,
    86                 maxlength: 12,
    87                 validatePhone: true
    88             },
    89             companyWebsite: {
    90                 required: true,
    91                 // excludeCommonSites: true,
    92                 validateURL: true,
    93             }
    94         },
    95 
    96         messages: {
    97 
    98             password: {
    99                 required: "The password length must be between 6 to 12 characters",
    100                 minlength: "The password length must be between 6 to 12 characters",
    101                 maxlength: "The password length must be between 6 to 12 characters"
    102             },
    103             fullName: {
    104                 required: "Please provide your name"
    105             },
    106             emailAddress: {
    107                 required: "Please provide your business email address"
    108             },
    109             phoneTaker: {
    110                 required: "The phone number length must be between 6 to 12 digits",
    111                 phoneMinLength: "The phone number length must be between 6 to 12 digits",
    112                 maxlength: "The phone number length must be between 6 to 12 digits",
    113                 validatePhone: "The phone number length must be between 6 to 12 digits"
    114             },
    115             companyWebsite: {
    116                 required: "Please enter the website, where REVE Chat will be integrated",
    117                 validateURL: "This is not a valid entry. Please enter the website, where REVE Chat will be integrated",
    118                 // excludeCommonSites: "This is not a valid entry. Please enter the website, where REVE Chat will be integrated",
    119             }
    120 
    121         },
    122 
    123         submitHandler: function(form) {
    124             console.log(`newAccountID.val()`,newAccountID.val());
    125             console.log(`form`,form);
    126 
    127             // if (parseInt((newAccountID.val()) > 0))     
     87            }
     88        }
     89
     90        var validationRules = {
     91
     92            rules: {
     93                password: {
     94                    required: true,
     95                    minlength: 6,
     96                    maxlength: 12
     97                },
     98                fullName: {
     99                    required: true
     100                },
     101                emailAddress: {
     102                    required: true
     103                },
     104                phoneTaker: {
     105                    required: true,
     106                    phoneMinLength: 6,
     107                    maxlength: 12,
     108                    validatePhone: true
     109                },
     110                companyWebsite: {
     111                    required: true,
     112                    // excludeCommonSites: true,
     113                    validateURL: true,
     114                }
     115            },
     116
     117            messages: {
     118
     119                password: {
     120                    required: "The password length must be between 6 to 12 characters",
     121                    minlength: "The password length must be between 6 to 12 characters",
     122                    maxlength: "The password length must be between 6 to 12 characters"
     123                },
     124                fullName: {
     125                    required: "Please provide your name"
     126                },
     127                emailAddress: {
     128                    required: "Please provide your business email address"
     129                },
     130                phoneTaker: {
     131                    required: "The phone number length must be between 6 to 12 digits",
     132                    phoneMinLength: "The phone number length must be between 6 to 12 digits",
     133                    maxlength: "The phone number length must be between 6 to 12 digits",
     134                    validatePhone: "The phone number length must be between 6 to 12 digits"
     135                },
     136                companyWebsite: {
     137                    required: "Please enter the website, where REVE Chat will be integrated",
     138                    validateURL: "This is not a valid entry. Please enter the website, where REVE Chat will be integrated",
     139                    // excludeCommonSites: "This is not a valid entry. Please enter the website, where REVE Chat will be integrated",
     140                }
     141
     142            },
     143
     144            submitHandler: function (form) {
     145                console.log(`newAccountID.val()`, newAccountID.val());
     146                console.log(`form`, form);
     147
     148                // if (parseInt((newAccountID.val()) > 0))     
    128149                form.submit();
    129         }
    130     }
    131 
    132     $("#eye_close").on("click", function() {
    133 
    134         password.attr('type', 'text');
    135         $("#eye_close").hide();
    136         $("#eye_open").show();
    137     });
    138 
    139     $("#eye_open").on("click", function() {
    140 
    141         password.attr('type', 'password');
    142         $("#eye_open").hide();
    143         $("#eye_close").show();
    144     });
    145    
    146    
    147 
    148     window.ExistingAccoutVerify = function (response) {
    149         console.log(`response`,response);
    150         if (response.error)
    151         {
    152             ajaxMessage.removeClass('wait').addClass('message alert').html('Incorrect REVE Chat login.');
    153             setTimeout(function () { ajaxMessage.slideUp().removeClass('wait message alert').html(''); }, 3000);
    154             existingAccountEmail.focus();
    155         }
    156         else
    157         {
    158             if( response.data.account_id ) {
    159 
    160                 existingAccountID.val(response.data.account_id);
    161                 existingAccountForm.submit();
    162 
    163             } else {
    164                 console.log(`ExistingAccoutVerify Response Error: `,response);
    165             }
    166         }
    167     }
    168 
    169     function existingAccountFormFunc()
    170     {
    171 
    172         var isValid = existingAccountForm.valid(signInValidationRules);
    173         console.log(`isValid`,isValid);
    174         // if (0) {
    175         if (isValid) {
    176             ajaxMessage.removeClass('message').addClass('wait').html('Please wait…').slideDown();
    177             var signInUrl = baseUrl +'license/adminId/'+existingAccountEmail.val()+'/?callback=window.ExistingAccoutVerify';
    178 
    179             $.ajax({
    180                 type: 'GET',
    181                 dataType: "text",
    182                 // dataType: "jsonp",
    183                 url: signInUrl,
    184                 // jsonpCallback: "window.ExistingAccoutVerify",
    185                 success: function(response) {
    186                     eval(response);
    187                 },
    188                 error: function(XMLHttpRequest, textStatus, errorThrown) {
    189                     ajaxMessage.removeClass('wait').addClass('message alert').html('Unable to Login. Please check internet connection.');
    190                     setTimeout(function () { ajaxMessage.slideUp().removeClass('wait message alert').html(''); }, 3000);
    191                 }
    192 
    193             }); // end of ajax saving.
    194         }
    195     }
    196     existingAccountBtn.click(existingAccountFormFunc);
    197 
    198 
    199     function newAccountFormFunc()
    200     {
    201         var isValid = newAccountForm.valid(validationRules);
    202         // if (0) {
    203         if (isValid) {
    204             ajaxMessage.removeClass('message').addClass('wait').html('Creating new account…').slideDown();
    205             var signUpUrl = baseUrl + 'revechat/cms/api/signup.do';
    206 
    207             $.ajax({
    208                 data: {
    209                     'firstname': fullName.val(),
    210                     'lastname':' ',
    211                     'mailAddr': emailAddress.val(),
    212                     'password': password.val(),
    213                     'phoneNo': phoneNo.val(),
    214                     'companyWebsite': companyWebsite.val(),
    215                     'utm_source':'cms', 'utm_content':'wordpress', 'referrer':'https://wordpress.org/'
    216                 },
    217                 type:'POST',
    218                 url:signUpUrl,
    219                 dataType: 'json',
    220                 cache:false,
    221                 beforeSend: function() { },
    222                 success: function(response) {
    223 
    224                     if(response.status == 'success')
    225                     {
    226                         if(response.account_id) {
    227                             newAccountID.val(response.account_id);
    228                             newAccountForm.submit();
    229                         }
    230                         else if( response.accountId) {
    231                             newAccountID.val(response.accountId);
    232                             newAccountForm.submit();
     150            }
     151        }
     152
     153        $("#eye_close").on("click", function () {
     154
     155            password.attr('type', 'text');
     156            $("#eye_close").hide();
     157            $("#eye_open").show();
     158        });
     159
     160        $("#eye_open").on("click", function () {
     161
     162            password.attr('type', 'password');
     163            $("#eye_open").hide();
     164            $("#eye_close").show();
     165        });
     166
     167
     168
     169        window.ExistingAccoutVerify = function (response) {
     170            console.log(`response`, response);
     171            if (response.error) {
     172                ajaxMessage.removeClass('wait').addClass('message alert').html('Incorrect REVE Chat login.');
     173                setTimeout(function () { ajaxMessage.slideUp().removeClass('wait message alert').html(''); }, 3000);
     174                existingAccountEmail.focus();
     175            }
     176            else {
     177                if (response.data.account_id) {
     178
     179                    existingAccountID.val(response.data.account_id);
     180                    existingAccountForm.submit();
     181
     182                } else {
     183                    console.log(`ExistingAccoutVerify Response Error: `, response);
     184                }
     185            }
     186        }
     187
     188        function existingAccountFormFunc() {
     189
     190            var isValid = existingAccountForm.valid(signInValidationRules);
     191            console.log(`isValid`, isValid);
     192            // if (0) {
     193            if (isValid) {
     194                ajaxMessage.removeClass('message').addClass('wait').html('Please wait…').slideDown();
     195                var signInUrl = baseUrl + 'license/adminId/' + existingAccountEmail.val() + '/?callback=window.ExistingAccoutVerify&scriptLoadNeeded=true&url=' + ReveChatData.homeUrl;
     196
     197                $.ajax({
     198                    type: 'GET',
     199                    dataType: "text",
     200                    // dataType: "jsonp",
     201                    url: signInUrl,
     202                    // jsonpCallback: "window.ExistingAccoutVerify",
     203                    success: function (response) {
     204                        eval(response);
     205                    },
     206                    error: function (XMLHttpRequest, textStatus, errorThrown) {
     207                        ajaxMessage.removeClass('wait').addClass('message alert').html('Unable to Login. Please check internet connection.');
     208                        setTimeout(function () { ajaxMessage.slideUp().removeClass('wait message alert').html(''); }, 3000);
     209                    }
     210
     211                }); // end of ajax saving.
     212            }
     213        }
     214        existingAccountBtn.click(existingAccountFormFunc);
     215
     216
     217        function newAccountFormFunc() {
     218            var isValid = newAccountForm.valid(validationRules);
     219            // if (0) {
     220            if (isValid) {
     221                ajaxMessage.removeClass('message').addClass('wait').html('Creating new account…').slideDown();
     222                var signUpUrl = baseUrl + 'revechat/cms/api/signup.do';
     223
     224                $.ajax({
     225                    data: {
     226                        'firstname': fullName.val(),
     227                        'lastname': ' ',
     228                        'mailAddr': emailAddress.val(),
     229                        'password': password.val(),
     230                        'phoneNo': phoneNo.val(),
     231                        'companyWebsite': companyWebsite.val(),
     232                        'utm_source': 'cms', 'utm_content': 'wordpress', 'referrer': 'https://wordpress.org/'
     233                    },
     234                    type: 'POST',
     235                    url: signUpUrl,
     236                    dataType: 'json',
     237                    cache: false,
     238                    beforeSend: function () { },
     239                    success: function (response) {
     240
     241                        if (response.status == 'success') {
     242                            if (response.account_id) {
     243                                newAccountID.val(response.account_id);
     244                                newAccountForm.submit();
     245                            }
     246                            else if (response.accountId) {
     247                                newAccountID.val(response.accountId);
     248                                newAccountForm.submit();
     249                            }
     250                            else {
     251                                response.message = 'Account Id missing Please contact with Revechat Adminstrator.';
     252                            }
     253                            ajaxMessage.removeClass('wait').addClass('message').html(response.message);
     254                            setTimeout(function () { ajaxMessage.slideUp().removeClass('wait message alert').html(''); }, 3000);
    233255                        }
    234256                        else {
    235                             response.message = 'Account Id missing Please contact with Revechat Adminstrator.';
     257                            ajaxMessage.removeClass('wait').addClass('message alert').html(response.message);
     258                            setTimeout(function () { ajaxMessage.slideUp().removeClass('wait message alert').html(''); }, 3000);
    236259                        }
    237                         ajaxMessage.removeClass('wait').addClass('message').html(response.message);
     260                    },
     261                    error: function (message) {
     262                        console.log(`message`, message);
     263                        ajaxMessage.removeClass('wait').addClass('message alert').html('Unable to Signup. Please check internet connection.');
    238264                        setTimeout(function () { ajaxMessage.slideUp().removeClass('wait message alert').html(''); }, 3000);
    239                     }
    240                     else {
    241                         ajaxMessage.removeClass('wait').addClass('message alert').html(response.message);
    242                         setTimeout(function () { ajaxMessage.slideUp().removeClass('wait message alert').html(''); }, 3000);
    243                     }
    244                 },
    245                 error: function (message) {
    246                     console.log(`message`,message);
    247                     ajaxMessage.removeClass('wait').addClass('message alert').html('Unable to Signup. Please check internet connection.');
    248                     setTimeout(function () { ajaxMessage.slideUp().removeClass('wait message alert').html(''); }, 3000);
    249                 }
    250             });
    251         }
    252     }
    253     newAccountBtn.click(newAccountFormFunc);
    254 
    255     function setCookie(cname, cvalue, exdays) {
    256         var d = new Date();
    257         d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    258         var expires = "expires=" + d.toUTCString();
    259         document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/";
    260     }
    261 
    262 
    263     phoneTaker.intlTelInput({
    264 
    265         initialCountry: "auto",
    266         separateDialCode: true,
    267         nationalMode: false,
    268         autoPlaceholder: true,
    269 
    270         customPlaceholder: function(selectedCountryPlaceholder, selectedCountryData) {
    271             return "For example: " + selectedCountryPlaceholder;
    272         },
    273 
    274         geoIpLookup: function(callback) {
    275             window.geoInfoCallback = function(data) {
    276 
    277                 var countryCode = data['result']['country_code'];
    278 
    279                 if (countryCode) {
    280                     countryCode = countryCode == "-" ? "us" : countryCode.toLowerCase();
    281                 } else {
    282                     countryCode = "us";
    283                 }
    284                 callback(countryCode);
    285                 setCookie("countryCode", countryCode, 30);
    286             }
    287             $.ajax({
    288                 url: "https://location.revechat.com:9090/",
    289                 type: "get",
    290                 async: true,
    291                 success: function(response) {
    292                     eval(response);
    293                 }
    294             });
    295         },
    296         utilsScript: "https://www.revechat.com/wp-content/themes/revechat/js/vendors/utils.js" // just for formatting/placeholders etc
    297     });
    298 
    299     phoneTaker.on("countrychange", function (e, countryData) {
    300         selectedCountryData = countryData;
    301         newAccountForm.validate(validationRules);
    302         // console.log(`selectedCountryData`,selectedCountryData);
    303     });
    304 
    305     phoneTaker.on("change", function(e) {
    306 
    307         var me= $(this);
    308         var currentValue = me.val();
    309         var regex = new RegExp("^[\+0-9\-\)\( ]+$");
    310         var phone_number =  phoneTaker.intlTelInput("getNumber");
    311         var isOK = regex.test(phone_number);
    312         // console.log(`isOK`,isOK);
    313         // console.log(`phone_number`,phone_number);
    314         // console.log(`currentValue`,currentValue);
    315 
    316         if(isOK) {
    317             phoneNo.val(phone_number);
    318         } else if ( selectedCountryData == null ) {
    319             phoneNo.val( currentValue );
    320         } else {
    321 
    322         }
    323 
    324     });
    325 
    326     phoneTaker.on("keypress", function(e) {
    327 
    328         var theEvent = e || window.event;
    329         var key = theEvent.keyCode || theEvent.which;
    330 
    331         if ((
    332             // < "0"  || > 9
    333             (key < 48 || key > 57)
    334             && !(
    335                 key == 8    // BACK_SPACE
    336                 || key == 32  //' '
    337                 || key == 45  //'-'
    338                 || key == 41  //')'
    339                 || key == 40  //'('
    340                 // || key == 9  //TAB
    341                 // || key == 13  // ''
    342                 // ||  key == 37 // "%"
    343                 // || key == 39 // "'"
    344                 // || key == 46 "."
     265                    }
     266                });
     267            }
     268        }
     269        newAccountBtn.click(newAccountFormFunc);
     270
     271        function setCookie(cname, cvalue, exdays) {
     272            var d = new Date();
     273            d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
     274            var expires = "expires=" + d.toUTCString();
     275            document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/";
     276        }
     277
     278
     279        phoneTaker.intlTelInput({
     280
     281            initialCountry: "auto",
     282            separateDialCode: true,
     283            nationalMode: false,
     284            autoPlaceholder: true,
     285
     286            customPlaceholder: function (selectedCountryPlaceholder, selectedCountryData) {
     287                return "For example: " + selectedCountryPlaceholder;
     288            },
     289
     290            geoIpLookup: function (callback) {
     291                window.geoInfoCallback = function (data) {
     292
     293                    var countryCode = data['result']['country_code'];
     294
     295                    if (countryCode) {
     296                        countryCode = countryCode == "-" ? "us" : countryCode.toLowerCase();
     297                    } else {
     298                        countryCode = "us";
     299                    }
     300                    callback(countryCode);
     301                    setCookie("countryCode", countryCode, 30);
     302                }
     303                $.ajax({
     304                    url: "https://location.revechat.com:9090/",
     305                    type: "get",
     306                    async: true,
     307                    success: function (response) {
     308                        eval(response);
     309                    }
     310                });
     311            },
     312            utilsScript: "https://www.revechat.com/wp-content/themes/revechat/js/vendors/utils.js" // just for formatting/placeholders etc
     313        });
     314
     315        phoneTaker.on("countrychange", function (e, countryData) {
     316            selectedCountryData = countryData;
     317            newAccountForm.validate(validationRules);
     318            // console.log(`selectedCountryData`,selectedCountryData);
     319        });
     320
     321        phoneTaker.on("change", function (e) {
     322
     323            var me = $(this);
     324            var currentValue = me.val();
     325            var regex = new RegExp("^[\+0-9\-\)\( ]+$");
     326            var phone_number = phoneTaker.intlTelInput("getNumber");
     327            var isOK = regex.test(phone_number);
     328            // console.log(`isOK`,isOK);
     329            // console.log(`phone_number`,phone_number);
     330            // console.log(`currentValue`,currentValue);
     331
     332            if (isOK) {
     333                phoneNo.val(phone_number);
     334            } else if (selectedCountryData == null) {
     335                phoneNo.val(currentValue);
     336            } else {
     337
     338            }
     339
     340        });
     341
     342        phoneTaker.on("keypress", function (e) {
     343
     344            var theEvent = e || window.event;
     345            var key = theEvent.keyCode || theEvent.which;
     346
     347            if ((
     348                // < "0"  || > 9
     349                (key < 48 || key > 57)
     350                && !(
     351                    key == 8    // BACK_SPACE
     352                    || key == 32  //' '
     353                    || key == 45  //'-'
     354                    || key == 41  //')'
     355                    || key == 40  //'('
     356                    // || key == 9  //TAB
     357                    // || key == 13  // ''
     358                    // ||  key == 37 // "%"
     359                    // || key == 39 // "'"
     360                    // || key == 46 "."
    345361                )
    346362            )) {
    347             theEvent.returnValue = false;
    348             if (theEvent.preventDefault) theEvent.preventDefault();
    349         }
    350     });
    351 
    352 
    353     newAccountForm.validate(validationRules);
    354     existingAccountForm.validate(signInValidationRules);
    355 
    356 
    357 
    358     $.validator.addMethod('validatePhone', function() {
    359         // this is the inteligent validation check provided by the core initTelInput script
    360         // if ( $REVEChatSignup.$_phoneNoInputFieldSelector.intlTelInput("isValidNumber")){
    361         //  return true;
    362         // }
    363         // else{
    364         //  return false;
    365         // }
    366 
    367         var phone_number = phoneTaker.val();
    368         var regex = new RegExp("^[0-9\-\)\( ]+$");
    369         var isNumber = regex.test(phone_number);
    370         // console.log(`isNumber`,isNumber);
    371         return isNumber;
    372 
    373     }, "Please Enter a valid phone number.");
    374 
    375     $.validator.addMethod('phoneMinLength', function(inputValue, selectorDom, settingValue) {
    376         // console.log(`inputValue`,inputValue);
    377         // console.log(`selectorDom`,selectorDom);
    378         // console.log(`settingValue`,settingValue);
    379 
    380         var realVal = inputValue.replace(/[ \-+\(\)]/g, '');
    381         // console.log(`realVal.length`,realVal.length);
    382 
    383         if (realVal.length >= settingValue ){
    384             return true;
    385         }
    386         else{
    387             return false;
    388         }
    389 
    390     }, "Please enter at least 6 digits without country code");
    391 
    392     $.validator.addMethod('validateURL', function(inputValue, selectorDom, settingValue) {
    393 
    394         var urlregex = new RegExp(/^(?![\.\-\_\+])(((https?1?2?\:\/\/)?www\.)|((https?1?2?\:\/\/)?(www\.))|((https?1?2?\:\/\/)))?[0-9A-Za-z-]+\..+$/, 'i');
    395         // var urlregex = new RegExp("^(((https?\:\/\/)?www\.)|((https?\:\/\/)?(www\.)))([0-9A-Za-z]+\..+)");
    396         var ret = urlregex.test(inputValue);
    397         var arr = inputValue.split('.');
    398 
    399         if( arr[ arr.length-1 ] == ''){
    400             return false
    401         }
    402 
    403         if((arr[0].substr(arr[0].length - 3)).toLowerCase() == 'www' && arr.length<3)
    404             return false       
    405        
    406         if(arr.length>4)
    407             return false;
    408 
    409         if(arr[ arr.length-1 ].length > 6)
    410             return false;
    411        
    412         return ret;
    413 
    414     }, "Please enter a valid URL.");
    415 
    416     $.validator.addMethod('excludeCommonSites', function(inputValue, selectorDom, settingValue) {
    417 
    418         var urlregex = new RegExp(/^.*?((hotmail)|(facebook)|(yahoo)|(google)|(revechat)|(fb\.com)|(twitter)|(gmail)).*?$/, 'i');
    419         // var urlregex = new RegExp("^(((https?\:\/\/)?www\.)|((https?\:\/\/)?(www\.)))([0-9A-Za-z]+\..+)");
    420         var ret = urlregex.test(inputValue);
    421 
    422         return !ret;
    423 
    424     }, "Please enter a valid URL.");
    425 
    426     $.validator.addMethod('isValidEmail', function(inputValue, selectorDom, settingValue) {
    427 
    428         var urlregex = new RegExp(/^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/, 'i');
    429         // var urlregex = new RegExp("^(((https?\:\/\/)?www\.)|((https?\:\/\/)?(www\.)))([0-9A-Za-z]+\..+)");
    430         var ret = urlregex.test(inputValue);
    431 
    432         return ret;
    433 
    434     }, "Please enter a real email.");
    435 
    436     function ShowToast(msg,msg_type,snackbar_wrapper, delay, calback_func, calback_params){
    437         msg_type = msg_type || 'spf-success';
    438         delay = delay || 3000;
    439         var auto_snackbar = false;
    440         if( $("#snackbar").length > 0 )
    441             $("#snackbar").remove();
    442         if( !snackbar_wrapper ) {
    443             $("body").append(`<div id="snackbar"><div class="overlay"></div><span class="data"></span></div>`);
    444             snackbar_wrapper = $("#snackbar");
    445             auto_snackbar = true;
    446         }
    447 
    448         if (snackbar_wrapper.data("active")) { return; }
    449         snackbar_wrapper.slideDown().addClass(msg_type).data("active", true).find('.data').html(msg);
    450 
    451         setTimeout(function() {
    452             snackbar_wrapper.slideUp().removeClass(msg_type).data("active", false).find('.data').html('');
    453             if( auto_snackbar ) {
    454                 snackbar_wrapper.remove();
    455                 auto_snackbar = false;
    456             }
    457 
    458             if(Array.isArray(calback_func)) {
    459                 if( typeof calback_func[1] == "function" ) {
    460                     // callable_func     obj_for_bind     params_for_callable_func
    461                     calback_func[1].call(calback_func[0], calback_params);
    462                 }
    463             } else if(typeof calback_func == "function") {
    464                 calback_func(calback_params);
    465             }
    466         }, delay);           
    467     }
    468 
    469 
    470 });
     363                theEvent.returnValue = false;
     364                if (theEvent.preventDefault) theEvent.preventDefault();
     365            }
     366        });
     367
     368
     369        newAccountForm.validate(validationRules);
     370        existingAccountForm.validate(signInValidationRules);
     371
     372
     373
     374        $.validator.addMethod('validatePhone', function () {
     375            // this is the inteligent validation check provided by the core initTelInput script
     376            // if ( $REVEChatSignup.$_phoneNoInputFieldSelector.intlTelInput("isValidNumber")){
     377            //  return true;
     378            // }
     379            // else{
     380            //  return false;
     381            // }
     382
     383            var phone_number = phoneTaker.val();
     384            var regex = new RegExp("^[0-9\-\)\( ]+$");
     385            var isNumber = regex.test(phone_number);
     386            // console.log(`isNumber`,isNumber);
     387            return isNumber;
     388
     389        }, "Please Enter a valid phone number.");
     390
     391        $.validator.addMethod('phoneMinLength', function (inputValue, selectorDom, settingValue) {
     392            // console.log(`inputValue`,inputValue);
     393            // console.log(`selectorDom`,selectorDom);
     394            // console.log(`settingValue`,settingValue);
     395
     396            var realVal = inputValue.replace(/[ \-+\(\)]/g, '');
     397            // console.log(`realVal.length`,realVal.length);
     398
     399            if (realVal.length >= settingValue) {
     400                return true;
     401            }
     402            else {
     403                return false;
     404            }
     405
     406        }, "Please enter at least 6 digits without country code");
     407
     408        $.validator.addMethod('validateURL', function (inputValue, selectorDom, settingValue) {
     409
     410            var urlregex = new RegExp(/^(?![\.\-\_\+])(((https?1?2?\:\/\/)?www\.)|((https?1?2?\:\/\/)?(www\.))|((https?1?2?\:\/\/)))?[0-9A-Za-z-]+\..+$/, 'i');
     411            // var urlregex = new RegExp("^(((https?\:\/\/)?www\.)|((https?\:\/\/)?(www\.)))([0-9A-Za-z]+\..+)");
     412            var ret = urlregex.test(inputValue);
     413            var arr = inputValue.split('.');
     414
     415            if (arr[arr.length - 1] == '') {
     416                return false
     417            }
     418
     419            if ((arr[0].substr(arr[0].length - 3)).toLowerCase() == 'www' && arr.length < 3)
     420                return false
     421
     422            if (arr.length > 4)
     423                return false;
     424
     425            if (arr[arr.length - 1].length > 6)
     426                return false;
     427
     428            return ret;
     429
     430        }, "Please enter a valid URL.");
     431
     432        $.validator.addMethod('excludeCommonSites', function (inputValue, selectorDom, settingValue) {
     433
     434            var urlregex = new RegExp(/^.*?((hotmail)|(facebook)|(yahoo)|(google)|(revechat)|(fb\.com)|(twitter)|(gmail)).*?$/, 'i');
     435            // var urlregex = new RegExp("^(((https?\:\/\/)?www\.)|((https?\:\/\/)?(www\.)))([0-9A-Za-z]+\..+)");
     436            var ret = urlregex.test(inputValue);
     437
     438            return !ret;
     439
     440        }, "Please enter a valid URL.");
     441
     442        $.validator.addMethod('isValidEmail', function (inputValue, selectorDom, settingValue) {
     443
     444            var urlregex = new RegExp(/^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/, 'i');
     445            // var urlregex = new RegExp("^(((https?\:\/\/)?www\.)|((https?\:\/\/)?(www\.)))([0-9A-Za-z]+\..+)");
     446            var ret = urlregex.test(inputValue);
     447
     448            return ret;
     449
     450        }, "Please enter a real email.");
     451
     452        function ShowToast(msg, msg_type, snackbar_wrapper, delay, calback_func, calback_params) {
     453            msg_type = msg_type || 'spf-success';
     454            delay = delay || 3000;
     455            var auto_snackbar = false;
     456            if ($("#snackbar").length > 0)
     457                $("#snackbar").remove();
     458            if (!snackbar_wrapper) {
     459                $("body").append(`<div id="snackbar"><div class="overlay"></div><span class="data"></span></div>`);
     460                snackbar_wrapper = $("#snackbar");
     461                auto_snackbar = true;
     462            }
     463
     464            if (snackbar_wrapper.data("active")) { return; }
     465            snackbar_wrapper.slideDown().addClass(msg_type).data("active", true).find('.data').html(msg);
     466
     467            setTimeout(function () {
     468                snackbar_wrapper.slideUp().removeClass(msg_type).data("active", false).find('.data').html('');
     469                if (auto_snackbar) {
     470                    snackbar_wrapper.remove();
     471                    auto_snackbar = false;
     472                }
     473
     474                if (Array.isArray(calback_func)) {
     475                    if (typeof calback_func[1] == "function") {
     476                        // callable_func     obj_for_bind     params_for_callable_func
     477                        calback_func[1].call(calback_func[0], calback_params);
     478                    }
     479                } else if (typeof calback_func == "function") {
     480                    calback_func(calback_params);
     481                }
     482            }, delay);
     483        }
     484
     485
     486    });
    471487})(jQuery);
  • revechat/trunk/assets/js/woocommerceCart.js

    r3398671 r3424497  
    1919   
    2020   
    21     var cartContents = fetch("/wp-json/revechat/v1/cart",
     21    var cartContents = fetch(revechatSettings.home_url +"/wp-json/revechat/v1/cart",
    2222    {
    2323        method: "GET",
  • revechat/trunk/readme.txt

    r3408794 r3424497  
    66Tested up to: 6.8.2
    77Requires PHP: 7.0
    8 Stable tag: 6.4.0
     8Stable tag: 6.4.1
    99License: GPLv2 or later
    1010License URI: https://www.gnu.org/licenses/gpl-2.0.html
  • revechat/trunk/revechat.php

    r3408794 r3424497  
    33Plugin Name: REVE Chat - WP Live Chat Support plugin
    44Description: REVE Chat is a powerful and intuitive real-time customer engagement software. As a customer support software, REVE Chat puts a live person on your website to personally guide and help your visitors, while they go through the various sections of your digital display. This live chat service helps them to get the most out of your web presence, while allowing you to understand their diverse needs on a one-to-one basis. REVE Chat is easy to install and use.
    5 Version: 6.4.0
     5Version: 6.4.1
    66Author: REVE Chat
    77Author URI: www.revechat.com
     
    5050        add_action('admin_enqueue_scripts',array($this,'admin_scripts'));
    5151       
    52         if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
    53             add_action('wp_enqueue_scripts', [$this, 'loadCartScript']);
    54         }
    55 
     52        // if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
     53        //     add_action('wp_enqueue_scripts', [$this, 'loadCartScript']);
     54        // }
     55        add_action('wp_enqueue_scripts', [$this, 'loadCartScript']);
    5656
    5757        // shopping cart api
     
    5959           
    6060            register_rest_route( 'revechat/v1', '/cart', array(
    61               'methods' => 'GET',
    62               'callback' => array($this,'getCartInfo'),
     61                'methods' => 'GET',
     62                'callback' => array($this,'getCartInfo'),
    6363            ) );
    64            
    65            
    66           });
    67          
    68      
    69         add_action('plugins_loaded', function() {
    70             load_plugin_textdomain('revechat', false, dirname(plugin_basename(__FILE__)) . '/languages');
     64       
    7165        });
    72 
    73        
    74    
    75         } // END public function __construct
     66       
     67
     68        add_action('template_redirect', function () {
     69            if (!isset($_GET['add-multiple-to-cart'])) return;
     70
     71            if (!function_exists('WC')) return;
     72
     73            // Load cart if not exists
     74            if (!WC()->cart) wc_load_cart();
     75
     76            // Ensure WooCommerce session is initialized
     77            if (WC()->session && !WC()->session->has_session()) {
     78                WC()->session->set_customer_session_cookie(true);
     79                WC()->session->init();
     80            }
     81
     82            $items = explode(',', sanitize_text_field($_GET['add-multiple-to-cart']));
     83            WC()->cart->empty_cart();
     84
     85            foreach ($items as $item) {
     86                list($product_id, $quantity) = array_pad(explode(':', $item), 2, 1);
     87
     88                $added = WC()->cart->add_to_cart(intval($product_id), intval($quantity));
     89            }
     90
     91            // ✅ Apply coupon if provided
     92            if (isset($_GET['coupon']) && !empty($_GET['coupon'])) {
     93                $coupon_code = sanitize_text_field($_GET['coupon']);
     94                $coupon_result = WC()->cart->apply_coupon($coupon_code);
     95
     96                if (is_wp_error($coupon_result)) {
     97                    error_log('[DEBUG] Coupon error: ' . $coupon_result->get_error_message());
     98                } else {
     99                    error_log('[DEBUG] Coupon applied successfully: ' . $coupon_code);
     100                }
     101            }
     102
     103            // Make sure totals and cookies are set
     104            WC()->cart->calculate_totals();
     105            WC()->cart->maybe_set_cart_cookies();
     106
     107            wp_safe_redirect(wc_get_checkout_url());
     108            exit;
     109        });
     110
     111        add_filter('woocommerce_rest_prepare_product_object', function($response, $object) {
     112            $response->data['thumbnail_id'] = get_post_thumbnail_id($object->get_id());
     113            return $response;
     114        }, 10, 2);
     115
     116        add_action('wp_ajax_revechat_disconnect', 'revechat_disconnect_handler');
     117
     118        function revechat_disconnect_handler() {
     119            // Same code as your deactivate function
     120            $accountId = get_option('revechat_aid', '');
     121            $storeUrl = get_option("revechat_wc_storeUrl", '');
     122
     123            $api_url = 'https://app.revechat.com/rest/v1/cms/remove-site';
     124
     125            $body = [
     126                'storeUrl' => $storeUrl,
     127                'accountId' => $accountId,
     128                'platform' => 'WOOCOMMERCE',
     129                'event' => 'manual_disconnect',
     130            ];
     131
     132            wp_remote_post($api_url, [
     133                'method'      => 'POST',
     134                'timeout'     => 10,
     135                'blocking'    => true,
     136                'headers'     => [ 'Content-Type' => 'application/json' ],
     137                'body'        => json_encode($body),
     138            ]);
     139
     140            // Remove options
     141            delete_option('revechat_aid');
     142
     143            wp_send_json_success([
     144                'message' => 'Disconnected successfully'
     145            ]);
     146        }
     147
     148    }
     149 // END public function __construct
    76150
    77151     /**
     
    140214        $cartPayload = array(
    141215              "cartId" => "",
    142               "shop" => (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]",
     216              "shop" => home_url(),
    143217              "customer" => $customer,
    144218              "platform" => $this->getPlatform(),
     
    181255    {
    182256        $accountId = get_option('revechat_aid' , '');
     257        $storeUrl = str_replace('/', '_', rtrim(preg_replace('#^https?://#', '', home_url()), '/'));
     258       
    183259       
    184260        if( (isset($accountId) && !empty($accountId))  ) {
    185261
    186             $script = "<script type='text/javascript'>";
    187             $script .= 'window.$_REVECHAT_API || (function(d, w) { var r = $_REVECHAT_API = function(c) {r._.push(c);}; w.__revechat_account=\''.$accountId.'\';w.__revechat_version=2;
    188                     r._= []; var rc = d.createElement(\'script\'); rc.type = \'text/javascript\'; rc.async = true; rc.setAttribute(\'charset\', \'utf-8\');
    189                     rc.src = (\'https:\' == document.location.protocol ? \'https://\' : \'http://\') + \'static.revechat.com/widget/scripts/new-livechat.js?\'+new Date().getTime();
    190                     var s = d.getElementsByTagName(\'script\')[0]; s.parentNode.insertBefore(rc, s);
    191                     })(document, window);';
    192 
    193             $script .='</script>';
     262            // $script = "<script type='text/javascript'>
     263            //     var urlParams = new URLSearchParams(window.location.search);
     264            //     var widgetId = urlParams.get('widgetId');
     265
     266            //     window.\$_REVECHAT_API || (function(d, w) {
     267            //         var r = \$_REVECHAT_API = function(c) { r._.push(c); };
     268            //         w.__revechat_account = '{$accountId}';
     269            //         w.__revechat_version = 2;
     270
     271            //         if (widgetId) w.__revechat_widget_id = widgetId;
     272
     273            //         r._ = [];
     274            //         var rc = d.createElement('script');
     275            //         rc.type = 'text/javascript';
     276            //         rc.async = true;
     277            //         rc.setAttribute('charset', 'utf-8');
     278            //         rc.src = (document.location.protocol === 'https:' ? 'https://' : 'http://') +
     279            //                 'staging-static.revechat.com/client_2/scripts/minify/new-livechat.js?' + new Date().getTime();
     280
     281            //         var s = d.getElementsByTagName('script')[0];
     282            //         s.parentNode.insertBefore(rc, s);
     283            //     })(document, window);
     284
     285            //     \$(function() {
     286            //         \$_REVECHAT_API(function() {
     287            //             try {
     288            //                 window.frames['reve-chat-widget-holder']
     289            //                     .document.getElementById('reve-chat-widget-header')
     290            //                     .addEventListener('click', function() {
     291            //                         \$_REVECHAT_Analytics.addClientVisitInfo('/chat-button');
     292            //                     });
     293            //             } catch(e) {}
     294
     295            //             try {
     296            //                 window.frames['reve-chat-widget-holder']
     297            //                     .document.getElementById('reve-chat-widget-body')
     298            //                     .addEventListener('click', function() {
     299            //                         \$_REVECHAT_Analytics.addClientVisitInfo('/client-chat-window');
     300            //                     });
     301            //             } catch(e) {}
     302            //         });
     303            //     });
     304            // </script>";
     305
     306            // $script = "<script type='text/javascript'>window.$_REVECHAT_API || (function(d, w) { var r = $_REVECHAT_API = function(c) {r._.push(c);}; w.__revechat_account='10377411';w.__revechat_version=2;
     307            //         r._= []; var rc = d.createElement('script'); rc.type = 'text/javascript'; rc.async = true; rc.setAttribute('charset', 'utf-8');
     308            //         rc.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'static.revechat.com/widget/scripts/new-livechat.js?'+new Date().getTime();
     309            //         var s = d.getElementsByTagName('script')[0]; s.parentNode.insertBefore(rc, s);
     310            //         })(document, window);</script>";
     311
     312            $version = time();
     313            $script = "<script src='https://preview.revechat.com/shopify/{$accountId}_{$storeUrl}_WORDPRESS.js?v={$version}'></script>";
     314
    194315           
    195316           
     
    247368                  'consumerKey' => $_POST["revechat_wc_consumerKey"],
    248369                  'consumerSecret' => $_POST["revechat_wc_consumerSecret"],
    249                   'shopUrl'   => "$_SERVER[HTTP_HOST]",
     370                  'shopUrl'   => str_replace('/', '_', rtrim(preg_replace('#^https?://#', '', home_url()), '/')),
    250371                  'adminUrl' => admin_url()
    251372                )
     
    292413              update_option( "revechat_wc_consumerSecret" , $_POST["revechat_wc_consumerSecret"]  );
    293414              update_option('revechat_wc_aid', get_option( $accountId ));
     415              update_option( "revechat_wc_storeUrl", str_replace('/', '_', rtrim(preg_replace('#^https?://#', '', home_url()), '/')));
    294416            }
    295417           
     
    347469                    <input type="hidden" name="revechat_aid" value="0">
    348470                   <!-- <p><small>Something went wrong? <input type="submit" style="background: transparent; border: 0; text-decoration: underline;text-transform: lowercase; font-size: 10px; cursor: pointer;" value="Disconnect" name="revechat_remove" id="edit-submit"></small></p>  -->
    349                     <p><small><?php _e( 'Something went wrong?', 'revechat' ); ?> <input type="submit" style="background: transparent; border: 0; text-decoration: underline;text-transform: lowercase; font-size: 10px; cursor: pointer;" value="<?php _e( 'Disconnect', 'revechat' ); ?>" name="revechat_remove" id="edit-submit"></small></p>
     471                    <p><small><?php _e( 'Something went wrong?', 'revechat' ); ?> <input type="submit" style="background: transparent; border: 0; text-decoration: underline;text-transform: lowercase; font-size: 10px; cursor: pointer;" value="<?php _e( 'Disconnect', 'revechat' ); ?>" name="revechat_remove" id="revechat_disconnect_btn"></small></p>
    350472                </div>
    351473            </form>
     
    490612    }
    491613
     614    public static function my_plugin_on_deactivate() {
     615        // Your logic when plugin is deactivated
     616        $accountId = get_option('revechat_aid' , '');
     617        $storeUrl = get_option("revechat_wc_storeUrl", '');
     618
     619        // Example: send request to your external server
     620        $api_url = 'https://app.revechat.com/rest/v1/cms/remove-site';
     621
     622        $body = [
     623            'storeUrl' => $storeUrl,
     624            'accountId' => $accountId,
     625            'platform' => 'WOOCOMMERCE',
     626            'event' => 'plugin_deactivated',
     627        ];
     628
     629        wp_remote_post($api_url, [
     630            'method'      => 'POST',
     631            'timeout'     => 10,
     632            'blocking'    => true,  // true = wait for response before finishing deactivation
     633            'headers'     => [ 'Content-Type' => 'application/json' ],
     634            'body'        => json_encode($body),
     635        ]);
     636        delete_option('revechat_aid');
     637    }
     638
    492639
    493640    /**
     
    496643     */
    497644    public function admin_scripts(){
     645
    498646
    499647        wp_enqueue_script( 'jquery');
     
    504652        wp_enqueue_script( 'intlTelInput', plugin_dir_url( __FILE__ ) . 'assets/js/intlTelInput.min.js', array('jquery') );
    505653        wp_enqueue_script( 'revechat_scripts', plugin_dir_url( __FILE__ ) . 'assets/js/scripts.js', array('jquery','jquery-validation','intlTelInput') );
    506 
     654        wp_localize_script('revechat_scripts', 'ReveChatData', array(
     655            'homeUrl' => str_replace('/', '_', rtrim(preg_replace('#^https?://#', '', home_url()), '/')),
     656            'baseUrl' => site_url(),   // if you need baseUrl as well
     657        ));
    507658    }
    508659
     
    513664    public function loadCartScript()
    514665    {
     666        // Check if WooCommerce is active.
     667        if ( ! class_exists( 'WooCommerce' ) ) {
     668            return;
     669        }
    515670        // Add JS.
    516         wp_enqueue_script('revechat', plugin_dir_url(__FILE__) . 'assets/js/woocommerceCart.js?ver='.round(microtime(true)*1000), ['jquery'], NULL, TRUE);
     671        wp_enqueue_script('revechat', plugin_dir_url(__FILE__) . 'assets/js/woocommerceCart.js?ver='.round(microtime(true)*1000), array(), NULL, true);
     672       
    517673        // Pass nonce to JS.
    518674        wp_localize_script('revechat', 'revechatSettings', [
    519675          'nonce' => wp_create_nonce('wp_rest'),
     676          'home_url' => home_url()
    520677        ]);
    521       }
     678    }
    522679
    523680    /**
     
    547704* Register the deactivation hook.
    548705*/
    549 register_deactivation_hook( __FILE__, array( 'WP_Plugin_Revechat', 'deactivate' ) );
     706register_deactivation_hook( __FILE__, array( 'WP_Plugin_Revechat', 'my_plugin_on_deactivate' ) );
    550707
    551708function revechat_activation_redirect( $plugin ) {
Note: See TracChangeset for help on using the changeset viewer.