<?php

/*======================================================================*\
|| #################################################################### ||
|| # Push Notification System Wordpress Plugin                        # ||
|| # ---------------------------------------------------------------- # ||
|| # Copyright ©2014-2017 Smart IO Labs Inc. All Rights Reserved.     # ||
|| # This file may not be redistributed in whole or significant part. # ||
|| # --- Smart Push Notification System IS NOT FREE SOFTWARE ---      # ||
|| # https://smartiolabs.com/product/push-notification-system         # ||
|| #################################################################### ||
\*======================================================================*/

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

use Rakit\Validation\Validator;

class smpush_modules extends smpush_controller {

  public static $wpdateformat;
  public static $reports;

  public function __construct() {
    parent::__construct();
  }
  
  public static function widget() {
    register_widget('smpush_widget');
  }
  
  public static function error_log() {
    if(!empty($_POST['clear'])){
      smpush_unlink(smpush_dir.'/cron_log.log');
    }
    $error_log = '';
    if(file_exists(smpush_dir.'/cron_log.log')){
      $error_log = smpush_helper::readFile(smpush_dir.'/cron_log.log');
    }
    include(smpush_dir.'/pages/error_log.php');
  }
  
  public static function collectUsage($fromdate, $todate, $platform, $msgid=0) {
	global $wpdb;
    $where = '';
    $dwhere = '';
    $dataTypes = [];
    $dataTypes2 = [];
    if(!empty($platform)){
      $where .= " AND platid=%s";
      array_push($dataTypes, $platform);
    }
    if(!empty($msgid)){
      $where .= " AND msgid=%d";
      array_push($dataTypes, $msgid);
      $dwhere .= " AND msgid=%d";
      array_push($dataTypes2, $msgid);
    }
    $where .= " AND `date` BETWEEN %s AND %s GROUP BY `date` ORDER BY `date` ASC";
    array_push($dataTypes, $fromdate);
    array_push($dataTypes, $todate);
    $dwhere .= " AND `date` BETWEEN %s AND %s";
    array_push($dataTypes2, $fromdate);
    array_push($dataTypes2, $todate);
    self::$reports['platforms'] = array(
    'smsgs' => 0,
    'fmsgs' => 0,
    'views' => 0,
    'clicks' => 0,
    'devices' => 0,
    'total' => 0,
    );
    
    $results = $wpdb->get_results($wpdb->prepare("SELECT SUM(stat) AS smsg,`date` FROM ".$wpdb->prefix."push_statistics WHERE `action`='smsg' $where", $dataTypes), ARRAY_A);
    if($results){
      foreach($results as $result){
        self::$reports[$result['date']]['smsg'] = $result['smsg'];
        self::$reports[$result['date']]['totals'] += $result['smsg'];
        self::$reports['platforms']['smsgs'] += $result['smsg'];
      }
    }
    $results = $wpdb->get_results($wpdb->prepare("SELECT SUM(stat) AS fmsg,`date` FROM ".$wpdb->prefix."push_statistics WHERE `action`='fmsg' $where", $dataTypes), ARRAY_A);
    if($results){
      foreach($results as $result){
        self::$reports[$result['date']]['fmsg'] = $result['fmsg'];
        self::$reports[$result['date']]['totalf'] += $result['fmsg'];
        self::$reports['platforms']['fmsgs'] += $result['fmsg'];
      }
    }
    
    $results = $wpdb->get_results($wpdb->prepare("SELECT SUM(stat) AS sschmsg,`date` FROM ".$wpdb->prefix."push_statistics WHERE `action`='sschmsg' $where", $dataTypes), ARRAY_A);
    if($results){
      foreach($results as $result){
        self::$reports[$result['date']]['sschmsg'] = $result['sschmsg'];
        self::$reports[$result['date']]['totals'] += $result['sschmsg'];
        self::$reports['platforms']['smsgs'] += $result['sschmsg'];
      }
    }

    $results = $wpdb->get_results($wpdb->prepare("SELECT SUM(stat) AS fschmsg,`date` FROM ".$wpdb->prefix."push_statistics WHERE `action`='fschmsg' $where", $dataTypes), ARRAY_A);
    if($results){
      foreach($results as $result){
        self::$reports[$result['date']]['fschmsg'] = $result['fschmsg'];
        self::$reports[$result['date']]['totalf'] += $result['fschmsg'];
        self::$reports['platforms']['fmsgs'] += $result['fschmsg'];
      }
    }
    
    $results = $wpdb->get_results($wpdb->prepare("SELECT SUM(stat) AS sgeomsg,`date` FROM ".$wpdb->prefix."push_statistics WHERE `action`='sgeomsg' $where", $dataTypes), ARRAY_A);
    if($results){
      foreach($results as $result){
        self::$reports[$result['date']]['sgeomsg'] = $result['sgeomsg'];
        self::$reports[$result['date']]['totals'] += $result['sgeomsg'];
        self::$reports['platforms']['smsgs'] += $result['sgeomsg'];
      }
    }
    $results = $wpdb->get_results($wpdb->prepare("SELECT SUM(stat) AS fgeomsg,`date` FROM ".$wpdb->prefix."push_statistics WHERE `action`='fgeomsg' $where", $dataTypes), ARRAY_A);
    if($results){
      foreach($results as $result){
        self::$reports[$result['date']]['fgeomsg'] = $result['fgeomsg'];
        self::$reports[$result['date']]['totalf'] += $result['fgeomsg'];
        self::$reports['platforms']['fmsgs'] += $result['fgeomsg'];
      }
    }
    
    if(empty($msgid)){
      $results = $wpdb->get_results($wpdb->prepare("SELECT SUM(stat) AS newdevice,`date` FROM ".$wpdb->prefix."push_statistics WHERE `action`='newdevice' $where", $dataTypes), ARRAY_A);
      if($results){
        foreach($results as $result){
          self::$reports[$result['date']]['newdevice'] = $result['newdevice'];
        }
      }
      $results = $wpdb->get_results($wpdb->prepare("SELECT SUM(stat) AS invdevice,`date` FROM ".$wpdb->prefix."push_statistics WHERE `action`='invdevice' $where", $dataTypes), ARRAY_A);
      if($results){
        foreach($results as $result){
          self::$reports[$result['date']]['invdevice'] = $result['invdevice'];
        }
      }
      
      $results = $wpdb->get_results($wpdb->prepare("SELECT SUM(stat) AS registered,platid FROM ".$wpdb->prefix."push_statistics WHERE `action`='newdevice' $dwhere GROUP BY `platid` ORDER BY `platid` ASC", $dataTypes2), ARRAY_A);
      if($results){
        foreach($results as $result){
          self::$reports['platforms'][$result['platid']] = $result['registered'];
          self::$reports['platforms']['total'] += $result['registered'];
        }
      }

      $results = $wpdb->get_results($wpdb->prepare("SELECT SUM(stat) AS counter,`action` FROM ".$wpdb->prefix."push_statistics WHERE `action` IN ('newdevice','invdevice') $dwhere GROUP BY `action` ORDER BY `action` ASC", $dataTypes2), ARRAY_A);
      if($results){
        foreach($results as $result){
          self::$reports['platforms'][$result['action']] = $result['counter'];
          self::$reports['platforms']['devices'] += $result['counter'];
        }
      }
    }
    
    $results = $wpdb->get_results($wpdb->prepare("SELECT SUM(stat) AS views,`date` FROM ".$wpdb->prefix."push_statistics WHERE `action`='views' $where", $dataTypes), ARRAY_A);
    if($results){
      foreach($results as $result){
        self::$reports[$result['date']]['views'] = $result['views'];
        self::$reports['platforms']['views'] += $result['views'];
      }
    }
    
    $results = $wpdb->get_results($wpdb->prepare("SELECT SUM(stat) AS clicks,`date` FROM ".$wpdb->prefix."push_statistics WHERE `action`='clicks' $where", $dataTypes), ARRAY_A);
    if($results){
      foreach($results as $result){
        self::$reports[$result['date']]['clicks'] = $result['clicks'];
        self::$reports['platforms']['clicks'] += $result['clicks'];
      }
    }
    
  }
  
