<?php

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

add_action('save_post', array('smio_auto_channel_class', 'update_preset_meta'), 10, 2);
add_action('save_page', array('smio_auto_channel_class', 'update_preset_meta'), 10, 2);
add_action('add_meta_boxes', array('smio_auto_channel_class', 'build_meta_box'));
add_action('template_redirect', array('smio_auto_channel_class', 'listen_on_landings'));
add_action('smpush_new_subscriber_presaved', array('smio_auto_channel_class', 'new_subscriber'), 99, 2);

class smio_auto_channel_class
{

  function __construct(){}

  public static function listen_on_landings(){
    if(is_single()){
      if(empty($_COOKIE['smpush_auto_channel_landing'])){
        setcookie('smpush_auto_channel_landing', get_the_ID(), (time() + 2592000), COOKIEPATH);
      }
    }
  }

  public static function update_preset_meta($postid, $post){
    if(isset($_POST['smpush_auto_preset_channels'])){
      update_post_meta($postid, 'smpush_auto_preset_channels', serialize($_POST['smpush_auto_preset_channels']));
    }
  }

  public static function new_subscriber($token, $device_type){
    if(!empty($_COOKIE['smpush_auto_channel_landing'])){
      $postid = intval($_COOKIE['smpush_auto_channel_landing']);
      $auto_channels = unserialize(get_post_meta($postid, 'smpush_auto_preset_channels', true));
      if(!empty($auto_channels)){
        $_REQUEST['channels_id'] = implode(',', $auto_channels);
      }
    }
  }

  public static function build_meta_box(){
    add_meta_box('smpush-meta-box-auto-channel', esc_html__('Auto Channel Subscribe', 'smio-push-notification'), 'smio_auto_channel_meta_box_design', null, 'side', 'high');
  }
}

function smio_auto_channel_meta_box_design($post){
  global $wpdb;
  $channels = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'push_channels ORDER BY title ASC');
  $auto_channels = unserialize(get_post_meta(get_the_ID(), 'smpush_auto_preset_channels', true));
  if(empty($auto_channels)){
    $auto_channels = array();
  }
  ?>
  <table>
    <tbody>
    <tr valign="middle">
      <td>
        <ul class="categorychecklist form-no-clear" style="margin: 0">
          <?php foreach($channels as $channel): ?>
            <li><label class="selectit"><input value="<?php echo esc_attr($channel->id); ?>" <?php if(in_array($channel->id, $auto_channels)): ?>checked="checked"<?php endif; ?> type="checkbox"
                                               name="smpush_auto_preset_channels[]"> <?php echo esc_attr($channel->title); ?> (<?php echo esc_attr($channel->count); ?>)</label></li>
          <?php endforeach; ?>
        </ul>
      </td>
    </tr>
    </tbody>
  </table>
  <?php
}

?>
