<?php

/**
 * Class for managing the Lockee settings page in the WordPress admin
 */
class Lockee_Settings extends Lockee_Singleton
{
  /**
   * Option name for storing settings
   */
  private $option_name = 'lockee_settings';

  /**
   * Default colors for the themes
   */
  private $default_colors;

  /**
   * Initialize the settings
   */
  protected function init()
  {
    $this->default_colors =  array(
      'light' => array(
        'primary'    => '#161616',
        'accent'     => '#1976d2',
        'error'      => '#dc2626',
        'warning'    => '#d97706',
        'success'    => '#16a34a',
        'background' => '#fdfdfd',
        'border'     => '#a8a8a8',
      ),
      'dark' => array(
        'primary'    => '#eaeaea',
        'accent'     => '#4ea0ff',
        'error'      => '#ef4444',
        'warning'    => '#f59e0b',
        'success'    => '#22c55e',
        'background' => '#151518',
        'border'     => '#6b6b6c',
      )
    );
  }

  /**
   * Adds the settings page to the WordPress admin menu
   */
  public function add_settings_page()
  {
    add_submenu_page(
      'edit.php?post_type=lockee_lock',
      __('Lockee settings', 'lockee'),
      __('Lockee settings', 'lockee'),
      'manage_options',
      'lockee-settings',
      array($this, 'render_settings_page')
    );
  }

  /**
   * Registers the settings for the Lockee plugin
   */
  public function register_settings()
  {
    $this->post_force_flush_rewrite_rules();
    update_option('lockee_settings_visited', true);
    register_setting(
      'lockee_settings_group',
      $this->option_name,
      array(
        'type' => 'array',
        'sanitize_callback' => array($this, 'sanitize_settings'),
        'default' => array(
          'theme' => 'system',
          'transparent_bg' => 0,
          'colors' => $this->default_colors,
          'confetti' => 'per-lock',
          'play_sound' => 'per-lock',
          'backspace_button' => 'per-lock',
          'metabox_on_posts' => 'off',
        )
      )
    );

    add_settings_section(
      'lockee_general_section',
      __('General settings', 'lockee'),
      array($this, 'render_section_info'),
      'lockee-settings'
    );

    add_settings_field(
      'metabox_on_posts',
      __('Metabox on publications', 'lockee'),
      array($this, 'render_metabox_on_posts_field'),
      'lockee-settings',
      'lockee_general_section',
      array(
        'label_for' => 'metabox_on_posts',
        'class' => 'lockee-row'
      )
    );

    add_settings_field(
      'theme',
      __('Appearance mode', 'lockee'),
      array($this, 'render_theme_field'),
      'lockee-settings',
      'lockee_general_section',
      array(
        'label_for' => 'theme',
        'class' => 'lockee-row'
      )
    );

    add_settings_field(
      'transparent_bg',
      __('Transparent background', 'lockee'),
      array($this, 'render_transparent_bg_field'),
      'lockee-settings',
      'lockee_general_section',
      array(
        'label_for' => 'transparent_bg',
        'class' => 'lockee-row'
      )
    );

    add_settings_field(
      'colors',
      __('Theme colors', 'lockee'),
      array($this, 'render_colors_fields'),
      'lockee-settings',
      'lockee_general_section'
    );

    add_settings_field(
      'confetti',
      __('Confetti animation', 'lockee'),
      array($this, 'render_confetti_field'),
      'lockee-settings',
      'lockee_general_section',
      array(
        'label_for' => 'confetti',
        'class' => 'lockee-row'
      )
    );
    add_settings_field(
      'play_sound',
      __('Reaction sound', 'lockee'),
      array($this, 'render_play_sound_field'),
      'lockee-settings',
      'lockee_general_section',
      array(
        'label_for' => 'play_sound',
        'class' => 'lockee-row'
      )
    );
    add_settings_field(
      'backspace_button',
      __('Backspace button', 'lockee'),
      array($this, 'render_backspace_button_field'),
      'lockee-settings',
      'lockee_general_section',
      array(
        'label_for' => 'backspace_button',
        'class' => 'lockee-row'
      )
    );
  }

