<?php

namespace ReadJutsu;

defined('ABSPATH') or die('Something went wrong.');

class Admin
{

  public function __construct()
  {
    add_action('admin_menu',            [$this, 'register_admin_menu']);
    add_action('admin_init',            [$this, 'register_settings']);
    add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_scripts']);
    add_action('wp_ajax_readjutsu_save',    [$this, 'ajax_save_handler']);
    add_action('add_meta_boxes',        [$this, 'register_override_teaser']);

    add_filter('plugin_action_links_readjutsu/readjutsu.php', function ($links) {
      if (readjutsu_show_upsell()) {
        array_unshift($links, '<a href="' . esc_url(readjutsu_upgrade_url()) . '" style="color:#0069FF;font-weight:bold;">GET PRO</a>');
      }
      array_unshift($links, '<a href="admin.php?page=readjutsu-options">' . __('Settings', 'readjutsu') . '</a>');
      return $links;
    });
  }

  public function enqueue_admin_scripts(string $hook)
  {
    if ('toplevel_page_readjutsu-options' !== $hook) {
      return;
    }
    wp_enqueue_style('readjutsu_admin_css', READJUTSU_PLUGIN_URL . 'admin/css/readjutsu-admin.css', [], READJUTSU_VERSION);
    wp_enqueue_script('readjutsu_admin_js', READJUTSU_PLUGIN_URL . 'admin/js/readjutsu-admin.js', [], READJUTSU_VERSION, true);
    wp_localize_script('readjutsu_admin_js', 'READJUTSUADMIN', [
      'ajaxUrl' => admin_url('admin-ajax.php'),
      'nonce'   => wp_create_nonce('readjutsu_save_nonce'),
    ]);
  }

  // Locked upsell meta box — the real one is registered by Post_Override_Pro.
  public function register_override_teaser()
  {
    if (!readjutsu_show_upsell()) {
      return;
    }
    foreach (get_post_types(['public' => true], 'names') as $post_type) {
      if ('attachment' === $post_type) {
        continue;
      }
      add_meta_box(
        'readjutsu-override-teaser',
        __('ReadJutsu — Per-post override', 'readjutsu') . ' 🔒',
        [$this, 'render_override_teaser'],
        $post_type,
        'side'
      );
    }
  }

  public function render_override_teaser()
  {
    $url = readjutsu_upgrade_url();
    echo '<p style="margin:0 0 10px">' . esc_html__('Hide or force the badge and progress bar on this post, or set a manual reading time.', 'readjutsu') . '</p>';
    echo '<a class="button button-primary" href="' . esc_url($url) . '">' . esc_html__('Upgrade to Pro', 'readjutsu') . ' &rarr;</a>';
  }

  public function register_admin_menu()
  {
    add_menu_page(
      'ReadJutsu Options',
      'ReadJutsu',
      'manage_options',
      'readjutsu-options',
      [$this, 'render_admin_page'],
      'dashicons-align-pull-left',
    );
  }

