<?php
/**
  * Ahead WebSoft Technologies Pvt Ltd.
  * @copyright  Copyright 2006-2026 Ahead WebSoft Technologies Pvt Ltd.
  * @license    https://www.socialengine.com/policies
*/

class Browserpush_Api_Core extends Core_Api_Abstract {
  
  function sendPush($params = array(), $tokenids) {

    $message = array(
      'title' => $params['title'],
      'body' => !empty($params['body']) ? $params['body'] : " ",
      'icon' => !empty($params['icon']) ? $params['icon'] : " ",
      'click_action' => !empty($params['click_action']) ? $params['click_action'] : " ",
      'scheduled_id' => !empty($params['scheduled_id']) ? 'scheduled_' . $params['scheduled_id'] :'scheduled_0',
    );

    $settings = Engine_Api::_()->getApi('settings', 'core');

    $snippet = $settings->getSetting('browserpush.snippet', '');

    $token = $this->getFCMToken();
    if(!$token) return;

    // Parse service account details
    $authConfig = json_decode($snippet);

    $headers = array(
      'Authorization: Bearer ' .$token,
      'Content-Type: application/json'
    );
    $url = 'https://fcm.googleapis.com/v1/projects/'.$authConfig->project_id.'/messages:send';
    
    foreach($tokenids as $array){
      $fields = array("message"=>array(
        'token' => $array,
        'data' => $message,
      ));
      $this->useCurl($url, $headers,json_encode($fields));
    }
    return true;
  }

	private function useCurl($url, $headers, $fields = null) {
    // Open connection
    $ch = curl_init();
    if ($url) {
      // Set the url, number of POST vars, POST data
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
      curl_setopt($ch,CURLOPT_TIMEOUT,10);
      // Disabling SSL Certificate support temporarly
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
      if ($fields)
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
      // Execute post
      $result = curl_exec($ch);
      // Close connection
      curl_close($ch);
      return $result;
    }
  }

  function getFCMToken() {
    
    $settings = Engine_Api::_()->getApi('settings', 'core');

    $tokenfcm = $settings->getSetting('browserpush_tokenfcm', '');
    $tokentime = $settings->getSetting('browserpush_tokentime', '');

    // Read service account details
    $authConfigString = $settings->getSetting('browserpush.snippet');

    if(!empty($tokenfcm)){
      if($tokentime > time() - (50*60)){
        return $tokenfcm;
      }
    }
    
    // Parse service account details
    $authConfig = json_decode($authConfigString);

    // Read private key from service account details
    $secret = openssl_get_privatekey($authConfig->private_key);

    // Create the token header
    $header = json_encode([
      'typ' => 'JWT',
      'alg' => 'RS256'
    ]);

    // Get seconds since 1 January 1970
    $time = time();

    // Allow 1 minute time deviation between client en server (not sure if this is necessary)
    $start = $time - 60;
    $end = $start + 3600;

    // Create payload
    $payload = json_encode([
      "iss" => $authConfig->client_email,
      "scope" => "https://www.googleapis.com/auth/firebase.messaging",
      "aud" => "https://oauth2.googleapis.com/token",
      "exp" => $end,
      "iat" => $start
    ]);

    // Encode Header
    $base64UrlHeader = $this->base64UrlEncode($header);

    // Encode Payload
    $base64UrlPayload = $this->base64UrlEncode($payload);
    
    // Create Signature Hash
    $result = openssl_sign($base64UrlHeader . "." . $base64UrlPayload, $signature, $secret, OPENSSL_ALGO_SHA256);

    // Encode Signature to Base64Url String
    $base64UrlSignature = $this->base64UrlEncode($signature);

    // Create JWT
    $jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
    
    //-----Request token, with an http post request------
    $options = array('http' => array(
        'method'  => 'POST',
        'content' => 'grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion='.$jwt,
        'header'  => "Content-Type: application/x-www-form-urlencoded"
    ));
    $context  = stream_context_create($options);
   
    $responseText = file_get_contents("https://oauth2.googleapis.com/token", false, $context);
    
    $response = json_decode($responseText);
    if(!empty($response->access_token)){
      
      if($settings->getSetting('browserpush.tokenfcm')){
        $settings->removeSetting('browserpush.tokenfcm');
        $settings->setSetting('browserpush.tokenfcm', $response->access_token);
      }

      if($settings->getSetting('browserpush.tokentime')){
        $settings->removeSetting('browserpush.tokentime');
        $settings->setSetting('browserpush.tokentime', time());
      }
      return $response->access_token;
    }
  }

  function base64UrlEncode($text) {
    return str_replace(
      ['+', '/', '='],
      ['-', '_', ''],
      base64_encode($text)
    );
  }

  public function sendNotification($values) {

    $title = $values['title'];
    $body = $values['description'];
    $href = $values['link'];
    $image = '';

    if($values['file_id']){
      $file = Engine_Api::_()->getItemTable('storage_file')->getFile($values['file_id']);
      if( $file ) {
        $image =  $file->map();
        $baseURL =(!empty($_SERVER["HTTPS"]) && strtolower($_SERVER["HTTPS"] == 'on')) ? "https://" : 'http://';
        $baseURL = $baseURL. $_SERVER['HTTP_HOST'];
        if(strpos($image,'http') === false)
          $image = $baseURL.$image;
      }
    }

    if($values['criteria'] == 'all') {
      $tokens = Engine_Api::_()->getDbTable('tokens','browserpush')->getTokens();
    } else if($values['criteria'] == 'memberlevel') {
      $level = $values['param'];
      $tokens = Engine_Api::_()->getDbTable('tokens','browserpush')->getTokens(array('level'=>$level));
    } else if($values['criteria'] == 'network') {
      $network = $values['param'];
      $tokens = Engine_Api::_()->getDbTable('tokens','browserpush')->getTokens(array('network'=>$network));
    } else if($values['criteria'] == 'user') {
      $user_ids = $values['param'];
      $tokens = Engine_Api::_()->getDbTable('tokens','browserpush')->getTokens(array('user_ids'=>$user_ids));
    } else {
      $tokens = Engine_Api::_()->getDbTable('tokens','browserpush')->getTokens(array('browser'=>$values['criteria']));
    }

    Engine_Api::_()->browserpush()->sendPush(array('title'=>strip_tags($title),'body'=>$body,'icon'=>$image,'click_action'=>$href),$tokens);
    
    $values->sent = 1;
    $values->save();
    return true;
  }
}