  /**
   * Sanitizes the settings input
   */
  public function sanitize_settings($input)
  {
    $sanitized = array();

    $allowed_themes = array('system', 'light', 'dark');
    $sanitized['theme'] = isset($input['theme']) && in_array($input['theme'], $allowed_themes)
      ? $input['theme']
      : 'system';

    $sanitized['transparent_bg'] = !empty($input['transparent_bg']) ? 1 : 0;

    $allowed_global = array('per-lock', 'off', 'on');
    $sanitized['confetti'] = isset($input['confetti']) && in_array($input['confetti'], $allowed_global) ? $input['confetti'] : 'per-lock';
    $sanitized['play_sound'] = isset($input['play_sound']) && in_array($input['play_sound'], $allowed_global) ? $input['play_sound'] : 'per-lock';
    $sanitized['backspace_button'] = isset($input['backspace_button']) && in_array($input['backspace_button'], $allowed_global) ? $input['backspace_button'] : 'per-lock';

    if (isset($_POST['lockee_reset_colors'])) {
      $sanitized['colors'] = $this->default_colors;
    } else {
      $sanitized['colors'] = array('light' => array(), 'dark' => array());
      foreach (array('light', 'dark') as $mode) {
        foreach ($this->default_colors[$mode] as $key => $default) {
          $val = isset($input['colors'][$mode][$key]) ? sanitize_hex_color($input['colors'][$mode][$key]) : '';
          if ($val && $val !== $default) {
            $sanitized['colors'][$mode][$key] = $val;
          }
        }
      }
    }

    $sanitized['metabox_on_posts'] = isset($input['metabox_on_posts']) && $input['metabox_on_posts'] === 'on' ? 'on' : 'off';

    return $sanitized;
  }

  /**
   * Display the field for the transparent background option
   */
  public function render_transparent_bg_field($args)
  {
    $options = get_option($this->option_name, array('transparent_bg' => 0));
    $checked = !empty($options['transparent_bg']) ? 'checked' : '';
?>
    <fieldset>
      <label for="<?php echo esc_attr($args['label_for']); ?>">
        <input type="checkbox"
          id="<?php echo esc_attr($args['label_for']); ?>"
          name="<?php echo esc_attr($this->option_name); ?>[transparent_bg]"
          value="1" <?php echo $checked; ?> />
        <?php esc_html_e('Make locks background transparent', 'lockee'); ?>
      </label>
    </fieldset>
  <?php
  }

  /**
   * Display the section information for the settings page
   */
  public function render_section_info()
  {
    echo '<p>' . __('Configure the general settings of the Lockee plugin.', 'lockee') . '</p>';
  }

  /**
   * Display the field for selecting the theme
   */
  public function render_theme_field($args)
  {
    $options = get_option($this->option_name, array('theme' => 'system'));
    $current_theme = isset($options['theme']) ? $options['theme'] : 'system';
  ?>
    <fieldset>
      <select id="<?php echo esc_attr($args['label_for']); ?>"
        name="<?php echo esc_attr($this->option_name); ?>[theme]">
        <option value="system" <?php selected($current_theme, 'system'); ?>>
          <?php esc_html_e('Automatic', 'lockee'); ?>
        </option>
        <option value="light" <?php selected($current_theme, 'light'); ?>>
          <?php esc_html_e('Light', 'lockee'); ?>
        </option>
        <option value="dark" <?php selected($current_theme, 'dark'); ?>>
          <?php esc_html_e('Dark', 'lockee'); ?>
        </option>
      </select>
      <p class="description">
        <?php esc_html_e('Choose the locks appearance mode', 'lockee'); ?>
      </p>
    </fieldset>
  <?php
  }

  /**
   * Display the section information for the colors settings
   */
  public function render_colors_section_info()
  {
    echo '<p>' . __('Customize the colors of the locks theme for light and dark modes. Leave blank to use the default colors.', 'lockee') . '</p>';
  }

  /**
   * Display the fields for customizing the colors of the Lockee theme
   */
  public function render_colors_fields()
  {
    $options = get_option($this->option_name, array('colors' => $this->default_colors));
    $colors = isset($options['colors']) ? $options['colors'] : $this->default_colors;
  ?>
    <table class="form-table">
      <tr>
        <th></th>
        <th style="text-align:center;"><?php esc_html_e('Light theme', 'lockee'); ?></th>
        <th style="text-align:center;"><?php esc_html_e('Dark theme', 'lockee'); ?></th>
      </tr>
      <?php
      $fields = array(
        'primary'    => __('Primary', 'lockee'),
        'accent'     => __('Accent', 'lockee'),
        'error'      => __('Error', 'lockee'),
        'warning'    => __('Warning', 'lockee'),
        'success'    => __('Success', 'lockee'),
        'background' => __('Background', 'lockee'),
        'border'     => __('Border', 'lockee'),
      );
      foreach ($fields as $key => $label) :
      ?>
        <tr>
          <th><label><?php echo esc_html($label); ?></label></th>
          <?php foreach (['light', 'dark'] as $theme) : ?>
            <td style="text-align:center;">
              <input
                class="lockee-color-field"
                type="text"
                data-default-color="<?php echo esc_attr($this->default_colors[$theme][$key]); ?>"
                name="<?php echo esc_attr($this->option_name); ?>[colors][<?php echo $theme; ?>][<?php echo esc_attr($key); ?>]"
                value="<?php echo esc_attr(isset($colors[$theme][$key]) ? $colors[$theme][$key] : $this->default_colors[$theme][$key]); ?>" />
            </td>
          <?php endforeach; ?>
        </tr>
      <?php endforeach; ?>
    </table>
    <p>
      <button type="submit" name="lockee_reset_colors" value="1" class="button"><?php esc_html_e('Reset to default colors', 'lockee'); ?></button>
    </p>
  <?php
  }

