<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://hypodash.com
 * @since      1.0.0
 *
 * @package    Hypodash
 * @subpackage Hypodash/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Hypodash
 * @subpackage Hypodash/admin
 * @author     Hypodash <support@hypodash.com>
 */
class Hypodash_Admin
{

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of this plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct($plugin_name, $version)
	{

		$this->plugin_name = $plugin_name;
		$this->version = $version;
	}

	/**
	 * Register Hypodash settings and fields.
	 */
	public function register_settings()
	{

		register_setting(
			'hypodash_settings',
			HYPODASH_OPTION_API_KEY,
			array(
				'type'              => 'string',
				'sanitize_callback' => array($this, 'sanitize_api_key'),
				'default'           => '',
			)
		);

		register_setting(
			'hypodash_settings',
			HYPODASH_OPTION_WEBHOOK_ENABLED,
			array(
				'type'              => 'boolean',
				'sanitize_callback' => array($this, 'sanitize_boolean'),
				'default'           => false,
			)
		);

		register_setting(
			'hypodash_settings',
			HYPODASH_OPTION_WEBHOOK_SECRET,
			array(
				'type'              => 'string',
				'sanitize_callback' => array($this, 'sanitize_webhook_secret'),
				'default'           => '',
			)
		);

		// Default category for imported posts (term ID)
		register_setting(
			'hypodash_settings',
			'hypodash_default_category',
			array(
				'type'              => 'integer',
				'sanitize_callback' => 'absint',
				'default'           => 0,
			)
		);

		add_settings_section(
			'hypodash_settings_section',
			__('Hypodash Settings', 'hypodash'),
			array($this, 'render_settings_section'),
			'hypodash'
		);

		add_settings_field(
			'hypodash_api_key',
			__('Hypodash API Key', 'hypodash'),
			array($this, 'render_api_key_field'),
			'hypodash',
			'hypodash_settings_section'
		);

		add_settings_field(
			'hypodash_enable_webhook',
			__('Enable Webhook', 'hypodash'),
			array($this, 'render_enable_webhook_field'),
			'hypodash',
			'hypodash_settings_section'
		);

		add_settings_field(
			'hypodash_webhook_secret',
			__('Webhook Secret', 'hypodash'),
			array($this, 'render_webhook_secret_field'),
			'hypodash',
			'hypodash_settings_section'
		);

		add_settings_field(
			'hypodash_default_category',
			__('Default Category', 'hypodash'),
			array($this, 'render_default_category_field'),
			'hypodash',
			'hypodash_settings_section'
		);
	}

	/**
	 * Add Hypodash settings page under Settings.
	 */
	public function add_settings_page()
	{
		add_options_page(
			__('Hypodash', 'hypodash'),
			__('Hypodash', 'hypodash'),
			'manage_options',
			'hypodash',
			array($this, 'render_settings_page')
		);
	}

	/**
	 * Render the main settings section description.
	 */
	public function render_settings_section()
	{
		echo '<p>' . esc_html__('Configure your Hypodash integration.', 'hypodash') . '</p>';
	}

	/**
	 * Render the API key field.
	 */
	public function render_api_key_field()
	{
		$stored = get_option(HYPODASH_OPTION_API_KEY, '');
		$api_key = function_exists('hypodash_decrypt') ? hypodash_decrypt($stored) : $stored;
		echo '<input type="text" name="' . esc_attr(HYPODASH_OPTION_API_KEY) . '" value="' . esc_attr($api_key) . '" class="regular-text" autocomplete="off" />';
		echo '<p class="description">' . esc_html__('Find your key under ', 'hypodash') . '<a href="https://hypodash.com/settings/app" target="_blank">' . esc_html__('app settings', 'hypodash') . '</a>' . esc_html__(' on Hypodash.', 'hypodash') . '</p>';
	}

	/**
	 * Render the webhook enable toggle.
	 */
	public function render_enable_webhook_field()
	{
		$enabled = (bool) get_option(HYPODASH_OPTION_WEBHOOK_ENABLED, false);
		echo '<label for="' . esc_attr(HYPODASH_OPTION_WEBHOOK_ENABLED) . '">';
		echo '<input type="checkbox" id="' . esc_attr(HYPODASH_OPTION_WEBHOOK_ENABLED) . '" name="' . esc_attr(HYPODASH_OPTION_WEBHOOK_ENABLED) . '" value="1" ' . checked($enabled, true, false) . ' /> ';
		echo esc_html__('Allow Hypodash to deliver webhooks.', 'hypodash');
		echo '</label>';
	}

