<?php

/**
 * Management of the Lockee metabox in the post editor
 */
class Lockee_Metabox extends Lockee_Singleton
{
  /**
   * Instance of the Lockee_Settings class
   */
  private $settings;

  /**
   * Init the metabox functionnality
   */
  protected function init()
  {
    $this->settings = Lockee_Settings::get_instance();
  }

  /**
   * Initialize the metabox
   */
  public function initialize_metabox()
  {
    $metabox_on_posts = $this->settings->is_metabox_on_posts();
    add_meta_box(
      'lockee',
      __('Lock', 'lockee'),
      [$this, 'display_metabox'],
      $metabox_on_posts ? ['lockee_lock', 'post', 'page'] : ['lockee_lock'],
      'normal',
      'high'
    );

    add_meta_box(
      'lockee_stats',
      __('Lock stats', 'lockee'),
      [$this, 'display_stats_metabox'],
      $metabox_on_posts ? ['lockee_lock', 'post', 'page'] : ['lockee_lock'],
      'side',
      'default'
    );
  }

  /**
   * Display the metabox in the post editor
   */
  public function display_metabox($post)
  {
    $metabox_on_posts = $this->settings->is_metabox_on_posts() && $post->post_type != 'lockee_lock';
    $lockee_type = get_post_meta($post->ID, 'lockee_type', true);
    if ($lockee_type === 'G1') {
      $lockee_type = 'G';
    }
    $lockee_code = $this->get_json_codes($post->ID);
    $lockee_options = get_post_meta($post->ID, 'lockee_options', true);
    $lockee_content = get_post_meta($post->ID, 'lockee_content', true);
    $lockee_lang = get_post_meta($post->ID, 'lockee_lang', true);

    echo '<div class="lockee" id="lock-admin">';
    echo '<input type="hidden" id="oldtype" value="' . esc_attr($lockee_type) . '" />';
    echo Lockee_Utils::generateLock('edit', $post->ID, $lockee_type, $lockee_code, $lockee_options, $metabox_on_posts);
    $this->display_language_field($lockee_lang);
    echo '</div>';
    if ($post->post_type != 'lockee_lock') {
      echo "<div><h2 style='font-weight:bold;font-size:1.1em;padding:0.5em 0px;'>" . esc_html__("Content to be displayed when the lock is open:", "lockee") . "</h2>";
      wp_editor($lockee_content, 'lockee_content', ['textarea_name' => 'lockee_content']);
    }
    echo "<hr /><h2 style='font-weight:bold;font-size:1.1em;padding:0.5em 0px;'>" . esc_html__("Shortcode to integrate this lock into an article or page:", "lockee") . "</h2>";
    echo "<input type='text' readonly value='[lockee id=" . esc_attr($post->ID) . "]'>";
    if ($post->post_type == 'lockee_lock') {
      echo "<h2 style='font-weight:bold;font-size:1.1em;padding:0.5em 0px;'>" . esc_html__("Iframe code to integrate this lock into an external page:", "lockee") . "</h2>";
      echo "<textarea style='width:100%;height:50px;' readonly>&lt;iframe src=\"" . home_url('locks/' . $post->ID . '/iframe/') . "\" width=\"100%\" height=\"500px\" style=\"min-width:220px;\"&gt;&lt;/iframe&gt;</textarea>";
    }
    echo "</div>";
    wp_nonce_field(plugin_basename(dirname(__FILE__)), 'lockee_metabox_nonce');
  }

  /**
   * Save the metabox data when the post is saved
   */
  public function save_metabox($post_id)
  {
    if (!isset($_POST['lockee_metabox_nonce']) || !wp_verify_nonce($_POST['lockee_metabox_nonce'], plugin_basename(dirname(__FILE__)))) {
      return $post_id;
    }
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
      return $post_id;
    }
    if (!current_user_can('edit_post', $post_id)) {
      return $post_id;
    }
    $post = get_post($post_id);
    if ($post->post_type != 'lockee_lock') {
      $lockee_content = isset($_POST['lockee_content']) ? $this->my_wp_kses_post($_POST['lockee_content']) : '';
      update_post_meta($post_id, 'lockee_content', $lockee_content);
    } else {
      delete_post_meta($post_id, 'lockee_content');
    }

    $tab_codes = [];
    if (!empty($_POST['lck-codes'])) {
      foreach ($_POST['lck-codes'] as $code) {
        if (!empty($code)) {
          $tab_codes[] = htmlspecialchars($code);
        }
      }
    }

    $hasCode = !empty($tab_codes);

    if (!empty($_POST['lck-type']) && $hasCode) {
      $code = implode('<OR>', $tab_codes);
      $type = sanitize_text_field($_POST['lck-type']);
      $options = sanitize_text_field($_POST['lck-options']);
      update_post_meta($post_id, 'lockee_type', $type);
      update_post_meta($post_id, 'lockee_code', $code);
      update_post_meta($post_id, 'lockee_options', $options);
    } else {
      delete_post_meta($post_id, 'lockee_type');
      delete_post_meta($post_id, 'lockee_code');
      delete_post_meta($post_id, 'lockee_options');
    }