  public function register_settings()
  {
    // Type-correct sanitization for the options.php no-JS fallback path
    // (the live save path is the AJAX whitelist in ajax_save_handler).
    // bool  => rest_sanitize_boolean, int => absint, color => sanitize_hex_color,
    // enum  => bounded whitelist callback, text => sanitize_text_field, array => sanitize_post_types.
    $bool   = ['type' => 'boolean', 'sanitize_callback' => 'rest_sanitize_boolean'];
    $int    = ['type' => 'integer', 'sanitize_callback' => 'absint'];
    $color  = ['type' => 'string', 'sanitize_callback' => 'sanitize_hex_color'];
    $text   = ['type' => 'string', 'sanitize_callback' => 'sanitize_text_field'];

    // Premium enum values are accepted here too so a lapsed-then-renewed
    // licence never has its stored value stripped by the fallback path.
    $enum = function (array $allowed, $default) {
      return [
        'type'              => 'string',
        'sanitize_callback' => function ($value) use ($allowed, $default) {
          $value = sanitize_key((string) $value);
          return in_array($value, $allowed, true) ? $value : $default;
        },
      ];
    };

    $array = [
      'type'              => 'array',
      'sanitize_callback' => [$this, 'sanitize_post_types'],
    ];

    $options = [
      'readjutsu_activate'                => $bool,
      'readjutsu_wpm'                     => $int,
      'readjutsu_include_images'          => $bool,
      'readjutsu_badge_activate'          => $bool,
      'readjutsu_badge_display'           => $enum(['auto', 'manual'], 'auto'),
      'readjutsu_badge_post_types'        => $array,
      'readjutsu_badge_position'          => $enum(['before', 'after'], 'before'),
      'readjutsu_badge_style'             => $enum(['pill', 'minimal', 'inline', 'floating', 'bordered', 'glass'], 'pill'),
      'readjutsu_badge_float_position'    => $enum(['top-left', 'top-right', 'bottom-left', 'bottom-right'], 'bottom-right'),
      'readjutsu_badge_icon'              => $bool,
      'readjutsu_badge_prefix'            => $text,
      'readjutsu_badge_postfix'           => $text,
      'readjutsu_badge_color'             => $color,
      'readjutsu_badge_text_color'        => $color,
      'readjutsu_progress_activate'       => $bool,
      'readjutsu_progress_display'        => $enum(['auto', 'manual'], 'auto'),
      'readjutsu_progress_post_types'     => $array,
      'readjutsu_progress_scope'          => $enum(['content', 'page'], 'content'),
      'readjutsu_progress_position'       => $enum(['top', 'bottom', 'left', 'right'], 'top'),
      'readjutsu_progress_donut_position' => $enum(['top-left', 'top-right', 'bottom-left', 'bottom-right'], 'bottom-right'),
      'readjutsu_progress_donut_size'     => $int,
      'readjutsu_progress_style'          => $enum(['solid', 'gradient', 'animated', 'percent', 'donut'], 'solid'),
      'readjutsu_progress_color'          => $color,
      'readjutsu_progress_color2'         => $color,
      'readjutsu_progress_bg'             => $color,
      'readjutsu_progress_height'         => $int,
      'readjutsu_analytics_activate'      => $bool,
      'readjutsu_analytics_retention'     => $int,
    ];
    foreach ($options as $key => $args) {
      register_setting('readjutsu-settings', $key, $args);
    }
  }

  /**
   * Sanitize a post-types option: keep an array of slug-safe strings.
   *
   * @param mixed $value Raw value from the options.php fallback path.
   * @return array
   */
  public function sanitize_post_types($value)
  {
    if (!is_array($value)) {
      return [];
    }
    return array_values(array_filter(array_map('sanitize_key', $value)));
  }

