<?php

/**
 * Author: wbolt team
 * Author URI: https://www.wbolt.com
 */

class WB_MagicPost_Enhance extends WB_MagicPost_Base
{
  private static $option_name = 'magicpost_enhance_option';

  public function __construct()
  {

    if (is_admin()) {
      add_action('wp_ajax_magicpost', array($this, 'magicpost_ajax'));
    }

    $switch = self::opt('enhance_switch', 1);
    if (!$switch || !get_option('wb_magicpost_ver', 0)) {
      return;
    }
    $opt = self::opt();
    //update current time
    if (!empty($opt['publish_time'])) {
      add_action('post_submitbox_misc_actions', array($this, 'action_post_submitbox_misc_actions'));
      add_filter('wp_insert_post_data', array($this, 'filter_wp_insert_post_data'), 10, 4);
    }
    //clone
    if (!empty($opt['clone_post']) && is_admin()) {
      add_filter('post_row_actions', array($this, 'post_row_actions'), 99, 2);
    }

    //auto slug
    if (!empty($opt['auto_slug']) && is_admin()) {

      add_action('save_post', array($this, 'generate_post_name_from_title'), 10, 2);
    }

    //search replace window
    if (!empty($opt['search_replace_window']) && is_admin()) {
      add_action('media_buttons', array($this, 'add_search_replace_button'), 20);
      add_action('admin_enqueue_scripts', array($this, 'admin_enqueue_scripts'));
    }
  }

  public function admin_enqueue_scripts()
  {
    add_editor_style(MAGICPOST_URI . 'assets/wbp_tinymce_search_replace.css');
    wp_enqueue_script('wbp-search-replace', MAGICPOST_URI . 'assets/search-replace.js', [], MAGICPOST_VERSION, true);
  }

  public function add_search_replace_button()
  {
    echo '<button id="wb-search-replace-btn" type="button" class="button wb-wbsm-btn"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M18.031 16.6168L22.3137 20.8995L20.8995 22.3137L16.6168 18.031C15.0769 19.263 13.124 20 11 20C6.032 20 2 15.968 2 11C2 6.032 6.032 2 11 2C15.968 2 20 6.032 20 11C20 13.124 19.263 15.0769 18.031 16.6168ZM16.6589 9C15.8357 6.66906 13.6136 5 11 5C7.685 5 5 7.685 5 11H7C7 8.792 8.792 7 11 7C11.6912 7 12.3417 7.17563 12.9092 7.48467L12 9H16.6589ZM17 11H15C15 13.208 13.208 15 11 15C10.3088 15 9.65828 14.8244 9.0908 14.5153L10 13H7.53567H5.34109C6.16433 15.3309 8.38635 17 11 17C14.315 17 17 14.315 17 11Z"></path></svg><span>' . _x('搜索替换', 'admin, btn', WB_MAGICPOST_TD) . '</span></button>';
  }