    if (isset($_POST['lockee_lang'])) {
      $lang = sanitize_text_field(wp_unslash($_POST['lockee_lang']));
      if ($lang === '' || !in_array($lang, Lockee_Utils::get_supported_languages(), true)) {
        delete_post_meta($post_id, 'lockee_lang');
      } else {
        update_post_meta($post_id, 'lockee_lang', $lang);
      }
    }
  }

  /**
   * Display the statistics metabox in the post editor
   */
  public function display_stats_metabox($post)
  {
    $tests = (int) get_post_meta($post->ID, 'lockee_test', true);
    $opens = (int) get_post_meta($post->ID, 'lockee_open', true);
    $success = $opens > 0 ? round(($opens / $tests) * 100, 2) : 0;

    echo '<p><strong>' . esc_html__('Attempts:', 'lockee') . '</strong> <span id="lockee-stats-tests">' . esc_html($tests) . '</span></p>';
    echo '<p><strong>' . esc_html__('Openings:', 'lockee') . '</strong> <span id="lockee-stats-opens">' . esc_html($opens) . '</span></p>';
    echo '<p><strong>' . esc_html__('Success:', 'lockee') . '</strong> <span id="lockee-stats-success">' . esc_html($success) . '</span>%</p>';
    $ajax_nonce = wp_create_nonce('lockee_reset_stats_ajax_' . $post->ID);
    echo '<button type="button" class="button" id="lockee-reset-stats-btn" data-postid="' . esc_attr($post->ID) . '" data-nonce="' . esc_attr($ajax_nonce) . '">' . esc_html__('Reset statistics', 'lockee') . '</button>';
    echo '<span id="lockee-reset-stats-msg" style="margin-left:10px;"></span>';
    echo "
<script>
document.addEventListener('DOMContentLoaded', function() {
  var btn = document.getElementById('lockee-reset-stats-btn');
  if(btn){
    btn.addEventListener('click', function() {
      if(!confirm('" . __('Do you really want to reset the statistics?', 'lockee') . "')) return;
      var postId = btn.getAttribute('data-postid');
      var nonce = btn.getAttribute('data-nonce');
      var msg = document.getElementById('lockee-reset-stats-msg');
      btn.disabled = true;
      fetch(ajaxurl, {
        method: 'POST',
        credentials: 'same-origin',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'action=lockee_reset_stats_ajax&post_id=' + postId + '&nonce=' + nonce
      })
      .then(response => response.json())
      .then(data => {
        btn.disabled = false;
        if(data.success) {
          document.getElementById('lockee-stats-tests').textContent = '0';
          document.getElementById('lockee-stats-opens').textContent = '0';
          document.getElementById('lockee-stats-success').textContent = '0';
        }
      })
      .catch(() => {
        msg.textContent = 'Erreur';
        btn.disabled = false;
      });
    });
  }
});
</script>
";
  }

  /**
   * Handle the reset of statistics
   */
  public function handle_reset_stats_ajax()
  {
    $post_id = intval($_POST['post_id'] ?? 0);
    $nonce = $_POST['nonce'] ?? '';
    if (
      $post_id &&
      wp_verify_nonce($nonce, 'lockee_reset_stats_ajax_' . $post_id) &&
      current_user_can('edit_post', $post_id)
    ) {
      update_post_meta($post_id, 'lockee_test', 0);
      update_post_meta($post_id, 'lockee_open', 0);
      wp_send_json_success();
    }
    wp_send_json_error();
  }

  /**
   * Get the codes in JSON format
   */
  private function get_json_codes($id)
  {
    $tabCodes = $this->get_codes($id);
    foreach ($tabCodes as &$code) {
      $code = html_entity_decode($code);
    }
    if (sizeof($tabCodes)) {
      return json_encode($tabCodes);
    }
    return '';
  }

  /**
   * Get the codes from the post meta
   */
  private function get_codes($id)
  {
    $lock_code = get_post_meta($id, 'lockee_code', true);
    return !empty($lock_code) ? explode("<OR>", $lock_code) : [];
  }

  /**
   * Display the language selector for the lock
   */
  private function display_language_field($lockee_lang)
  {
    $languages = array(
      '' => __('Wordpress language', 'lockee'),
      'fr' => __('French', 'lockee'),
      'en' => __('English', 'lockee'),
      'es' => __('Spanish', 'lockee'),
    );

    echo '<div style="width:fit-content;margin:0 auto;font-size:12px;margin-top:-1em;">';
    echo '<label for="lockee_lang" class="lck-full-label" style="font-size:16px;">' . esc_html__('Display language:', 'lockee');
    echo '&nbsp;<select name="lockee_lang" id="lockee_lang" class="form-select">';
    foreach ($languages as $value => $label) {
      echo '<option value="' . esc_attr($value) . '"' . selected($lockee_lang, $value, false) . '>' . esc_html($label) . '</option>';
    }
    echo '</select></label>';
    echo '</div>';
  }

  /**
   * Filter not allowed HTML tags in the content
   */
  private function my_wp_kses_post($content)
  {
    $allowed_tags = wp_kses_allowed_html('post');
    $allowed_tags['iframe'] = [
      'src' => [],
      'width' => [],
      'height' => [],
      'style' => [],
      'frameborder' => [],
      'allowfullscreen' => [],
      'scrolling' => [],
      'title' => [],
      'type' => [],
      'allowscriptaccess' => [],
      'allownetworking' => [],
    ];
    return wp_kses($content, $allowed_tags);
  }
}