  /**
   * Display the field for the metabox on posts option
   */
  public function render_metabox_on_posts_field($args)
  {
    $options = get_option($this->option_name, array('metabox_on_posts' => 'off'));
    $checked = isset($options['metabox_on_posts']) && $options['metabox_on_posts'] === 'on' ? 'checked' : '';
  ?>
    <fieldset>
      <label for="<?php echo esc_attr($args['label_for']); ?>">
        <input type="checkbox"
          id="<?php echo esc_attr($args['label_for']); ?>"
          name="<?php echo esc_attr($this->option_name); ?>[metabox_on_posts]"
          value="on" <?php echo $checked; ?> />
        <?php esc_html_e('Allow adding locks directly to posts and pages using a metabox', 'lockee'); ?>
        <p class="description"><?php esc_html_e("Check this option if you don't want to proceed to the migration of your existing locks to the new post type", 'lockee'); ?></p>
      </label>
    </fieldset>
  <?php
  }

  /**
   * Render the settings page in the WordPress admin
   */
  public function render_settings_page()
  {
    if (!current_user_can('manage_options')) {
      return;
    }
    // Affiche le message de succès natif WordPress
    if (isset($_GET['settings-updated']) && $_GET['settings-updated']) {
      add_settings_error('lockee_messages', 'lockee_settings_saved', __('Settings saved.', 'lockee'), 'updated');
    }
    settings_errors('lockee_messages');
  ?>
    <div class="wrap">
      <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
      <form action="options.php" method="post">
        <?php
        settings_fields('lockee_settings_group');
        do_settings_sections('lockee-settings');
        submit_button(__('Save your changes', 'lockee'));
        ?>
      </form>
      <?php $this->add_force_flush_rewrite_rules(); ?>
    </div>
  <?php
  }

  // Render select for confetti
  public function render_confetti_field($args)
  {
    $this->render_global_select_field(array(
      'option_key' => 'confetti',
      'label_for' => $args['label_for'],
      'description' => __('Show a confetti animation when the lock is opened', 'lockee')
    ));
  }

  // Render select for error sound
  public function render_play_sound_field($args)
  {
    $this->render_global_select_field(array(
      'option_key' => 'play_sound',
      'label_for' => $args['label_for'],
      'description' => __('Play a sound when a combinaison is tested', 'lockee')
    ));
  }

  // Render select for backspace button
  public function render_backspace_button_field($args)
  {
    $this->render_global_select_field(array(
      'option_key' => 'backspace_button',
      'label_for' => $args['label_for'],
      'description' => __('Show a button to delete the last character entered', 'lockee')
    ));
  }

  private function render_global_select_field($args)
  {
    $option_key = $args['option_key'];
    $label_for = $args['label_for'];
    $description = $args['description'];
    $options = get_option($this->option_name, array($option_key => 'per-lock'));
    $current = isset($options[$option_key]) ? $options[$option_key] : 'per-lock';
  ?>
    <select id="<?php echo esc_attr($label_for); ?>"
      name="<?php echo esc_attr($this->option_name); ?>[<?php echo esc_attr($option_key); ?>]">
      <option value="per-lock" <?php selected($current, 'per-lock'); ?>>
        <?php esc_html_e('Use the setting defined for each lock', 'lockee'); ?>
      </option>
      <option value="off" <?php selected($current, 'off'); ?>>
        <?php esc_html_e('Disable for all locks', 'lockee'); ?>
      </option>
      <option value="on" <?php selected($current, 'on'); ?>>
        <?php esc_html_e('Enable for all locks', 'lockee'); ?>
      </option>
    </select>
    <p class="description"><?php echo esc_html($description); ?></p>
    <?php
  }