  public function generate_post_name_from_title($post_id, $post)
  {
    if (wp_is_post_revision($post_id)) return;

    // Skip if post_name is already set and not empty
    if (!empty($post->post_name) || empty($post->post_title)) return;
    $excluded_types = array('attachment', 'revision', 'nav_menu_item');
    if (in_array($post->post_type, $excluded_types)) return;
    $translate = new WB_MagicPost_Translate();
    if (!$translate->can_use()) {
      return;
    }
    $post_title = $translate->title_to_name($post->post_title, $post);
    if (empty($post_title)) {
      return;
    }
    $slug = sanitize_title($post_title);

    // Make sure the slug is unique
    $slug = wp_unique_post_slug($slug, $post_id, $post->post_status, $post->post_type, $post->post_parent);

    // Update the post_name
    global $wpdb;
    $wpdb->update(
      $wpdb->posts,
      array('post_name' => $slug),
      array('ID' => $post_id),
      array('%s'),
      array('%d')
    );
  }
  public function post_row_actions($actions, $post)
  {
    static $has_inline_js = false;
    if (!current_user_can('edit_post', $post->ID)) {
      return $actions;
    }

    if (!$has_inline_js) {
      $has_inline_js = true;
      $nonce = wp_create_nonce('wp_ajax_wb_magicpost');
      $js = array();
      $js[] = "jQuery('a.magicpos_enhance_action').on('click',function(){var obj = jQuery(this);";
      $js[] = "jQuery.post(ajaxurl,{_ajax_nonce:'" . $nonce . "',action:'magicpost','op':'enhance_clone',post_id:obj.data('post_id')},function(ret){";
      $js[] = "if(ret){obj.parents('tr').find('.row-title').parent().append(ret); }obj.remove();";
      $js[] = "});return false;});";

      wp_add_inline_script('wp-auth-check', implode('', $js));
    }
    $actions['magicpos_enhance_action'] = '<a class="magicpos_enhance_action" data-post_id="' . $post->ID . '" href="javascript:;">' . __('克隆', WB_MAGICPOST_TD) . '</a>';
    return $actions;
  }

  public function action_post_submitbox_misc_actions($post)
  {
    echo '<div style="padding:10px;"><label><input type="checkbox" name="use_current_time" value="1">' . __('发布时间变更为当前时间', 'admin, post', WB_MAGICPOST_TD) . '</label></div>';
  }

  public function filter_wp_insert_post_data($data, $postarr, $unsanitized_postarr, $update = false)
  {
    if (!$update) {
      return $data;
    }
    if (!isset($data['post_type'])) {
      return $data;
    }
    if (!isset($postarr['use_current_time']) || !$postarr['use_current_time']) {
      return $data;
    }
    $data['post_date'] = current_time('mysql');
    $data['post_date_gmt'] = current_time('mysql', 1);
    //error_log(print_r($data,true)."\n",3,__DIR__.'/log.txt');
    return $data;
  }

  /**
   * 管理设置
   */
  public function magicpost_ajax()
  {


    $op = trim(self::param('op'));
    if (!$op) {
      return;
    }
    $arrow = [
      'enhance_setting',
      'enhance_update',
      'enhance_clone',
    ];

    if (!in_array($op, $arrow)) {
      return;
    }

    if (!current_user_can('manage_options')) {
      self::ajax_resp(['code' => 1, 'desc' => 'deny']);
      return;
    }

    if (!wp_verify_nonce(sanitize_text_field(self::param('_ajax_nonce')), 'wp_ajax_wb_magicpost')) {
      self::ajax_resp(['code' => 1, 'desc' => 'illegal']);
      return;
    }
    switch ($op) {
      case 'enhance_clone':
        $message = __('克隆失败', WB_MAGICPOST_TD);
        do {
          $id = intval(self::param('post_id', 0));
          if (!$id) {
            break;
          }
          if (!current_user_can('edit_post', $id) || wp_is_post_revision($id)) {
            break;
          }
          $state = $this->clone_post($id);
          if (!$state) {
            break;
          }
          $message = __('克隆成功', WB_MAGICPOST_TD);
        } while (0);
        echo '[' . $message . ']';
        exit();
        break;
      case 'enhance_setting':
        $ret = ['code' => 1];

        do {
          $ret['cnf'] = WB_MagicPost::get_fields('enhance');
          $ret['opt'] = self::opt();

          $ret['code'] = 0;
          $ret['desc'] = 'success';
        } while (0);

        self::ajax_resp($ret);

        break;

      case 'enhance_update':
        $ret = ['code' => 1];
        do {
          $opt = $this->sanitize_text_field_array(self::param('opt', []));
          if (empty($opt) || !is_array($opt)) {
            $ret['desc'] = 'illegal';
            break;
          }
          update_option(self::$option_name, $opt);

          $ret['code'] = 0;
          $ret['desc'] = 'success';
        } while (0);

        self::ajax_resp($ret);
        break;
    }
  }

