<?php

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

use Rakit\Validation\Validator;

class smpush_event_manager extends smpush_controller {

  public function __construct() {
    parent::__construct();
  }

  public static function page() {
    global $wpdb;
    self::load_jsplugins();
    $pageurl = admin_url().'admin.php?page=smpush_events';
    if ($_POST) {
      require(smpush_dir.'/lib/validation/autoload.php');
      $validator = new Validator;
      $validation = $validator->make($_POST, [
        'title' => 'required',
        'event_type' => 'required',
        'event_post_type' => 'required',
        'msg_template' => 'nullable|integer',
        'subject' => 'required',
        'message' => 'required',
        'fbmsn_message' => 'required',
        'fbnotify_message' => 'required',
        'email_message' => 'required',
        'viber_message' => 'required',
        'notify_segment' => 'required',
      ]);
      $validation->validate();
      if ($validation->fails()) {
        $errors = $validation->errors();
        self::jsonPrint('validation', $errors->all());
      }

      if(smpush_env_demo){
        echo 1;
        exit;
      }
      if (empty($_POST['title']) || empty($_POST['message']) || empty($_POST['event_post_type'])) {
        self::jsonPrint(0, esc_html__('All fields are required.', 'smio-push-notification'));
      }
      $conditions = array();
      foreach($_POST['conditions']['attri'] as $key => $value){
        if(!empty($_POST['conditions']['attri'][$key]) && !empty($_POST['conditions']['sign'][$key])){
          $conditions['attri'][$key] = $_POST['conditions']['attri'][$key];
          $conditions['sign'][$key] = $_POST['conditions']['sign'][$key];
          $conditions['value'][$key] = $_POST['conditions']['value'][$key];
        }
      }
      $data = array();
      $data['title'] = $_POST['title'];
      $data['event_type'] = $_POST['event_type'];
      $data['post_type'] = $_POST['event_post_type'];
      $data['subject'] = $_POST['subject'];
      $data['message'] = $_POST['message'];
      $data['viber_message'] = $_POST['viber_message'];
      $data['fbmsn_message'] = $_POST['fbmsn_message'];
      $data['fbnotify_message'] = $_POST['fbnotify_message'];
      $data['email_message'] = $_POST['email_message'];
      $data['subs_filter'] = $_POST['subs_filter'];
      $data['notify_segment'] = $_POST['notify_segment'];
      $data['userid_field'] = $_POST['userid_field'];
      $data['msg_template'] = $_POST['msg_template'];
      $data['conditions'] = (empty($conditions))? '' : serialize($conditions);
      $data['payload_fields'] = (empty($_POST['payload']))? '' : serialize($_POST['payload']);
      $data['once_notify'] = (isset($_POST['once_notify']))? 1 : 0;
      $data['desktop_link'] = (isset($_POST['desktop_link']))? 1 : 0;
      $data['email'] = (isset($_POST['email']))? 1 : 0;
      $data['status'] = (isset($_POST['status']))? 1 : 0;
      $data['ignore'] = (isset($_POST['ignore']))? 1 : 0;
      if (!empty($_POST['id'])) {
        $wpdb->update($wpdb->prefix.'push_events', $data, array('id' => $_POST['id']), ['%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%d','%d','%d','%d','%d'], ['%d']);
      } else {
        $wpdb->insert($wpdb->prefix.'push_events', $data, ['%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%d','%d','%d','%d','%d']);
      }
      echo 1;
      exit;
    }
    elseif (isset($_GET['loadAttri'])) {
      $post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_type=%s LIMIT 0,1", [ $_GET['smpush_post_type'] ]), 'ARRAY_A');
      if(empty($post)){
        echo json_encode(array('status' => 0));
        exit;
      }
      $selcOptions = '<option value="">'.esc_html__('Choose Attribute', 'smio-push-notification').'</option><optgroup label="'.esc_html__('Post Attributes', 'smio-push-notification').'">';
      foreach($post as $column => $value){
        $selcOptions .= '<option>'.$column.'</option>';
      }
      $selcOptions .= '</optgroup>';
      $postIDs = $wpdb->get_row($wpdb->prepare("SELECT GROUP_CONCAT(ID SEPARATOR ',') AS ids FROM $wpdb->posts WHERE post_type=%s ORDER BY ID DESC LIMIT 0,1000", [ $_GET['smpush_post_type'] ]), 'ARRAY_A');
      $postIDs['ids'] = rtrim($postIDs['ids'], ',');
      $metakeys = $wpdb->get_results("SELECT DISTINCT(meta_key) AS meta_key FROM $wpdb->postmeta WHERE post_id IN($postIDs[ids])", 'ARRAY_A');
      $selcOptions .= '<optgroup label="'.esc_html__('Postmeta Attributes', 'smio-push-notification').'">';
      foreach($metakeys as $metakey){
        $selcOptions .= '<option value="meta_'.$metakey['meta_key'].'">'.$metakey['meta_key'].'</option>';
      }
      $selcOptions .= '</optgroup>';
      
      $postFuncs = '<option value="">'.esc_html__('Pass Any ID To Function And Get', 'smio-push-notification').'</option>
      <optgroup label="'.esc_html__('Post Functions', 'smio-push-notification').'">
        <option value="post_title">'.esc_html__('Title', 'smio-push-notification').'</option>
        <option value="post_content">'.esc_html__('Content', 'smio-push-notification').'</option>
        <option value="post_permalink">'.esc_html__('Permalink', 'smio-push-notification').'</option>
        <option value="post_date">'.esc_html__('Publish Date', 'smio-push-notification').'</option>
        <option value="post_mod_date">'.esc_html__('Last Update Date', 'smio-push-notification').'</option>
        <option value="post_categories">'.esc_html__('Categories', 'smio-push-notification').'</option>
        <option value="post_categories_ids">'.esc_html__('Categories IDs', 'smio-push-notification').'</option>
        <option value="post_tags">'.esc_html__('Tags', 'smio-push-notification').'</option>
        <option value="post_thumbnail">'.esc_html__('Post Thumbnail', 'smio-push-notification').'</option>
      </optgroup>
      <optgroup label="'.esc_html__('User Functions', 'smio-push-notification').'">
        <option value="user_title">'.esc_html__('Display Name', 'smio-push-notification').'</option>
        <option value="user_title_fpost">'.esc_html__('Display Name Using Post ID', 'smio-push-notification').'</option>
        <option value="user_email">'.esc_html__('Email', 'smio-push-notification').'</option>
        <option value="user_name">'.esc_html__('Username', 'smio-push-notification').'</option>
      </optgroup>
      <optgroup label="'.esc_html__('Time Functions', 'smio-push-notification').'">
        <option value="format_date">'.esc_html__('Format Date', 'smio-push-notification').'</option>
        <option value="remain_time">'.esc_html__('Remaining Time', 'smio-push-notification').'</option>
      </optgroup>';
      $taxs = get_object_taxonomies($_GET['smpush_post_type'], 'names');
      if(!empty($taxs)){
        $postFuncs .= '<optgroup label="'.esc_html__('Taxonomies Return IDs', 'smio-push-notification').'">';
        foreach($taxs as $tax){
          $postFuncs .= '<option>'.$tax.'</option>';
        }
        $postFuncs .= '</optgroup>';
      }
      
      if(!empty($taxs)){
        $selcOptions .= '<optgroup label="'.esc_html__('Taxonomies IDs', 'smio-push-notification').'">';
        foreach($taxs as $tax){
          $selcOptions .= '<option value="tax_func_'.$tax.'">'.$tax.'</option>';
        }
        $selcOptions .= '</optgroup>';
      }
      
      $html = array('status' => 1, 'postAttrs' => $selcOptions, 'postFuncs' => $postFuncs);
      echo json_encode($html);
      exit;
    }
    elseif (isset($_GET['delete'])) {
      if(smpush_env_demo){
        echo 1;
        exit;
      }
      $wpdb->query($wpdb->prepare("DELETE FROM ".$wpdb->prefix."push_events WHERE id=%d", [ $_GET['id'] ]));
      wp_redirect($pageurl);
    }
    elseif (isset($_GET['id'])) {
      if ($_GET['id'] == -1) {
        $event = array('id' => 0, 'title' => '', 'event_type' => '1', 'msg_template' => 0, 'post_type' => '', 'subject' => '', 'message' => '', 'viber_message' => '', 'fbmsn_message' => '', 'fbnotify_message' => '', 'email_message' => '', 'notify_segment' => 'all', 'subs_filter' => 'all', 'userid_field' => '', 'desktop_link' => 1, 'once_notify' => 0, 'email' => 0, 'status' => 1, 'ignore' => 0);
      }
      else {
        $event = $wpdb->get_row($wpdb->prepare("SELECT * FROM ".$wpdb->prefix."push_events WHERE id=%d", [ $_GET['id'] ]), 'ARRAY_A');
        $event['conditions'] = unserialize($event['conditions']);
        $event['payload_fields'] = unserialize($event['payload_fields']);
        $event = stripslashes_deep($event);
      }
      $templates = $wpdb->get_results("SELECT id,name FROM ".$wpdb->prefix."push_archive WHERE send_type='template' ORDER BY id ASC", 'ARRAY_A');
      include(smpush_dir.'/pages/event_form.php');
      exit;
    }
    else {
      $events = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."push_events ORDER BY id ASC");
      wp_enqueue_script('jquery-ui-tabs');
      wp_enqueue_style('smpush-jquery-smoothness');
      include(smpush_dir.'/pages/event_manage.php');
    }
  }
  
}
