<?php
/**
  * Ahead WebSoft Technologies Pvt Ltd.
  * @copyright  Copyright 2006-2026 Ahead WebSoft Technologies Pvt Ltd.
  * @license    https://www.socialengine.com/policies
*/
?>
<script src="https://www.gstatic.com/firebasejs/9.0.2/firebase-app-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.0.2/firebase-messaging-compat.js"></script>

<style>
  #iframe_browserpush_notification{display:none;}
</style>

<link rel="manifest" href="/manifest.json">

<script type="application/javascript">
  const firebaseConfig = <?php echo $this->server_key; ?>;
  firebase.initializeApp(firebaseConfig);

  function checkBrowser() {
    var status = false;
    if (navigator.userAgent.search("Chrome") >= 0 && navigator.userAgent.search("OPR") < 0){
      // For some reason in the browser identification Chrome contains the word "Safari" so when detecting for Safari you need to include Not Chrome
      var position = navigator.userAgent.search("Chrome") + 7;
      var end = navigator.userAgent.search(" Safari");
      var version = navigator.userAgent.substring(position,end);
      if(version.search('.') >= 0){
        version = version.split('.');
        version = version[0];
      }
      var BrowserName = 'Chrome';
      if(version >= 42)
        status = true;
    } else if (navigator.userAgent.search("Firefox") >= 0) {
      var position = navigator.userAgent.search("Firefox") + 8;
      var version = navigator.userAgent.substring(position);
      if(version.search('.') >= 0){
        version = version.split('.');
        version = version[0];
      }
      var BrowserName = 'Firefox';
      if(version >= 44)
        status = true;
    } else if (navigator.userAgent.search("OPR") >= 0) {
      var position = navigator.userAgent.search("Version") + 8;
      var version = navigator.userAgent.substring(position);
      if(version.search('.') >= 0){
        version = version.split('.');
        version = version[0];
      }
      var BrowserName = 'Opera';
      if(version >= 42)
        status = true;
    } else {
      return ['','',status];  
    }
    return [BrowserName,version,status];
  }

  var browserDays = '<?php echo Engine_Api::_()->getApi('settings', 'core')->getSetting('browserpush.days', 5); ?>';

  var browser_ispopup=getCookieBrowserPush('browser_ispopup');

  en4.core.runonce.add(function(){
    if (Notification.permission === "granted") {
      //scriptJquery('#browserpush_tip').hide();
      if(scriptJquery('#subscribe_browertip')) {
        scriptJquery('#subscribe_browertip').html('<?php echo $this->translate("Click to Unsubscribe"); ?>');
      }
    } else {
      scriptJquery('#browserpush_tip').show();
      if(scriptJquery('#browsepush_browser_permission_container'))
      scriptJquery('#browsepush_browser_permission_container').hide();
      if(scriptJquery('#browsepush_browser_permission_box'))
      scriptJquery('#browsepush_browser_permission_box').hide();
    }
    if(browser_ispopup != '' && browserDays == '0') {
      setCookie('browser_ispopup','',0);
    }
    if(browser_ispopup != '') {
      scriptJquery('#browserpush_tip').hide();
    }
  });

  const messaging = firebase.messaging();

  // Callback fired if Instance ID token is updated.

  // messaging.onTokenRefresh(function() {
  //   var status = 2;
  //   messageNotification(status,'*');
  // });

  messaging.onMessage(function(payload) {

    var payload = payload.data;
    
    messaging.getToken().then(function (currentToken) {
      if (currentToken) {
        {
        //console.log(payload, currentToken);
        scriptJquery.post(en4.core.baseUrl+'browserpush/index/notifications/',{scheduled_id:payload.scheduled_id,token:currentToken,param:'1'},function(result){
          if(result) {
            //console.log('User Subscribed Successfully');  
          } else {
            //console.log('Error While Subscribing User'); 
          }
        });  
        }
      }
    }).then(function () {
    }).catch(function (err) {
      console.log(err);
    });
    
    const notificationTitle = payload.title;
    const notificationOptions = {
      body: payload.body,
      icon: payload.icon
    };
    var notification = new Notification(notificationTitle, notificationOptions);
    if(payload.click_action != '') {
      notification.addEventListener("click", function (event) {

      messaging.getToken().then(function (currentToken) {
        if (currentToken) {
          {
          scriptJquery.post(en4.core.baseUrl+'browserpush/index/notifications/',{scheduled_id:payload.scheduled_id,token:currentToken,param:'2'},function(result){
            if(result) {
              //console.log('User Subscribed Successfully');  
            }else{
              //console.log('Error While Subscribing User'); 
            }
          });  
          }
        }
      }).then(function () {
      }).catch(function (err) {
          console.log(err);
      });
        
        window.open(payload.click_action);
      }, false);
    }
  });
  
  scriptJquery(window).load(function(){
    <?php if($this->type == '0') { ?>
      requestPermission();  
    <?php } ?>
    <?php if($this->type == '1') { ?>
      if(browser_ispopup == '') {
      requestPermission();
      }
      scriptJquery ('.hide_push_popup').hide();
    <?php } ?>
  });
  
  function requestPermission() {
    //if already subscribed
    if (Notification.permission === "granted") {
        var status = 2;
        messageNotification(status,'*');
        return;
    } else if(Notification.permission == 'default') {
      if(scriptJquery('#browsepush_browser_permission_container'))
        scriptJquery('#browsepush_browser_permission_container').show();
      if(scriptJquery('#browsepush_browser_permission_box'))
        scriptJquery('#browsepush_browser_permission_box').show();
      if(scriptJquery('#browserpush_notification_bubble'))
        scriptJquery('#browserpush_notification_bubble').hide();
    }
    
    Notification.requestPermission(function (state) {

      if(state == 'default') {
        if(scriptJquery('#browsepush_browser_permission_container'))
        scriptJquery('#browsepush_browser_permission_container').hide();
        if(scriptJquery('#browsepush_browser_permission_box'))
        scriptJquery('#browsepush_browser_permission_box').hide();
        if(scriptJquery('#browserpush_notification_bubble'))
          scriptJquery('#browserpush_notification_bubble').hide();
      } else if(state == 'granted') {
        if(scriptJquery('#browsepush_browser_permission_container'))
        scriptJquery('#browsepush_browser_permission_container').hide();
        if(scriptJquery('#browsepush_browser_permission_box'))
        scriptJquery('#browsepush_browser_permission_box').hide();
        
        if(scriptJquery('#subscribe_browertip')) {
          scriptJquery('#subscribe_browertip').html('<?php echo $this->translate("Click to Unsubscribe"); ?>');
          scriptJquery('#browserpush_tip').removeClass('showpulldown');
          scriptJquery('#browserpush_bell').attr('data-active', '0');
        }
      } else if(state == 'denied') {
        if(scriptJquery('#browsepush_browser_permission_container'))
          scriptJquery('#browsepush_browser_permission_container').hide();
        if(scriptJquery('#browsepush_browser_permission_box'))
          scriptJquery('#browsepush_browser_permission_box').hide();
      }
      // call message event handler of parent window
      var status = 1;
      messageNotification(status,'*');
    });
  }

  function messageNotification(status,token) {
    // Get registration token. Initially this makes a network call, once retrieved
    // subsequent calls to getToken will return from cache.
    messaging.getToken().then(function (currentToken) {
      if (currentToken) {
        {
          window.localStorage.setItem('sitesubscriber', currentToken);
          updateNotification(currentToken);
        }
      }
    }).then(function () {
    }).catch(function (err) {
        console.log(err);
    });
 }
 
function updateNotification(token){
  var browser = checkBrowser();
  scriptJquery.post(en4.core.baseUrl+'browserpush/index/update/',{token:token,browser:browser[0]},function(result) {
    if(result) {
      //console.log('User Subscribed Successfully');  
    } else {
      //console.log('Error While Subscribing User'); 
    }
  });  
}
</script>