  public function clone_post($post_id)
  {
    global $wpdb;

    $post_id = intval($post_id);

    //, `post_date`, `post_date_gmt`, `post_modified`, `post_modified_gmt`
    $post_field = ['`post_author`, `post_content`, `post_title`, `post_excerpt`, `post_status`'];
    $post_field[] = '`post_password`, `post_parent`, `post_type`, `comment_status`, `ping_status`, `to_ping`, `menu_order`';
    $field = implode(',', $post_field);
    $row = $wpdb->get_row($wpdb->prepare("SELECT $field FROM $wpdb->posts WHERE ID = %d", $post_id), ARRAY_A);
    if (!$row) {
      return false;
    }
    $current_user = wp_get_current_user();
    $row['post_author'] = $current_user->ID;
    $new_post_id = wp_insert_post($row);
    if (!$new_post_id || is_wp_error($new_post_id)) {
      return  false;
    }

    //taxonomy
    $tax_ids = $wpdb->get_col("SELECT DISTINCT term_taxonomy_id FROM $wpdb->term_relationships WHERE object_id = $new_post_id");
    $sub_where = '';
    if ($tax_ids) {
      $sub_where =  " AND term_taxonomy_id NOT IN (" . implode(',', $tax_ids) . ")";
    }
    $wpdb->query("INSERT INTO  $wpdb->term_relationships(object_id, term_taxonomy_id) SELECT $new_post_id AS object_id, term_taxonomy_id FROM $wpdb->term_relationships WHERE object_id = $post_id $sub_where");
    //post meta
    $wpdb->query("INSERT INTO $wpdb->postmeta(post_id, meta_key, meta_value) SELECT $new_post_id AS post_id,meta_key, meta_value FROM $wpdb->postmeta WHERE post_id = $post_id");

    return $new_post_id;
  }

  public static function set_active($switch)
  {
    $opt = self::opt(null);
    $opt['enhance_switch'] = $switch;
    update_option(self::$option_name, $opt);
  }

  public static function get_active()
  {
    return self::opt('enhance_switch');
  }

  public function sanitize_text_field_array($v)
  {
    if (is_array($v)) foreach ($v as $sk => $sv) {
      if (is_array($sv)) {
        $v[$sk] = $this->sanitize_text_field_array($sv);
      } else if (is_string($sv)) {
        $v[$sk] = sanitize_text_field($sv);
      }
    }
    else if (is_string($v)) {
      $v = sanitize_text_field($v);
    }
    return $v;
  }

  //配置值
  public static function opt($name = '', $default = false)
  {
    static $options = null;

    if (null == $options) {
      $options = get_option(self::$option_name, array());
      self::extend_conf($options, self::def_opt());
    }

    $return = null;
    do {
      if (!$name) {
        $return = $options;
        break;
      }
      $ret = $options;
      $ak = explode('.', $name);

      foreach ($ak as $sk) {
        if (isset($ret[$sk])) {
          $ret = $ret[$sk];
        } else {
          $ret = $default;
          break;
        }
      }
      $return = $ret;
    } while (0);

    return apply_filters('wb_magicpost_conf', $return, $name, $default, 'enhance');
  }

  public static function def_opt()
  {

    $cnf = array(
      'enhance_switch' => '0',
      'publish_time' => '0',
      'clone_post' => '0',
      'auto_slug' => '0',
    );

    $cnf_enhance = WB_MagicPost::get_fields('enhance');
    $def_values = $cnf_enhance['default'] ?? [];
    $cnf = array_merge($cnf, $def_values);

    return $cnf;
  }

  public static function extend_conf(&$cnf, $conf)
  {
    if (is_array($conf)) foreach ($conf as  $k => $v) {
      if (!isset($cnf[$k])) {
        $cnf[$k] = $v;
      } else if (is_array($v)) {
        self::extend_conf($cnf[$k], $v);
      }
    }
  }
}