  public function render_admin_page()
  {
    $show_upsell  = readjutsu_show_upsell();
    $upgrade_url  = readjutsu_upgrade_url();
    $label        = readjutsu_can_use_premium() ? 'PRO VERSION' : 'FREE VERSION';
?>
    <div id="readjutsu-loading-mask"></div>

    <?php if ($show_upsell) : ?>
      <div class="readjutsu-topbar">
        <span class="readjutsu-topbar__copy"><?php esc_html_e('Upgrade to Pro:', 'readjutsu'); ?></span>
        <span class="readjutsu-topbar__pills">
          <span class="readjutsu-topbar__pill"><?php esc_html_e('Floating badge', 'readjutsu'); ?></span>
          <span class="readjutsu-topbar__pill"><?php esc_html_e('Animated bar', 'readjutsu'); ?></span>
          <span class="readjutsu-topbar__pill"><?php esc_html_e('Per-post override', 'readjutsu'); ?></span>
          <span class="readjutsu-topbar__pill"><?php esc_html_e('Analytics', 'readjutsu'); ?></span>
        </span>
        <a href="<?php echo esc_url($upgrade_url); ?>" class="readjutsu-topbar__cta"><?php esc_html_e('Get Pro', 'readjutsu'); ?> &rarr;</a>
      </div>
    <?php endif; ?>

    <div id="readjutsu-toast">
      <span id="readjutsu-toast-success"><?php esc_html_e('Settings saved', 'readjutsu'); ?></span>
      <span id="readjutsu-toast-error"><?php esc_html_e('Oops, something went wrong', 'readjutsu'); ?></span>
    </div>

    <div id="readjutsu-settings">
      <div class="readjutsu-settings-header">
        <h1 class="readjutsu-settings-header__title">
          <img src="<?php echo esc_url(READJUTSU_PLUGIN_URL); ?>/admin/assets/img/logo-readjutsu.svg" alt="">
          ReadJutsu
          <span><?php echo esc_html($label); ?></span>
        </h1>
        <ul class="readjutsu-settings-header__links">
          <li>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <circle cx="12" cy="12" r="10" />
              <path d="M12 16v-4M12 8h.01" />
            </svg>
            <a href="https://www.wp-jutsu.com/plugins/readjutsu/documentation" target="_blank"><?php esc_html_e('Documentation', 'readjutsu'); ?></a>
          </li>
          <li>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor">
              <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
            </svg>
            <a href="https://wordpress.org/support/plugin/readjutsu/reviews/#new-post" target="_blank"><?php esc_html_e('Rate this plugin?', 'readjutsu'); ?></a>
          </li>
        </ul>
      </div>

      <form id="readjutsu-settings-form" class="readjutsu-settings-main" method="post" action="<?php echo esc_url(admin_url('options.php')); ?>">
        <?php settings_fields('readjutsu-settings'); ?>

        <ul class="readjutsu-settings__menu">
          <li data-menu="general-settings" class="active">
            <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
              <circle cx="12" cy="12" r="3" />
              <path d="M19.07 4.93l-1.41 1.41M4.93 4.93l1.41 1.41M19.07 19.07l-1.41-1.41M4.93 19.07l1.41-1.41M12 2v2M12 20v2M2 12h2M20 12h2" />
            </svg>
            <?php esc_html_e('General', 'readjutsu'); ?>
          </li>
          <li data-menu="badge-settings">
            <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
              <circle cx="12" cy="12" r="10" />
              <polyline points="12 6 12 12 16 14" />
            </svg>
            <?php esc_html_e('Reading Time', 'readjutsu'); ?>
          </li>
          <li data-menu="progress-settings">
            <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
              <rect x="3" y="3" width="18" height="18" rx="2" />
              <path d="M3 9h18M9 21V9" />
            </svg>
            <?php esc_html_e('Progress Bar', 'readjutsu'); ?>
          </li>
          <li data-menu="analytics-settings">
            <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
              <path d="M3 3v18h18" />
              <path d="M7 14l4-4 3 3 5-6" />
            </svg>
            <?php esc_html_e('Analytics', 'readjutsu'); ?>
            <?php if (!readjutsu_can_use_premium()) : ?><span class="readjutsu-pro-badge">PRO</span><?php endif; ?>
          </li>

          <?php
          submit_button(__('Save settings', 'readjutsu'), 'readjutsu-settings__submit-btn', 'readjutsu_submit_ajax', false);
          if (wp_doing_ajax()) :
            wp_die();
          endif;
          ?>
          <p><?php esc_html_e('( or press CTRL + S )', 'readjutsu'); ?></p>

          <?php if ($show_upsell) : ?>
            <li class="readjutsu-pro-card-li">
              <div class="readjutsu-sidebar-pro">
                <div class="readjutsu-sidebar-pro__title">
                  <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                    <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
                  </svg>
                  <?php esc_html_e('Unlock Pro', 'readjutsu'); ?>
                </div>
                <div class="readjutsu-sidebar-pro__features">
                  <span class="readjutsu-sidebar-pro__pill"><?php esc_html_e('Floating badge', 'readjutsu'); ?></span>
                  <span class="readjutsu-sidebar-pro__pill"><?php esc_html_e('Animated bar', 'readjutsu'); ?></span>
                  <span class="readjutsu-sidebar-pro__pill"><?php esc_html_e('Per-post override', 'readjutsu'); ?></span>
                  <span class="readjutsu-sidebar-pro__pill"><?php esc_html_e('Analytics', 'readjutsu'); ?></span>
                </div>
                <a href="<?php echo esc_url($upgrade_url); ?>" class="readjutsu-sidebar-pro__cta"><?php esc_html_e('Get Pro', 'readjutsu'); ?> &rarr;</a>
              </div>
            </li>
          <?php endif; ?>
        </ul>

        <div class="readjutsu-settings__content">
          <?php include_once dirname(__FILE__) . '/partials/readjutsu-general-settings.php'; ?>
          <?php include_once dirname(__FILE__) . '/partials/readjutsu-badge-settings.php'; ?>
          <?php include_once dirname(__FILE__) . '/partials/readjutsu-progressbar-settings.php'; ?>
          <?php include_once dirname(__FILE__) . '/partials/readjutsu-analytics-settings.php'; ?>
        </div>
      </form>
    </div>
<?php
  }