	/**
	 * Render the webhook secret input.
	 */
	public function render_webhook_secret_field()
	{
		$secret = get_option(HYPODASH_OPTION_WEBHOOK_SECRET, '');
		echo '<input type="password" name="' . esc_attr(HYPODASH_OPTION_WEBHOOK_SECRET) . '" value="' . esc_attr($secret) . '" class="regular-text" autocomplete="new-password" />';
		echo '<p class="description">' . esc_html__('Optional secret used to validate Hypodash webhook payloads. Leave blank to skip verification.', 'hypodash') . '</p>';
	}

	/**
	 * Render the default category dropdown.
	 */
	public function render_default_category_field()
	{
		$selected = get_option('hypodash_default_category', 0);
		$args = array(
			'show_option_none' => __('-- None --', 'hypodash'),
			'name' => 'hypodash_default_category',
			'selected' => $selected,
			'hide_empty' => false,
			'orderby' => 'name',
			'echo' => 0,
			'hierarchical' => true,
		);

		$select = wp_dropdown_categories($args);
		if (! $select) {
			echo '<p>' . esc_html__('No categories available.', 'hypodash') . '</p>';
			return;
		}

		// Ensure the select has the proper name attribute for settings API to save it.
		// wp_dropdown_categories may return a select without the id/name as expected; we built it above.
		$dropdown_allowed_tags = array(
			'select' => array(
				'name' => true,
				'id' => true,
				'class' => true,
				'style' => true,
			),
			'optgroup' => array(
				'label' => true,
				'disabled' => true,
			),
			'option' => array(
				'value' => true,
				'label' => true,
				'selected' => true,
				'class' => true,
				'disabled' => true,
			),
		);

		// Escape only the HTML elements we trust so the select dropdown renders.
		echo wp_kses($select, $dropdown_allowed_tags);
		echo '<p class="description">' . esc_html__('The default category posts should be assigned to.', 'hypodash') . '</p>';
	}

	/**
	 * Render the settings page contents.
	 */
	public function render_settings_page()
	{
		$stored        = get_option(HYPODASH_OPTION_API_KEY, '');
		$api_key       = function_exists('hypodash_decrypt') ? hypodash_decrypt($stored) : $stored;
		$webhook_on    = (bool) get_option(HYPODASH_OPTION_WEBHOOK_ENABLED, false);
		$webhook_url   = esc_url($this->get_webhook_url());
		$webhook_route = esc_html(HYPODASH_WEBHOOK_NAMESPACE . HYPODASH_WEBHOOK_ROUTE);

		include plugin_dir_path(__FILE__) . 'partials/hypodash-admin-display.php';
	}

	/**
	 * Sanitize the API key text input.
	 *
	 * @param string $value Raw value from the form.
	 * @return string
	 */
	public function sanitize_api_key($value)
	{
		$clean = sanitize_text_field($value);
		if (function_exists('hypodash_encrypt')) {
			return hypodash_encrypt($clean);
		}
		return $clean;
	}

	/**
	 * Sanitize the webhook secret input.
	 */
	public function sanitize_webhook_secret($value)
	{
		return sanitize_text_field(trim((string) $value));
	}

	/**
	 * Sanitize boolean checkbox input.
	 *
	 * @param mixed $value Raw value.
	 * @return bool
	 */
	public function sanitize_boolean($value)
	{
		return (bool) rest_sanitize_boolean($value);
	}

	/**
	 * Compute the webhook URL.
	 *
	 * @return string
	 */
	private function get_webhook_url()
	{
		return home_url('/wp-json/' . HYPODASH_WEBHOOK_NAMESPACE . HYPODASH_WEBHOOK_ROUTE);
	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles()
	{

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Hypodash_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Hypodash_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */

		wp_enqueue_style($this->plugin_name, plugin_dir_url(__FILE__) . 'css/hypodash-admin.css', array(), $this->version, 'all');
	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts()
	{

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Hypodash_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Hypodash_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */

		wp_enqueue_script($this->plugin_name, plugin_dir_url(__FILE__) . 'js/hypodash-admin.js', array('jquery'), $this->version, false);
	}
}