  public static function statistics() {
    global $wpdb;
    self::load_jsplugins();
    $pageurl = admin_url().'admin.php?page=smpush_statistics';
    $pagname = 'smpush_statistics';
    wp_enqueue_script('smpush-moment-js');
    wp_enqueue_script('smpush-chart-bundle');
    wp_enqueue_script('smpush-chart-lib');
    wp_enqueue_style('smpush-jquery-smoothness');
    wp_enqueue_script('jquery-ui-core');
    wp_enqueue_script('jquery-ui-datepicker');
    if(empty($_GET['fromdate'])){
      $_GET['fromdate'] = date('Y-m-1', current_time('timestamp'));
    }
    if(empty($_GET['todate'])){
      $_GET['todate'] = date('Y-m-d', current_time('timestamp'));
    }
    if(empty($_GET['platform'])){
      $_GET['platform'] = 0;
    }
    self::collectUsage($_GET['fromdate'], $_GET['todate'], $_GET['platform']);
    $stat_date = array();
    $stat_date['start'] = strtotime($_GET['fromdate']);
    $stat_date['end'] = strtotime($_GET['todate']);
    include(smpush_dir.'/pages/general_statistics.php');
  }
  
  public static function archivepending() {
    self::archive(true, false);
  }

  public static function archiveauto() {
    self::archive(false, true);
  }

  public static function smpush_archiveres() {
    self::archive(true, false, true);
  }

  public static function ajax_actions() {
    if ($_GET['action'] == 'testemail') {
      wp_mail($_POST['email'], $_POST['subject'], $_POST['content'], array('From: '.bloginfo('name').' <'.get_option('admin_email').'>'));
      echo 1;
      exit;
    }
    elseif ($_GET['action'] == 'jsontemplate') {
      global $wpdb;
      $template = $wpdb->get_row($wpdb->prepare("SELECT * FROM ".$wpdb->prefix."push_newsletter_templates WHERE id=%d", [ $_GET['template'] ]));
      if($_GET['template'] <= 9){
        $templateContents = smpush_helper::readFile(smpush_dir.'/newsletter/'.$template->template.'.json');
        $templateContents = str_replace('{SITEDOMAIN}', get_bloginfo('wpurl'), $templateContents);
        $templateContents = str_replace('{ASSETS_LINK}', (plugins_url().'/smio-push-notification/newsletter/images'), $templateContents);
        echo $templateContents;
      }
      else{
        echo stripslashes($template->template);
      }
      exit;
    }
  }
  
  public static function archive($pendingonly=false, $autocamps=false, $autoresp=false) {
    if (isset($_GET['action']) && $_GET['action'] == 'edit') {
      smpush_sendpush::send_notification();
      return;
    }
    global $wpdb;
    self::load_jsplugins();
    if($_REQUEST['page'] == 'smpush_campending'){
      $pageurl = admin_url().'admin.php?page=smpush_campending';
      $pagname = 'smpush_campending';
    }
    elseif($_REQUEST['page'] == 'smpush_archiveauto'){
      $pageurl = admin_url().'admin.php?page=smpush_archiveauto';
      $pagname = 'smpush_archiveauto';
    }
    else{
      $pageurl = admin_url().'admin.php?page=smpush_archive';
      $pagname = 'smpush_archive';
    }
    
    if (isset($_GET['delete'])) {
      $wpdb->query($wpdb->prepare("DELETE FROM ".$wpdb->prefix."push_archive WHERE id=%d", [ $_GET['id'] ]));
      $wpdb->query($wpdb->prepare("DELETE FROM ".$wpdb->prefix."push_archive_reports WHERE msgid=%d", [ $_GET['id'] ]));
      $wpdb->query($wpdb->prepare("DELETE FROM ".$wpdb->prefix."push_cron_queue WHERE sendoptions=%d", [ $_GET['id'] ]));
      $wpdb->query($wpdb->prepare("DELETE FROM ".$wpdb->prefix."push_statistics WHERE msgid=%d", [ $_GET['id'] ]));
      $wpdb->query($wpdb->prepare("DELETE FROM ".$wpdb->prefix."push_desktop_messages WHERE msgid=%d", [ $_GET['id'] ]));
      $wpdb->query($wpdb->prepare("DELETE FROM ".$wpdb->prefix."push_history WHERE msgid=%d", [ $_GET['id'] ]));
      $wpdb->query($wpdb->prepare("DELETE FROM ".$wpdb->prefix."push_newsletter_templates WHERE msgid=%d", [ $_GET['id'] ]));
      exit;
    }
    if (isset($_GET['action']) && $_GET['action'] == 'clone') {
      $message = $wpdb->get_row($wpdb->prepare("SELECT * FROM ".$wpdb->prefix."push_archive WHERE id=%d", [ $_GET['id'] ]), ARRAY_A);
      $message_email = $wpdb->get_row($wpdb->prepare("SELECT * FROM ".$wpdb->prefix."push_newsletter_templates WHERE msgid=%d", [ $_GET['id'] ]), ARRAY_A);
      $message['processed'] = 0;
      $message['endtime'] = NULL;
      $message['status'] = 0;
      if($message['send_type'] == 'live'){
        $message['send_type'] = 'now';
      }
      unset($message['id']);
      $msgid = $wpdb->insert($wpdb->prefix.'push_archive', $message);
      if($message_email){
        unset($message_email['id']);
        $message_email['msgid'] = $msgid;
        $wpdb->insert($wpdb->prefix.'push_newsletter_templates', $message_email);
      }
      self::redirect(admin_url().'admin.php?page=smpush_campending');
      exit;
    }
    if (isset($_GET['empty'])) {
      set_time_limit(0);
      $toforgets = $wpdb->get_results("SELECT id FROM ".$wpdb->prefix."push_archive WHERE send_type IN('now','custom','feedback')");
      if($toforgets){
        foreach($toforgets as $toforget){
          $wpdb->query("DELETE FROM ".$wpdb->prefix."push_archive WHERE id='$toforget->id'");
          $wpdb->query("DELETE FROM ".$wpdb->prefix."push_archive_reports WHERE msgid='$toforget->id'");
          $wpdb->query("DELETE FROM ".$wpdb->prefix."push_history WHERE msgid='$toforget->id'");
          $wpdb->query("DELETE FROM ".$wpdb->prefix."push_newsletter_templates WHERE msgid='$toforget->id'");
          $wpdb->query("DELETE FROM ".$wpdb->prefix."push_statistics WHERE msgid='$toforget->id'");
        }
      }
      $wpdb->query("TRUNCATE ".$wpdb->prefix."push_cron_queue");
      $wpdb->query("TRUNCATE ".$wpdb->prefix."push_queue");
      $wpdb->query("TRUNCATE ".$wpdb->prefix."push_desktop_messages");
      wp_redirect($pageurl);
    }
    elseif (!empty($_GET['apply'])) {
      if (!empty($_GET['doaction'])) {
        $doaction = $_GET['doaction'];
      } elseif (!empty($_GET['doaction2'])) {
        $doaction = $_GET['doaction2'];
      }
      $_GET['archive'] = array_map('intval', $_GET['archive']);
      $ids = implode(',', $_GET['archive']);
      if ($doaction == 'delete') {
        $wpdb->query("DELETE FROM ".$wpdb->prefix."push_archive WHERE id IN($ids)");
        $wpdb->query("DELETE FROM ".$wpdb->prefix."push_archive_reports WHERE msgid IN($ids)");
        parent::update_counters();
      }
      elseif ($doaction == 'active') {
        $wpdb->query("UPDATE ".$wpdb->prefix."push_archive SET status='1' WHERE id IN($ids)");
      }
      elseif ($doaction == 'deactive') {
        $wpdb->query("UPDATE ".$wpdb->prefix."push_archive SET status='0' WHERE id IN($ids)");
      }
      wp_redirect($pageurl);
    }
    elseif (isset($_GET['action']) && $_GET['action'] == 'reports') {
      wp_enqueue_script('smpush-moment-js');
      wp_enqueue_script('smpush-chart-bundle');
      wp_enqueue_script('smpush-chart-lib');
      wp_enqueue_script('jquery-ui-datepicker');
      wp_enqueue_style('smpush-jquery-ui');
      if(empty($_GET['fromdate'])){
        $_GET['fromdate'] = date('Y-m-1', current_time('timestamp'));
      }
      if(empty($_GET['todate'])){
        $_GET['todate'] = date('Y-m-d', current_time('timestamp'));
      }
      if(empty($_GET['platform'])){
        $_GET['platform'] = 0;
      }
      self::collectUsage($_GET['fromdate'], $_GET['todate'], $_GET['platform'], $_GET['msgid']);
      $stat_date = array();
      $stat_date['start'] = strtotime($_GET['fromdate']);
      $stat_date['end'] = strtotime($_GET['todate']);
      include(smpush_dir.'/pages/archive_reports.php');
    }
    else {
      self::$wpdateformat = get_option('date_format').' '.get_option('time_format');
      $where = array();
      $dataTypes = [];
      $order = 'ORDER BY id DESC';
      if (!empty($_GET['type'])) {
        if($_GET['type'] == 'now'){
          $where[] = "send_type IN('now','live')";
        }
        else{
          $where[] = "send_type=%s";
          array_push($dataTypes, $_GET['type']);
        }
      }
      else{
        $_GET['type'] = '';
      }
      if (!empty($_GET['status'])) {
        $where[] = "status=%d";
        array_push($dataTypes, (($_GET['status'] == 1)? 1 : 0));
      }
      else{
        $_GET['status'] = 0;
      }
      if (!empty($_GET['query'])) {
        $where[] = "(name LIKE %s OR message LIKE %s)";
        array_push($dataTypes, '%'.$wpdb->esc_like($_GET['query']).'%');
        array_push($dataTypes, '%'.$wpdb->esc_like($_GET['query']).'%');
        $order = '';
      }
      else{
        $_GET['query'] = '';
      }
      if($pendingonly){
        $where[] = "processed='0'";
      }
      else{
        $where[] = "processed='1'";
      }
      if($autocamps){
        $where[] = "send_type='custom'";
      }
      elseif($autoresp){
        $where[] = "send_type='autoresponder'";
      }
      elseif(! $pendingonly){
        $where[] = "send_type!='custom'";
      }
      if (count($where) > 0) {
        $where = 'WHERE '.implode(' AND ', $where);
      } else {
        $where = '';
      }
      if($autoresp){
        $order = 'ORDER BY resp_sort ASC';
      }
      $sql = "SELECT * FROM ".$wpdb->prefix."push_archive $where $order";
      if(empty($dataTypes)){
        $archives = $wpdb->get_results(self::Paging($sql, $wpdb));
      } else {
        $archives = $wpdb->get_results(self::Paging($wpdb->prepare($sql, $dataTypes), $wpdb));
      }
      $paging_args = array(
        'base' => preg_replace('/&?callpage=([0-9]+)/', '', $_SERVER['REQUEST_URI']).'%_%',
        'format' => '&callpage=%#%',
        'total' => self::$paging['pages'],
        'current' => (empty(self::$paging['page']))? 1 : self::$paging['page'],
        'show_all' => false,
        'end_size' => 3,
        'mid_size' => 2,
        'prev_next' => true,
        'prev_text' => esc_html__('« Previous'),
        'next_text' => esc_html__('Next »')
      );
      include(smpush_dir.'/pages/archive_manage.php');
    }
  }