  private function post_force_flush_rewrite_rules()
  {
    if (isset($_POST['lockee_flush_rewrite']) && check_admin_referer('lockee_flush_rewrite', 'lockee_flush_rewrite_nonce')) {
      if (isset($_POST['lockee_slug_base'])) {
        $slug_base = sanitize_title($_POST['lockee_slug_base']);
        $slug_base = preg_replace('/\s+/', '-', strtolower($slug_base));
        $slug_base = trim($slug_base, '/');
        if (empty($slug_base)) {
          $slug_base = 'locks';
        }
        update_option('lockee_slug_base', $slug_base);
      }
      require_once plugin_dir_path(__FILE__) . 'class-lockee-post-types.php';
      Lockee_Post_Types::update_rewrite_rules_static();
      add_settings_error(
        'lockee_messages',
        'lockee_flush_rewrite',
        __('Locks rewrite rules have been regenerated.', 'lockee'),
        'updated'
      );
    }
  }

  private function add_force_flush_rewrite_rules()
  {
    if (current_user_can('manage_options')) : ?>
      <h2><?php _e('Other settings', 'lockee'); ?></h2>
      <form method="post" style="margin-top:2em;">
        <?php wp_nonce_field('lockee_flush_rewrite', 'lockee_flush_rewrite_nonce'); ?>
        <input type="hidden" name="lockee_flush_rewrite" value="1" />
        <div class="lockee-row">
          <label for="lockee_slug_base">
            <?php _e('Base slug for locks:', 'lockee'); ?>
          </label><input type="text" name="lockee_slug_base" id="lockee_slug_base" value="<?php echo esc_attr(get_option('lockee_slug_base', 'locks')); ?>" />
        </div>
        <div class="lockee-row" style="margin-top:1em;">
          <button type="submit" class="button button-primary"><?php _e('Validate and regenerate locks URLs', 'lockee'); ?>
          </button>
          <p>
            <?php _e('This will change the base slug to access locks and regenerate the locks URLs. Useful if the slug "locks" is already used by another plugin or theme.', 'lockee'); ?>
            <br />
            <?php _e('Be careful, this will change the URLs of all locks and may break existing links (used by iframe for example).', 'lockee'); ?>
          </p>
        </div>
      </form>
      <form method="post" style="margin-top:2em;">
        <?php wp_nonce_field('lockee_flush_rewrite', 'lockee_flush_rewrite_nonce'); ?>
        <input type="hidden" name="lockee_flush_rewrite" value="1" />
        <div class="lockee-row" style="margin-top:1em;">
          <button type="submit" class="button button-secondary">
            <?php _e('Regenerate locks URLs', 'lockee'); ?>
          </button>
          <p style="margin:0.5em 0 0 0;">
            <?php _e('Use this only if the locks URLs are not working.', 'lockee'); ?>
            <br />
            <?php _e('This will regenerate the rewrite rules for locks without changing the base slug (URLs will remain the same).', 'lockee'); ?>
          </p>
        </div>
      </form>
<?php endif;
  }

  /**
   * Get the current theme
   */
  public function get_theme()
  {
    $options = get_option($this->option_name, array('theme' => 'system'));
    return isset($options['theme']) ? $options['theme'] : 'system';
  }

  /**
   * Check if the background should be transparent
   */
  public function is_transparent_bg()
  {
    $options = get_option($this->option_name, array('transparent_bg' => 0));
    return !empty($options['transparent_bg']);
  }

  /**
   * Get the colors configured in the settings
   */
  public function get_colors()
  {
    $options = get_option($this->option_name, array('colors' => $this->default_colors));
    return isset($options['colors']) ? $options['colors'] : $this->default_colors;
  }

  /**
   * Get the default colors for the themes
   */
  public function get_default_colors()
  {
    return $this->default_colors;
  }

  /**
   * Get the metabox setting for posts
   */
  public function is_metabox_on_posts()
  {
    return get_option($this->option_name, array('metabox_on_posts' => 'off'))['metabox_on_posts'] === 'on';
  }

  /**
   * Get the locks settings
   */
  public function get_lock_settings()
  {
    $options = get_option($this->option_name, array(
      'confetti' => 'per-lock',
      'play_sound' => 'per-lock',
      'backspace_button' => 'per-lock'
    ));
    return array(
      'confetti' => isset($options['confetti']) ? $options['confetti'] : 'per-lock',
      'play_sound' => isset($options['play_sound']) ? $options['play_sound'] : 'per-lock',
      'backspace_button' => isset($options['backspace_button']) ? $options['backspace_button'] : 'per-lock'
    );
  }
}