  public function ajax_save_handler()
  {
    check_ajax_referer('readjutsu_save_nonce', '_ajax_nonce', true);

    if (! current_user_can('manage_options')) {
      wp_send_json_error(['message' => __('Permission denied.', 'readjutsu')], 403);
    }

    $valid_badge_displays  = ['auto', 'manual'];
    $valid_badge_positions = ['before', 'after'];
    $valid_badge_styles    = ['pill', 'minimal', 'inline'];
    $valid_bar_scopes      = ['content', 'page'];
    $valid_bar_displays    = ['auto', 'manual'];
    $valid_bar_positions       = ['top', 'bottom', 'left', 'right'];
    $valid_donut_positions     = ['top-right', 'top-left', 'bottom-right', 'bottom-left'];
    $valid_float_positions     = ['top-right', 'top-left', 'bottom-right', 'bottom-left'];
    $valid_bar_styles      = ['solid', 'gradient'];
    // Premium styles are only accepted when the build can run premium code.
    $can_premium = readjutsu_can_use_premium();
    if ($can_premium) {
      array_push($valid_badge_styles, 'floating', 'bordered', 'glass');
      array_push($valid_bar_styles, 'animated', 'percent', 'donut');
    }

    // General
    update_option('readjutsu_activate',       isset($_POST['readjutsu_activate'])       && '1' === sanitize_text_field(wp_unslash($_POST['readjutsu_activate'])));
    update_option('readjutsu_include_images', isset($_POST['readjutsu_include_images']) && '1' === sanitize_text_field(wp_unslash($_POST['readjutsu_include_images'])));
    update_option('readjutsu_wpm', isset($_POST['readjutsu_wpm']) ? absint(wp_unslash($_POST['readjutsu_wpm'])) : 238);

    // Badge
    update_option('readjutsu_badge_activate', isset($_POST['readjutsu_badge_activate']) && '1' === sanitize_text_field(wp_unslash($_POST['readjutsu_badge_activate'])));
    update_option('readjutsu_badge_icon',     isset($_POST['readjutsu_badge_icon'])     && '1' === sanitize_text_field(wp_unslash($_POST['readjutsu_badge_icon'])));

    $badge_post_types = [];
    if (isset($_POST['readjutsu_badge_post_types']) && is_array($_POST['readjutsu_badge_post_types'])) {
      $badge_post_types = array_map('sanitize_text_field', wp_unslash($_POST['readjutsu_badge_post_types']));
    }
    update_option('readjutsu_badge_post_types', $badge_post_types);

    if (isset($_POST['readjutsu_badge_display']) && in_array(wp_unslash($_POST['readjutsu_badge_display']), $valid_badge_displays, true)) {
      update_option('readjutsu_badge_display', sanitize_text_field(wp_unslash($_POST['readjutsu_badge_display'])));
    }
    if (isset($_POST['readjutsu_badge_position']) && in_array(wp_unslash($_POST['readjutsu_badge_position']), $valid_badge_positions, true)) {
      update_option('readjutsu_badge_position', sanitize_text_field(wp_unslash($_POST['readjutsu_badge_position'])));
    }
    if (isset($_POST['readjutsu_badge_style']) && in_array(wp_unslash($_POST['readjutsu_badge_style']), $valid_badge_styles, true)) {
      update_option('readjutsu_badge_style', sanitize_text_field(wp_unslash($_POST['readjutsu_badge_style'])));
    }
    if (isset($_POST['readjutsu_badge_float_position']) && in_array(wp_unslash($_POST['readjutsu_badge_float_position']), $valid_float_positions, true)) {
      update_option('readjutsu_badge_float_position', sanitize_text_field(wp_unslash($_POST['readjutsu_badge_float_position'])));
    }
    if (isset($_POST['readjutsu_badge_prefix']))     update_option('readjutsu_badge_prefix',     sanitize_text_field(wp_unslash($_POST['readjutsu_badge_prefix'])));
    if (isset($_POST['readjutsu_badge_postfix']))    update_option('readjutsu_badge_postfix',    sanitize_text_field(wp_unslash($_POST['readjutsu_badge_postfix'])));
    if (isset($_POST['readjutsu_badge_color']))      update_option('readjutsu_badge_color',      sanitize_hex_color(wp_unslash($_POST['readjutsu_badge_color'])));
    if (isset($_POST['readjutsu_badge_text_color'])) update_option('readjutsu_badge_text_color', sanitize_hex_color(wp_unslash($_POST['readjutsu_badge_text_color'])));

    // Progress bar
    update_option('readjutsu_progress_activate', isset($_POST['readjutsu_progress_activate']) && '1' === sanitize_text_field(wp_unslash($_POST['readjutsu_progress_activate'])));

    $progress_post_types = [];
    if (isset($_POST['readjutsu_progress_post_types']) && is_array($_POST['readjutsu_progress_post_types'])) {
      $progress_post_types = array_map('sanitize_text_field', wp_unslash($_POST['readjutsu_progress_post_types']));
    }
    update_option('readjutsu_progress_post_types', $progress_post_types);

    if (isset($_POST['readjutsu_progress_scope']) && in_array(wp_unslash($_POST['readjutsu_progress_scope']), $valid_bar_scopes, true)) {
      update_option('readjutsu_progress_scope', sanitize_text_field(wp_unslash($_POST['readjutsu_progress_scope'])));
    }
    if (isset($_POST['readjutsu_progress_display']) && in_array(wp_unslash($_POST['readjutsu_progress_display']), $valid_bar_displays, true)) {
      update_option('readjutsu_progress_display', sanitize_text_field(wp_unslash($_POST['readjutsu_progress_display'])));
    }
    if (isset($_POST['readjutsu_progress_position']) && in_array(wp_unslash($_POST['readjutsu_progress_position']), $valid_bar_positions, true)) {
      update_option('readjutsu_progress_position', sanitize_text_field(wp_unslash($_POST['readjutsu_progress_position'])));
    }
    if (isset($_POST['readjutsu_progress_donut_position']) && in_array(wp_unslash($_POST['readjutsu_progress_donut_position']), $valid_donut_positions, true)) {
      update_option('readjutsu_progress_donut_position', sanitize_text_field(wp_unslash($_POST['readjutsu_progress_donut_position'])));
    }
    if (isset($_POST['readjutsu_progress_donut_size'])) {
      update_option('readjutsu_progress_donut_size', min(120, max(24, absint(wp_unslash($_POST['readjutsu_progress_donut_size'])))));
    }
    if (isset($_POST['readjutsu_progress_style']) && in_array(wp_unslash($_POST['readjutsu_progress_style']), $valid_bar_styles, true)) {
      update_option('readjutsu_progress_style', sanitize_text_field(wp_unslash($_POST['readjutsu_progress_style'])));
    }
    if (isset($_POST['readjutsu_progress_color']))  update_option('readjutsu_progress_color',  sanitize_hex_color(wp_unslash($_POST['readjutsu_progress_color'])));
    if (isset($_POST['readjutsu_progress_color2'])) update_option('readjutsu_progress_color2', sanitize_hex_color(wp_unslash($_POST['readjutsu_progress_color2'])));
    if (isset($_POST['readjutsu_progress_bg']))     update_option('readjutsu_progress_bg',     sanitize_hex_color(wp_unslash($_POST['readjutsu_progress_bg'])));
    if (isset($_POST['readjutsu_progress_height'])) update_option('readjutsu_progress_height', absint(wp_unslash($_POST['readjutsu_progress_height'])));

    // Analytics — premium only: the free form has no analytics fields, an
    // unconditional save would silently reset the toggle on every free save.
    if ($can_premium) {
      update_option('readjutsu_analytics_activate', isset($_POST['readjutsu_analytics_activate']) && '1' === sanitize_text_field(wp_unslash($_POST['readjutsu_analytics_activate'])));
      if (isset($_POST['readjutsu_analytics_retention'])) {
        update_option('readjutsu_analytics_retention', min(3650, max(30, absint(wp_unslash($_POST['readjutsu_analytics_retention'])))));
      }
    }

    wp_send_json_success(['message' => __('Settings saved successfully', 'readjutsu')]);
  }
}