  public static function tokens() {
    global $wpdb;
    self::load_jsplugins();
    $pageurl = admin_url().'admin.php?page=smpush_tokens';
    $pagname = 'smpush_tokens';
    if (!empty($_POST['device_type'])) {
      require(smpush_dir.'/lib/validation/autoload.php');
      $validator = new Validator;
      $validation = $validator->make($_POST, [
        'device_token' => 'required|max:500',
        'information' => 'nullable|max:500',
        'device_type' => 'required',
        'active' => 'boolean',
      ]);
      $validation->validate();
      if ($validation->fails()) {
        $errors = $validation->errors();
        self::jsonPrint('validation', $errors->all());
      }

      if (empty($_POST['device_token'])) {
        self::jsonPrint(0, esc_html__('Field `Device Token` is required.', 'smio-push-notification'));
      }
      if ($_POST['id'] > 0) {
        self::$pushdb->query(self::parse_query("UPDATE {tbname} SET {id_name}='$_POST[id]',{token_name}='$_POST[device_token]',{md5token_name}='".md5($_REQUEST['device_token'])."',{type_name}='$_POST[device_type]',{info_name}='$_POST[information]',{active_name}='$_POST[active]',{latitude_name}='$_POST[latitude]',{longitude_name}='$_POST[longitude]',{gpstime_name}='".current_time('timestamp')."' WHERE {id_name}='$_POST[id]'"));
        $tokenid = $_POST['id'];
      } else {
        self::$pushdb->query(self::parse_query("INSERT INTO {tbname} ({token_name},{md5token_name},{type_name},{info_name},{active_name},{latitude_name},{longitude_name},{gpstime_name},{postdate}) VALUES ('$_POST[device_token]','".md5($_REQUEST['device_token'])."','$_POST[device_type]','$_POST[information]','$_POST[active]','$_POST[latitude]','$_POST[longitude]','".current_time('timestamp')."','".gmdate('Y-m-d H:i:s', current_time('timestamp'))."')"));
        $tokenid = self::$pushdb->insert_id;
        $wpdb->query("UPDATE ".$wpdb->prefix."push_connection SET counter=counter+1 WHERE id='".self::$apisetting['def_connection']."'");
      }
      if (!empty($_POST['channels'])) {
        $_POST['channels'] = implode(',', $_POST['channels']);
        smpush_api::editSubscribedChannels($tokenid, $_POST['channels']);
      }
      echo 1;
      exit;
    }
    elseif (isset($_GET['dismiss_vap_warn'])) {
      update_option('smpush_dismiss_vapwarn', 1);
      wp_redirect($_SERVER['HTTP_REFERER']);
    }
    elseif (isset($_GET['remove_duplicates'])) {
      self::$pushdb->query(self::parse_query("CREATE TABLE {tbname_temp} AS SELECT * FROM {tbname} GROUP BY {md5token_name}"));
      if (empty(self::$pushdb->last_error)) {
        self::$pushdb->query(self::parse_query("ALTER TABLE {tbname_temp} ADD PRIMARY KEY({id_name})"));
        self::$pushdb->query(self::parse_query("ALTER TABLE {tbname_temp} CHANGE {id_name} {id_name} INT(11) NOT NULL AUTO_INCREMENT"));
        self::$pushdb->query(self::parse_query("ALTER TABLE  {tbname_temp} ADD INDEX ({md5token_name})"));
        self::$pushdb->query(self::parse_query("DROP TABLE {tbname}"));
        self::$pushdb->query(self::parse_query("RENAME TABLE {tbname_temp} TO {tbname}"));
        parent::update_counters();
        wp_redirect($pageurl);
      }
      else {
        wp_die(esc_html__('An error has occurred, the system stopped and rolled back the changes.', 'smio-push-notification'));
      }
    }
    elseif (isset($_GET['remove_deads'])) {
      $counter = 0;
      $delIDs = [];
      $devices = self::$pushdb->get_results(self::parse_query("SELECT {id_name} AS devid FROM {tbname} WHERE {active_name}='0'"));
      if($devices){
        foreach($devices as $device){
          if($counter == 1000){
            $delIDs = implode(',', $delIDs);
            self::$pushdb->query(self::parse_query("DELETE FROM {tbname} WHERE {id_name} IN ($delIDs)"));
            $wpdb->query("DELETE FROM ".$wpdb->prefix."push_relation WHERE token_id IN ($delIDs)");
            $counter = 0;
            $delIDs = [];
          }
          $counter++;
          $delIDs[] = $device->devid;
        }
        if($counter < 1000 && $counter > 0){
          $delIDs = implode(',', $delIDs);
          self::$pushdb->query(self::parse_query("DELETE FROM {tbname} WHERE {id_name} IN ($delIDs)"));
          $wpdb->query("DELETE FROM ".$wpdb->prefix."push_relation WHERE token_id IN ($delIDs)");
        }
      }
      parent::update_counters();
      wp_redirect($pageurl);
    }
    elseif (isset($_GET['delete'])) {
      self::$pushdb->query($wpdb->prepare(self::parse_query("DELETE FROM {tbname} WHERE {id_name}=%d"), [ $_GET['id'] ]));
      $wpdb->query($wpdb->prepare("DELETE FROM ".$wpdb->prefix."push_relation WHERE token_id=%d AND connection_id='".self::$apisetting['def_connection']."'", [ $_GET['id'] ]));
      parent::update_counters();
      exit;
    }
    elseif (isset($_GET['id'])) {
      $channels = $wpdb->get_results("SELECT id,title FROM ".$wpdb->prefix."push_channels ORDER BY title ASC");
      $types_name = $wpdb->get_row("SELECT ios_name,iosfcm_name,android_name,wp_name,bb_name,chrome_name,safari_name,firefox_name,wp10_name,viber_name,fbmsn_name,fbnotify_name,opera_name,edge_name,samsung_name,email_name FROM ".$wpdb->prefix."push_connection WHERE id='".self::$apisetting['def_connection']."'");
      if ($_GET['id'] == -1) {
        $token = array('id' => 0, 'device_token' => '', 'device_type' => '', 'information' => '', 'latitude' => '', 'longitude' => '', 'channels' => array(), 'active' => 1);
      }
      else {
        $subschannels = $wpdb->get_results($wpdb->prepare("SELECT channel_id FROM ".$wpdb->prefix."push_relation WHERE token_id=%d AND connection_id='".self::$apisetting['def_connection']."'", [ $_GET['id'] ]));
        $token = self::$pushdb->get_row($wpdb->prepare(self::parse_query("SELECT {id_name} AS id,{token_name} AS device_token,{type_name} AS device_type,{info_name} AS information,{active_name} AS active,{latitude_name} AS latitude,{longitude_name} AS longitude FROM {tbname} WHERE {id_name}=%d"), [ $_GET['id'] ]), 'ARRAY_A');
        $token = array_map('stripslashes', $token);
        $token['channels'] = array();
        if ($subschannels) {
          foreach ($subschannels as $subschannel) {
            $token['channels'][] = $subschannel->channel_id;
          }
        }
      }
      include(smpush_dir.'/pages/token_form.php');
      exit;
    }
    else {
      $types_name = $wpdb->get_row("SELECT dbtype,ios_name,iosfcm_name,android_name,wp_name,bb_name,chrome_name,safari_name,firefox_name,wp10_name,viber_name,fbmsn_name,fbnotify_name,opera_name,edge_name,samsung_name,email_name FROM ".$wpdb->prefix."push_connection WHERE id='".self::$apisetting['def_connection']."'");
      $channels = $wpdb->get_results("SELECT id,title FROM ".$wpdb->prefix."push_channels ORDER BY title ASC");
      $where = array();
      $dataTypes = [];
      $inner = '';
      $order = 'ORDER BY {tbname}.{id_name} DESC';
      if (!empty($_GET['query'])) {
        $where[] = "({tbname}.{token_name}=%s OR {tbname}.{info_name} LIKE %s)";
        array_push($dataTypes, '%'.$wpdb->esc_like($_GET['query']).'%');
        array_push($dataTypes, '%'.$wpdb->esc_like($_GET['query']).'%');
        $order = '';
      }
      if (!empty($_GET['device_type'])) {
        $where[] = "{tbname}.{type_name}=%s";
        array_push($dataTypes, $_GET['device_type']);
      }
      else {
        $_GET['device_type'] = '';
      }
      if (!empty($_GET['userid'])) {
        $where[] = "{tbname}.userid=%d";
        array_push($dataTypes, $_GET['userid']);
      }
      else {
        $_GET['userid'] = '';
      }
      if (!empty($_GET['status'])) {
        if ($_GET['status'] == 2)
          $status = 0;
        else
          $status = 1;
        $where[] = "{tbname}.{active_name}='$status'";
      }
      else {
        $_GET['status'] = '-1';
      }
      if (!empty($_GET['channel_id'])) {
        $table = $wpdb->prefix.'push_relation';
        $inner = "INNER JOIN $table ON($table.token_id={tbname}.{id_name} AND $table.connection_id='".self::$apisetting['def_connection']."')";
        $where[] = "$table.channel_id=%d";
        array_push($dataTypes, $_GET['channel_id']);
        $order = 'GROUP BY {tbname}.{id_name} ORDER BY {tbname}.{id_name} DESC';
      } else {
        $_GET['channel_id'] = '';
      }
      if (count($where) > 0) {
        $where = 'WHERE '.implode(' AND ', $where);
      } else {
        $where = '';
      }
      if (!empty($_GET['apply'])) {
        if (!empty($_GET['doaction'])) {
          $doaction = $_GET['doaction'];
        } elseif (!empty($_GET['doaction2'])) {
          $doaction = $_GET['doaction2'];
        }
        $_GET['device'] = array_map('intval', $_GET['device']);
        $ids = implode(',', $_GET['device']);
        if ($doaction == 'activate') {
          self::$pushdb->query(self::parse_query("UPDATE {tbname} SET {active_name}='1' WHERE {id_name} IN($ids)"));
        } elseif ($doaction == 'deactivate') {
          self::$pushdb->query(self::parse_query("UPDATE {tbname} SET {active_name}='0' WHERE {id_name} IN($ids)"));
        } elseif ($doaction == 'delete') {
          self::$pushdb->query(self::parse_query("DELETE FROM {tbname} WHERE {id_name} IN($ids)"));
          $wpdb->query("DELETE FROM ".$wpdb->prefix."push_relation WHERE token_id IN($ids) AND connection_id='".self::$apisetting['def_connection']."'");
          parent::update_counters();
        }
        wp_redirect($pageurl);
      } elseif (!empty($_GET['applytoall'])) {
        if (!empty($_GET['doaction'])) {
          $doaction = $_GET['doaction'];
        } elseif (!empty($_GET['doaction2'])) {
          $doaction = $_GET['doaction2'];
        }
        $actionSql = self::parse_query("SELECT {tbname}.{id_name} AS id FROM {tbname} $inner $where GROUP BY {tbname}.{id_name}");
        if(empty($dataTypes)){
          $tokens = self::$pushdb->get_results($actionSql);
        } else {
          $tokens = self::$pushdb->get_results($wpdb->prepare($actionSql, $dataTypes));
        }
        if ($tokens) {
          foreach ($tokens as $token) {
            if ($doaction == 'activate') {
              self::$pushdb->query(self::parse_query("UPDATE {tbname} SET {active_name}='1' WHERE {id_name}='".$token->id."'"));
            } elseif ($doaction == 'deactivate') {
              self::$pushdb->query(self::parse_query("UPDATE {tbname} SET {active_name}='0' WHERE {id_name}='".$token->id."'"));
            } elseif ($doaction == 'delete') {
              self::$pushdb->query(self::parse_query("DELETE FROM {tbname} WHERE {id_name}='".$token->id."'"));
              $wpdb->query("DELETE FROM ".$wpdb->prefix."push_relation WHERE token_id='".$token->id."' AND connection_id='".self::$apisetting['def_connection']."'");
              parent::update_counters();
            }
          }
        }
        wp_redirect($pageurl);
      }
      $dbtype = $wpdb->get_var("SELECT dbtype FROM ".$wpdb->prefix."push_connection WHERE id='".self::$apisetting['def_connection']."'");
      if($dbtype == 'remote'){
        $sql = self::Paging(self::parse_query("SELECT {tbname}.{id_name} AS id,{tbname}.{token_name} AS device_token,{tbname}.{type_name} AS device_type
        ,{tbname}.{info_name} AS information,{tbname}.{latitude_name} AS latitude,{tbname}.{longitude_name} AS longitude,{tbname}.{postdate} AS timepost,{tbname}.{active_name} AS active FROM {tbname}
        $inner $where $order"), self::$pushdb);
      }
      else{
        $sql = self::parse_query("SELECT {tbname}.{id_name} AS id,{tbname}.{token_name} AS device_token,{tbname}.{type_name} AS device_type
        ,{tbname}.{info_name} AS information,{tbname}.{latitude_name} AS latitude,{tbname}.{longitude_name} AS longitude,{tbname}.{postdate} AS timepost,{tbname}.{active_name} AS active,$wpdb->users.user_login AS user FROM {tbname}
        LEFT JOIN $wpdb->users ON($wpdb->users.ID={tbname}.userid)
        $inner $where $order");

        if(empty($dataTypes)){
          $sql = self::Paging($sql, self::$pushdb);
        } else {
          $sql = self::Paging($wpdb->prepare($sql, $dataTypes), self::$pushdb);
        }
      }
      self::$wpdateformat = get_option('date_format').' '.get_option('time_format');
      $tokens = self::$pushdb->get_results($sql);
      $paging_args = array(
      'base' => preg_replace('/&?callpage=([0-9]+)/', '', $_SERVER['REQUEST_URI']).'%_%',
      'format' => '&callpage=%#%',
      'total' => self::$paging['pages'],
      'current' => self::$paging['page'],
      'show_all' => false,
      'end_size' => 3,
      'mid_size' => 2,
      'prev_next' => true,
      'prev_text' => esc_html__('« Previous'),
      'next_text' => esc_html__('Next »')
      );
      include(smpush_dir.'/pages/token_manage.php');
    }
  }

  public static function push_channel() {
    global $wpdb;
    self::load_jsplugins();
    $pageurl = admin_url().'admin.php?page=smpush_channel';
    if ($_POST) {
      require(smpush_dir.'/lib/validation/autoload.php');
      $validator = new Validator;
      $validation = $validator->make($_POST, [
        'title' => 'required|max:50',
        'description' => 'nullable|max:200',
        'privacy' => 'required|boolean',
      ]);
      $validation->validate();
      if ($validation->fails()) {
        $errors = $validation->errors();
        self::jsonPrint('validation', $errors->all());
      }

      if (empty($_POST['title'])) {
        self::jsonPrint(0, esc_html__('Field title is required.', 'smio-push-notification'));
      }
      if ($_POST['privacy'] == 1)
        $privacy = 1;
      else
        $privacy = 0;
      if ($_POST['id'] > 0) {
        $wpdb->update($wpdb->prefix.'push_channels', array('title' => $_POST['title'], 'description' => $_POST['description'], 'private' => $privacy), array('id' => $_POST['id']), ['%s','%s','%d'], ['%d']);
      } else {
        $wpdb->insert($wpdb->prefix.'push_channels', array('title' => $_POST['title'], 'description' => $_POST['description'], 'private' => $privacy), ['%s','%s','%d']);
      }
      echo 1;
      exit;
    } elseif (isset($_GET['update_counters'])) {
      parent::update_all_counters();
      wp_redirect($pageurl);
    } elseif (isset($_GET['delete'])) {
      $wpdb->query($wpdb->prepare("DELETE FROM ".$wpdb->prefix."push_channels WHERE id=%d", [ $_GET['id'] ]));
      $wpdb->query($wpdb->prepare("DELETE FROM ".$wpdb->prefix."push_relation WHERE channel_id=%d", [ $_GET['id'] ]));
      wp_redirect($pageurl);
    } elseif (isset($_GET['default'])) {
      $wpdb->query("UPDATE ".$wpdb->prefix."push_channels SET `default`='0'");
      $wpdb->update($wpdb->prefix.'push_channels', array('default' => 1), array('id' => $_GET['id']), ['%d'], ['%d']);
      wp_redirect($pageurl);
    } elseif (isset($_GET['id'])) {
      if ($_GET['id'] == -1) {
        $channel = array('id' => 0, 'title' => '', 'description' => '', 'private' => '0');
      } else {
        $channel = $wpdb->get_row($wpdb->prepare("SELECT * FROM ".$wpdb->prefix."push_channels WHERE id=%d", [ $_GET['id'] ]), 'ARRAY_A');
        $channel = array_map('stripslashes', $channel);
      }
      include(smpush_dir.'/pages/channel_form.php');
      exit;
    } else {
      $channels = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."push_channels ORDER BY id DESC");
      include(smpush_dir.'/pages/channel_manage.php');
    }
  }
  
  public static function import() {
    global $wpdb, $wp_filesystem;
    self::load_jsplugins();
    $pageurl = admin_url().'admin.php?page=smpush_import';

    if(!empty($_FILES['csv']['tmp_name'])) {
      $upload_dir = wp_upload_dir();
      $cert_upload_path = $upload_dir['basedir'].'/certifications';
      if(! file_exists($cert_upload_path)){
        if(! $wp_filesystem->mkdir($cert_upload_path)){
          header( 'HTTP/1.1 400 BAD REQUEST');
          echo esc_html__('can not create a directory to save the certifications files under uploads directory .', 'smio-push-notification');
          exit;
        }
      }

      $csvpath = $cert_upload_path.'/imported_file_'.time().'.csv';
      smpush_unlink($csvpath);
      if(! $wp_filesystem->move($_FILES['csv']['tmp_name'], $csvpath)){
        header( 'HTTP/1.1 400 BAD REQUEST');
        echo esc_html__('Can not move CSV file.', 'smio-push-notification');
        exit;
      }
    }
    elseif(!empty($_POST['csv_local'])) {
      $csvpath = $_POST['csv_local'];
    }

    if((!empty($_FILES['csv']['tmp_name']) || !empty($_POST['csv_local'])) && !isset($_POST['delite_plugin'])) {
      $delimiter = $_POST['delimiter'];
      $csvhtml = '';
      if (($handle = fopen($csvpath, 'r')) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
          $num = count($data);
          for ($c=0; $c < $num; $c++) {
            $data[$c] = trim(str_replace(array("\r", "\n", "\r\n"), '', $data[$c]));
            if(!empty($data[$c])){
              $csvhtml .= '<option value="'.$c.'">'.$data[$c].'</option>';
            }
          }
          fclose($handle);
          break;
        }
      }
      if(empty($csvhtml)){
        header( 'HTTP/1.1 400 BAD REQUEST');
        echo esc_html__('Can not parse CSV file.', 'smio-push-notification');
        smpush_unlink($csvpath);
      }
      else {
        header( 'HTTP/1.1 200 OK');
        include(smpush_dir.'/pages/tokens_import_options.php');
      }
      exit;
    }
    elseif ($_POST) {
      set_time_limit(0);

      if(isset($_POST['delite_plugin'])){
        $device_token = 0;
        $platform = 'chrome';
        $info = 4;
        $userid = 3;
        $_POST['csvfile'] = $csvpath;
        $_POST['delimiter'] = ',';
      } else {
        $device_token = $_POST['token'];
        $platform = $_POST['platform'];
        $info = $_POST['info'];
        $userid = $_POST['userid'];
      }

      $row = 1;
      $duplications = $new = $fail = $error = 0;
      $csvpath = realpath($_POST['csvfile']);
      if(!file_exists($csvpath)){
        header( 'HTTP/1.1 400 BAD REQUEST');
        echo esc_html__('Can not parse CSV file.', 'smio-push-notification');
        smpush_unlink($csvpath);
        exit;
      }
      if (($handle = fopen($csvpath, 'r')) !== FALSE) {
        while (($data = fgetcsv($handle, 0, $_POST['delimiter'])) !== FALSE) {
          $row++;
          if($row == 2)continue;
          if(empty($data[$device_token])){
            $fail++;
            continue;
          }
          if(isset($_POST['delite_plugin'])){
            if($data[1] != 'Web'){
              continue;
            }
            $data_device_token = json_encode(['endpoint' => $data[$device_token], 'p256dh' => $data[7], 'auth' => $data[8]]);
            $data_info = addslashes($data[$info]);
          } else {
            $data_device_token = addslashes($data[$device_token]);
            $data_info = addslashes($data[$info]);
          }
          $tokenid = self::$pushdb->get_var(self::parse_query("SELECT {id_name} FROM {tbname} WHERE {md5token_name}='".md5($data_device_token)."' AND {type_name}='$platform'"));
          if($tokenid > 0){
            $duplications++;
          }
          else{
            self::$pushdb->query(self::parse_query("INSERT INTO {tbname} ({token_name},{md5token_name},{type_name},{info_name},{active_name},{latitude_name},{longitude_name},{gpstime_name},{firebase_name}) VALUES ('$data_device_token','".md5($data_device_token)."','$platform','$data_info','1','0.00000000','0.00000000','".current_time('timestamp')."','0')"));
            if(! empty($data[$userid])){
              $wpdb->query('UPDATE '.$wpdb->prefix.'sm_push_tokens SET userid="'.$data[$userid].'" WHERE id="'.self::$pushdb->insert_id.'"');
            }
            $new++;
          }
        }
        fclose($handle);
        smpush_unlink($csvpath);
      }
      
      if($new > 0){
        $current_date = gmdate('Y-m-d', current_time('timestamp'));
        $statid = $wpdb->get_var("SELECT id FROM ".$wpdb->prefix."push_statistics WHERE platid='$platform' AND `date`='$current_date' AND action='newdevice'");
        if(empty($statid)){
          $stat = array();
          $stat['platid'] = $platform;
          $stat['date'] = $current_date;
          $stat['action'] = 'newdevice';
          $stat['stat'] = $new;
          $wpdb->insert($wpdb->prefix.'push_statistics', $stat);
        }
        else{
          $wpdb->query("UPDATE ".$wpdb->prefix."push_statistics SET `stat`=`stat`+$new WHERE id='$statid'");
        }
      }
      
      if(empty($error)){

        if(isset($_POST['delite_plugin'])){
          self::$apisetting['desktop_used_webpush'] = 1;
          update_option('smpush_options', self::$apisetting);
        }

        header( 'HTTP/1.1 200 OK');
        echo esc_html__('System finished importing subscribers', 'smio-push-notification').': '.$new.' '.esc_html__('new', 'smio-push-notification').' . '.$duplications.' '.esc_html__('duplicated', 'smio-push-notification').' . '.$fail.' '.esc_html__('fail', 'smio-push-notification');
      }
      else{
        header( 'HTTP/1.1 400 BAD REQUEST');
        echo $error;
      }
      exit;
    }
    else {
      include(smpush_dir.'/pages/tokens_import.php');
    }
  }

  public static function onesignal() {
    self::load_jsplugins();
    $pageurl = admin_url().'admin.php?page=smpush_onesignal';
    include(smpush_dir.'/pages/onesignal_import.php');
  }

  public static function testing() {
    global $wpdb;
    self::load_jsplugins();
    $pageurl = admin_url().'admin.php?page=smpush_test_sending';
    if ($_POST) {
      $message = $_POST['message'];
      $applelog = esc_html__('No device token', 'smio-push-notification');
      $googlelog = esc_html__('No device token', 'smio-push-notification');

      if (!empty($_POST['ios_token'])) {
        if (!defined('CURL_HTTP_VERSION_2_0')) {
          define('CURL_HTTP_VERSION_2_0', 3);
        }
        $chandle = curl_init();

        $message = html_entity_decode(preg_replace("/U\+([0-9A-F]{4})/", "&#x\\1;", $message), ENT_NOQUOTES, 'UTF-8');
        $body = [];
        if(self::$apisetting['ios_compatibility'] == 'expo') {
          $body['aps'] = array('alert' => ['title' => 'For Test', 'body' => $message], 'sound' => 'default');
          $body['body'] = ['postid' => 95];
        } else {
          $body['aps'] = array('alert' => $message, 'sound' => 'default');
        }
        $payload = json_encode($body, defined('JSON_UNESCAPED_UNICODE') ? JSON_UNESCAPED_UNICODE : 0);

        $cert = self::$apisetting['apple_cert_path'];
        $passphrase = self::$apisetting['apple_passphrase'];
        $appid = self::$apisetting['apple_appid'];
        if (self::$apisetting['apple_sandbox'] == 1) {
          $serverAPNS = 'https://api.development.push.apple.com/3/device/';
        }
        else {
          $serverAPNS = 'https://api.push.apple.com/3/device/';
        }

        if(self::$apisetting['apple_cert_type'] == 'pem'){
          $reqHeader = array('apns-topic: '.$appid);
          curl_setopt($chandle, CURLOPT_SSLCERT, $cert);
          curl_setopt($chandle, CURLOPT_SSLCERTPASSWD, $passphrase);
          curl_setopt($chandle, CURLOPT_HTTPHEADER, $reqHeader);
        }
        elseif(self::$apisetting['apple_cert_type'] == 'p8'){
          require_once(smpush_dir.'/lib/inc_jwt_helper.php');
          $helper = new smpush_helper();

          if(file_exists(smpush_cache_dir.'/jwt_header') && filemtime(smpush_cache_dir.'/jwt_header') > (time()-3600)){
            $header_jwt = $helper->readlocalfile(smpush_cache_dir.'/jwt_header');
          }
          else{
            $arParam = array();
            $arParam['teamId'] = self::$apisetting['apple_teamid'];
            $arParam['authKeyId'] = self::$apisetting['apple_keyid'];
            $arParam['apns-topic'] = $appid;
            $arClaim = [ 'iss' => $arParam['teamId'], 'iat'=>time() ];
            $arParam['p_key'] = $helper->readlocalfile(self::$apisetting['apple_certp8_path']);
            try {
              $header_jwt = smpushJWT::encode($arClaim, $arParam['p_key'], $arParam['authKeyId'], 'RS256');
            } catch (Exception $e) {
              return('iOS authentication error: '.$e->getMessage());
            }
            $helper->storelocalfile(smpush_cache_dir.'/jwt_header', $header_jwt);
          }

          $reqHeader = array('apns-topic: '.$appid, 'authorization: bearer '.$header_jwt);
          curl_setopt($chandle, CURLOPT_HTTPHEADER, $reqHeader);
        }

        curl_setopt($chandle, CURLOPT_URL, $serverAPNS.$_POST['ios_token']);
        curl_setopt($chandle, CURLOPT_PORT, 443);
        curl_setopt($chandle, CURLOPT_POST, true);
        curl_setopt($chandle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($chandle, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($chandle, CURLOPT_POSTFIELDS, $payload);
        curl_setopt($chandle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
        //curl_setopt($chandle, CURLOPT_SSLVERSION, 393216);
        if(defined('WP_PROXY_HOST')){
          curl_setopt($chandle, CURLOPT_PROXY, WP_PROXY_HOST);
          curl_setopt($chandle, CURLOPT_PROXYPORT, WP_PROXY_PORT);
          curl_setopt($chandle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
          if(defined('WP_PROXY_USERNAME')){
            curl_setopt($chandle, CURLOPT_PROXYUSERPWD, WP_PROXY_USERNAME.':'.WP_PROXY_PASSWORD);
            curl_setopt($chandle, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
          }
        }
        $response = curl_exec($chandle);
        $httpcode = curl_getinfo($chandle, CURLINFO_HTTP_CODE);
        curl_close($chandle);

        if (!empty($response)) {
          $response = json_decode($response, true);
        }
        $applelog = '';

        switch ($httpcode) {
          case 200:
            $applelog = esc_html__('Connected successfully with Apple server', 'smio-push-notification')."\n".esc_html__('If you did not receive any message please check again your certification file and mobile code', 'smio-push-notification');
            break;
          case 0:
            $applelog = 'Server must be installed CURL version >= 7.46 and OpenSSL version >= 1.0.2e with HTTP/2 enabled';
            break;
          default:
            $applelog = esc_html__('Connected successfully with Apple server and received an error', 'smio-push-notification')."\n".$response['reason'];
            break;
        }
      }
      if (!empty($_POST['android_token'])) {
        if (function_exists('curl_init')) {
          $url = 'https://fcm.googleapis.com/fcm/send';
          if (self::$apisetting['fcm_compatibility'] == 'titanium') {
            $data = array();
            $data['payload']['android']['alert'] = $message;
          }
          elseif (self::$apisetting['fcm_compatibility'] == 'corona') {
            $data = array();
            $data['alert'] = $message;
          }
          elseif(self::$apisetting['fcm_compatibility'] == 'fcm_notification'){
            $data = array('message' => $message);
            $notification = array();
            $notification['body'] = $message;
            $notification['title'] = self::$apisetting['android_title'];
          }
          elseif(self::$apisetting['fcm_compatibility'] == 'expo'){
            $data['message'] = $message;
            $data['title'] = self::$apisetting['android_title'];
          }
          else {
            $data = array('message' => $message);
          }
          $fields = array('registration_ids' => array($_POST['android_token']), 'data' => $data);
          if(self::$apisetting['fcm_compatibility'] == 'fcm_notification'){
            $fields['notification'] = $notification;
          }
          $headers = array('Authorization: key='.self::$apisetting['google_apikey'], 'Content-Type: application/json');
          $ch = curl_init();
          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_SSL_VERIFYPEER, false);
          curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields, defined('JSON_UNESCAPED_UNICODE') ? JSON_UNESCAPED_UNICODE : 0));
          if(defined('WP_PROXY_HOST')){
            curl_setopt($ch, CURLOPT_PROXY, WP_PROXY_HOST);
            curl_setopt($ch, CURLOPT_PROXYPORT, WP_PROXY_PORT);
            curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
            if(defined('WP_PROXY_USERNAME')){
              curl_setopt($ch, CURLOPT_PROXYUSERPWD, WP_PROXY_USERNAME.':'.WP_PROXY_PASSWORD);
              curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
            }
          }
          $result = curl_exec($ch);
          if ($result === false) {
            $googlelog = 'Curl failed: '.curl_error($ch);
          } else {
            $googlelog = $result;
          }
          curl_close($ch);
        } else {
          $googlelog = esc_html__('CURL Library is not support in your host', 'smio-push-notification');
        }
      }
      echo '<h3>'.esc_html__('Apple Response', 'smio-push-notification').'</h3><p><pre class="smpush_pre">'.$applelog.'</pre></p><h3>'.esc_html__('Google Response', 'smio-push-notification').'</h3><p><pre class="smpush_pre">'.$googlelog.'</pre></p>';
    } else {
      include(smpush_dir.'/pages/test_sending.php');
    }
  }

  public static function connections() {
    global $wpdb;
    self::load_jsplugins();
    $pageurl = admin_url().'admin.php?page=smpush_connections';
    if ($_POST) {
      require(smpush_dir.'/lib/validation/autoload.php');
      $validator = new Validator;
      $validation = $validator->make($_POST, [
        'title' => 'required|max:50',
        'type' => 'in:localhost,remote',
        'dbhost' => 'required_if:type,remote',
        'dbname' => 'required_if:type,remote',
        'dbuser' => 'required_if:type,remote',
        'dbpass' => 'required_if:type,remote',
        'tbname' => 'required',
        'id_name' => 'required',
        'token_name' => 'required',
        'md5token_name' => 'required',
        'active_name' => 'required',
        'firebase_name' => 'required',
        'latitude_name' => 'required',
        'longitude_name' => 'required',
        'gpstime_name' => 'required',
        'geotimeout_name' => 'required',
        'info_name' => 'required',
        'postdate' => 'required',
        'counter_name' => 'required',
        'type_name' => 'required',
        'ios_name' => 'required',
        'iosfcm_name' => 'required',
        'android_name' => 'required',
        'wp_name' => 'required',
        'wp10_name' => 'required',
        'bb_name' => 'required',
        'chrome_name' => 'required',
        'safari_name' => 'required',
        'firefox_name' => 'required',
        'opera_name' => 'required',
        'edge_name' => 'required',
        'samsung_name' => 'required',
        'viber_name' => 'required',
        'fbmsn_name' => 'required',
        'fbnotify_name' => 'required',
        'email_name' => 'required',
      ]);
      $validation->validate();
      if ($validation->fails()) {
        $errors = $validation->errors();
        self::jsonPrint('validation', $errors->all());
      }

      extract($_POST);
      if (empty($title)) {
        self::jsonPrint(0, esc_html__('Field title is required.', 'smio-push-notification'));
      }
      if ($type == 'remote') {
        if (function_exists('mysqli_connect')) {
          $testlink = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
          if ($testlink->connect_errno) {
            self::jsonPrint(0, esc_html__('Could not connect with remote database error', 'smio-push-notification').': '.$testlink->connect_error);
          }
        } else {
          $testlink = mysql_connect($dbhost, $dbuser, $dbpass, $dbname);
          if (!$testlink) {
            self::jsonPrint(0, esc_html__('Could not connect with remote database error', 'smio-push-notification').': '.mysql_error());
          }
        }
        $pushdb = new wpdb($dbuser, '', $dbname, $dbhost);
      } else {
        $pushdb = $wpdb;
      }
      $pushdb->hide_errors();
      $_tbname = str_replace('{wp_prefix}', $wpdb->prefix, $tbname);
      $count = $pushdb->get_var("SELECT COUNT($id_name) FROM `$_tbname`");
      if ($count === null) {
        self::jsonPrint(0, esc_html__('Table or ID name column is wrong', 'smio-push-notification'));
      }
      $test = $pushdb->get_row("SELECT COUNT($token_name) FROM `$_tbname` LIMIT 0,1");
      if ($test === null) {
        self::jsonPrint(0, esc_html__('Device Token column is wrong', 'smio-push-notification'));
      }
      $test = $pushdb->get_row("SELECT COUNT($md5token_name) FROM `$_tbname` LIMIT 0,1");
      if ($test === null) {
        self::jsonPrint(0, esc_html__('MD5 Device Token column is wrong', 'smio-push-notification'));
      }
      $test = $pushdb->get_row("SELECT COUNT($id_name) FROM `$_tbname` WHERE `$type_name`='$ios_name' OR `$type_name`='$iosfcm_name' OR `$type_name`='$android_name' OR `$type_name`='$wp_name' OR `$type_name`='$wp10_name' OR `$type_name`='$bb_name' OR `$type_name`='$chrome_name' OR `$type_name`='$safari_name' OR `$type_name`='$firefox_name' OR `$type_name`='$opera_name' OR `$type_name`='$edge_name' OR `$type_name`='$samsung_name' OR `$type_name`='$fbmsn_name' OR `$type_name`='$viber_name' OR `$type_name`='$fbnotify_name' OR `$type_name`='$email_name' LIMIT 0,1");
      if ($test === null) {
        self::jsonPrint(0, esc_html__('Type column or Device type values is wrong', 'smio-push-notification'));
      }
      if (!empty($info_name)) {
        $test = $pushdb->get_row("SELECT COUNT($info_name) FROM `$_tbname` LIMIT 0,1");
        if ($test === null) {
          self::jsonPrint(0, esc_html__('Information column name is wrong', 'smio-push-notification'));
        }
      } else {
        $info_name = 'information';
        $pushdb->query("ALTER TABLE `$_tbname` ADD `$info_name` TINYTEXT NOT NULL");
      }
      if (!empty($active_name)) {
        $test = $pushdb->get_row("SELECT COUNT($active_name) FROM `$_tbname` LIMIT 0,1");
        if ($test === null) {
          self::jsonPrint(0, esc_html__('Active column name is wrong', 'smio-push-notification'));
        }
      } else {
        $active_name = 'active';
        $pushdb->query("ALTER TABLE `$_tbname` ADD `$active_name` BOOLEAN NOT NULL");
        $pushdb->query("UPDATE `$_tbname` SET `$active_name`='1'");
      }
      if (!empty($firebase_name)) {
        $test = $pushdb->get_row("SELECT COUNT($firebase_name) FROM `$_tbname` LIMIT 0,1");
        if ($test === null) {
          self::jsonPrint(0, esc_html__('Firebase column name is wrong', 'smio-push-notification'));
        }
      } else {
        $firebase_name = 'firebase';
        $pushdb->query("ALTER TABLE `$_tbname` ADD `$firebase_name` BOOLEAN NOT NULL");
        $pushdb->query("UPDATE `$_tbname` SET `$firebase_name`='0'");
      }
      if (!empty($latitude_name)) {
        $test = $pushdb->get_row("SELECT COUNT($latitude_name) FROM `$_tbname` LIMIT 0,1");
        if ($test === null) {
          self::jsonPrint(0, esc_html__('Latitude column name is wrong', 'smio-push-notification'));
        }
      } else {
        $latitude_name = 'latitude';
        $pushdb->query("ALTER TABLE `$_tbname` ADD `$latitude_name` DECIMAL(10, 8) NOT NULL");
      }
      if (!empty($longitude_name)) {
        $test = $pushdb->get_row("SELECT COUNT($longitude_name) FROM `$_tbname` LIMIT 0,1");
        if ($test === null) {
          self::jsonPrint(0, esc_html__('Longitude column name is wrong', 'smio-push-notification'));
        }
      } else {
        $longitude_name = 'longitude';
        $pushdb->query("ALTER TABLE `$_tbname` ADD `$longitude_name` DECIMAL(11, 8) NOT NULL");
      }
      if (!empty($gpstime_name)) {
        $test = $pushdb->get_row("SELECT COUNT($gpstime_name) FROM `$_tbname` LIMIT 0,1");
        if ($test === null) {
          self::jsonPrint(0, esc_html__('GPS update time column name is wrong', 'smio-push-notification'));
        }
      } else {
        $gpstime_name = 'gps_time_update';
        $pushdb->query("ALTER TABLE `$_tbname` ADD `$gpstime_name` VARCHAR(15) NOT NULL");
      }
      if (!empty($geotimeout_name)) {
        $test = $pushdb->get_row("SELECT COUNT($geotimeout_name) FROM `$_tbname` LIMIT 0,1");
        if ($test === null) {
          self::jsonPrint(0, esc_html__('GPS timeout column name is wrong', 'smio-push-notification'));
        }
      } else {
        $geotimeout_name = 'geotimeout_name';
        $pushdb->query("ALTER TABLE `$_tbname` ADD `$geotimeout_name` VARCHAR(15) NOT NULL");
      }
      $test = $pushdb->get_row("SELECT COUNT(`userid`) FROM `$_tbname` LIMIT 0,1");
      if ($test === null) {
        $pushdb->query("ALTER TABLE `$_tbname` ADD `userid` INT NOT NULL");
      }
      $test = $pushdb->get_row("SELECT COUNT(`timepost`) FROM `$_tbname` LIMIT 0,1");
      if ($test === null) {
        $pushdb->query("ALTER TABLE `$_tbname` ADD `timepost` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP");
      }
      if (!empty($postdate)) {
        $test = $pushdb->get_row("SELECT COUNT($postdate) FROM `$_tbname` LIMIT 0,1");
        if ($test === null) {
          self::jsonPrint(0, esc_html__('Added time column name is wrong', 'smio-push-notification'));
        }
      } else {
        $postdate = 'timepost';
        $pushdb->query("ALTER TABLE `$_tbname` ADD `$postdate` VARCHAR(15) NOT NULL");
      }
      if (!empty($counter_name)) {
        $test = $pushdb->get_row("SELECT COUNT($counter_name) FROM `$_tbname` LIMIT 0,1");
        if ($test === null) {
          self::jsonPrint(0, esc_html__('Added counter column name is wrong', 'smio-push-notification'));
        }
      } else {
        $counter_name = 'counter';
        $pushdb->query("ALTER TABLE `$_tbname` ADD `$counter_name` SMALLINT NOT NULL");
      }
      $test = $pushdb->get_row("SELECT COUNT(`receive_again_at`) FROM `$_tbname` LIMIT 0,1");
      if ($test === null) {
        $pushdb->query("ALTER TABLE `$_tbname` ADD `receive_again_at` VARCHAR(15) NOT NULL DEFAULT '0'");
      }
      $data = array(
      'title' => $title,
      'description' => $description,
      'dbtype' => $type,
      'dbhost' => $dbhost,
      'dbname' => $dbname,
      'dbuser' => $dbuser,
      'dbpass' => $dbpass,
      'tbname' => $tbname,
      'id_name' => $id_name,
      'token_name' => $token_name,
      'md5token_name' => $md5token_name,
      'type_name' => $type_name,
      'ios_name' => $ios_name,
      'iosfcm_name' => $iosfcm_name,
      'android_name' => $android_name,
      'wp_name' => $wp_name,
      'wp10_name' => $wp10_name,
      'bb_name' => $bb_name,
      'chrome_name' => $chrome_name,
      'firefox_name' => $firefox_name,
      'safari_name' => $safari_name,
      'opera_name' => $opera_name,
      'edge_name' => $edge_name,
      'samsung_name' => $samsung_name,
      'fbmsn_name' => $fbmsn_name,
      'viber_name' => $viber_name,
      'fbnotify_name' => $fbnotify_name,
      'email_name' => $email_name,
      'info_name' => $info_name,
      'active_name' => $active_name,
      'firebase_name' => $firebase_name,
      'latitude_name' => $latitude_name,
      'longitude_name' => $longitude_name,
      'gpstime_name' => $gpstime_name,
      'geotimeout_name' => $geotimeout_name,
      'counter_name' => $counter_name,
      'postdate' => $postdate,
      'counter' => $count
      );
      $dataTypes = array_fill(0, count($data), '%s');
      if ($id > 0) {
        $wpdb->update($wpdb->prefix.'push_connection', $data, array('id' => $id), $dataTypes, ['%d']);
      } else {
        $wpdb->insert($wpdb->prefix.'push_connection', $data, $dataTypes);
      }
      echo 1;
      exit;
    } elseif (isset($_GET['delete'])) {
      $wpdb->query($wpdb->prepare("DELETE FROM ".$wpdb->prefix."push_connection WHERE id=%d", [ $_GET['id'] ]));
      $wpdb->query($wpdb->prepare("DELETE FROM ".$wpdb->prefix."push_relation WHERE connection_id=%d", [ $_GET['id'] ]));
      wp_redirect($pageurl);
    } elseif (isset($_GET['id'])) {
      if ($_GET['id'] == -1) {
        $connection = array('id' => 0, 'title' => '', 'description' => '', 'dbtype' => '', 'dbhost' => '', 'dbname' => '', 'dbuser' => '', 'dbpass' => '', 'tbname' => '', 'token_name' => '', 'md5token_name' => '', 'type_name' => '', 'ios_name' => '', 'iosfcm_name' => '', 'android_name' => '', 'bb_name' => '', 'wp_name' => '', 'wp10_name' => '', 'chrome_name' => '', 'safari_name' => '', 'firefox_name' => '', 'opera_name' => '', 'edge_name' => '', 'samsung_name' => '', 'viber_name' => '', 'fbmsn_name' => '', 'fbnotify_name' => '', 'email_name' => '', 'id_name' => '', 'info_name' => '', 'active_name' => '', 'firebase_name' => '', 'counter_name' => '', 'latitude_name' => '', 'longitude_name' => '', 'gpstime_name' => '', 'geotimeout_name' => '');
      } else {
        $connection = $wpdb->get_row($wpdb->prepare("SELECT * FROM ".$wpdb->prefix."push_connection WHERE id=%d", [ $_GET['id'] ]), 'ARRAY_A');
        $connection = array_map('stripslashes', $connection);
      }
      include(smpush_dir.'/pages/connection_form.php');
      exit;
    } else {
      $connections = $wpdb->get_results("SELECT id,title,description,counter FROM ".$wpdb->prefix."push_connection ORDER BY id DESC");
      include(smpush_dir.'/pages/connection_manage.php');
    }
  }

}
