<?php
/**
 * Admin settings for Maca Tjatt.
 *
 * @package Maca_Tjatt
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class Maca_Tjatt_Admin
 */
class Maca_Tjatt_Admin {

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'admin_menu', array( $this, 'register_menu' ) );
		add_action( 'admin_init', array( $this, 'handle_actions' ) );
		add_action( 'wp_ajax_maca_tjatt_build_index', array( $this, 'ajax_build_index' ) );
		add_action( 'wp_ajax_maca_tjatt_admin_ask', array( $this, 'ajax_admin_ask' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_plugins_screen_scripts' ) );

		require_once MACA_TJATT_PLUGIN_DIR . 'includes/deactivation-feedback.php';
	}

	/**
	 * Register admin menu.
	 */
	public function register_menu() {
		add_menu_page(
			__( 'Maca Tjatt', 'maca-tjatt' ),
			__( 'Maca Tjatt', 'maca-tjatt' ),
			'manage_options',
			'maca-tjatt',
			array( $this, 'render_page' ),
			'dashicons-format-chat',
			58
		);
	}

	/**
	 * Handle settings save and manual index build.
	 */
	public function handle_actions() {
		if ( ! is_admin() || ! isset( $_POST['maca_tjatt_action'] ) ) {
			return;
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		check_admin_referer( 'maca_tjatt_settings', 'maca_tjatt_nonce' );

		$action = sanitize_key( wp_unslash( $_POST['maca_tjatt_action'] ) );

		if ( 'save_settings' === $action ) {
			$this->save_settings();
			return;
		}

		if ( 'build_index' === $action ) {
			$result   = Maca_Tjatt_Indexer::build_index();
			$redirect = add_query_arg(
				array(
					'page'               => 'maca-tjatt',
					'maca_tjatt_notice'  => is_wp_error( $result ) ? 'error' : 'success',
					'maca_tjatt_message' => rawurlencode( is_wp_error( $result ) ? $result->get_error_message() : $result['message'] ),
				),
				admin_url( 'admin.php' )
			);
			wp_safe_redirect( $redirect );
			exit;
		}
	}

	/**
	 * Save settings.
	 */
	private function save_settings() {
		// phpcs:disable WordPress.Security.NonceVerification.Missing -- Nonce verified in handle_actions() before this method runs.
		$enabled          = isset( $_POST['maca_tjatt_enabled'] ) ? '1' : '0';
		$floating         = isset( $_POST['maca_tjatt_floating'] ) ? '1' : '0';
		$index_all_pages  = isset( $_POST['maca_tjatt_index_all_pages'] ) ? '1' : '0';
		$index_posts      = isset( $_POST['maca_tjatt_index_posts'] ) ? '1' : '0';
		$chat_model       = isset( $_POST['maca_tjatt_chat_model'] ) ? sanitize_text_field( wp_unslash( $_POST['maca_tjatt_chat_model'] ) ) : '';
		$rate_limit       = isset( $_POST['maca_tjatt_rate_limit'] ) ? absint( wp_unslash( $_POST['maca_tjatt_rate_limit'] ) ) : 30;
		$page_ids         = isset( $_POST['maca_tjatt_page_ids'] ) && is_array( $_POST['maca_tjatt_page_ids'] )
			? array_map( 'absint', wp_unslash( $_POST['maca_tjatt_page_ids'] ) )
			: array();
		$name             = isset( $_POST['maca_tjatt_name'] ) ? sanitize_text_field( wp_unslash( $_POST['maca_tjatt_name'] ) ) : '';
		$avatar_choice    = isset( $_POST['maca_tjatt_avatar'] ) ? sanitize_key( wp_unslash( $_POST['maca_tjatt_avatar'] ) ) : 'default';
		$avatar_url       = isset( $_POST['maca_tjatt_avatar_url'] ) ? esc_url_raw( wp_unslash( $_POST['maca_tjatt_avatar_url'] ) ) : '';
		$avatar_size      = isset( $_POST['maca_tjatt_avatar_size'] ) ? sanitize_key( wp_unslash( $_POST['maca_tjatt_avatar_size'] ) ) : 'medium';
		$avatar_bg_color  = isset( $_POST['maca_tjatt_avatar_bg_color'] ) ? Maca_Tjatt_Service::sanitize_avatar_bg_color( wp_unslash( $_POST['maca_tjatt_avatar_bg_color'] ) ) : Maca_Tjatt_Service::get_default_avatar_bg_color();
		$custom_knowledge = isset( $_POST['maca_tjatt_custom_knowledge'] ) ? sanitize_textarea_field( wp_unslash( $_POST['maca_tjatt_custom_knowledge'] ) ) : '';

		if ( ! array_key_exists( $avatar_size, Maca_Tjatt_Service::get_avatar_size_options() ) ) {
			$avatar_size = 'medium';
		}

		$allowed_avatars = array_merge( array( 'default', 'custom' ), Maca_Tjatt_Service::get_bundled_avatar_ids() );

		if ( ! in_array( $avatar_choice, $allowed_avatars, true ) ) {
			$avatar_choice = 'default';
		}

		if ( 'default' === $avatar_choice ) {
			$avatar_url = '';
		} elseif ( 'custom' === $avatar_choice ) {
			$avatar_url = esc_url_raw( wp_unslash( isset( $_POST['maca_tjatt_avatar_url'] ) ? (string) $_POST['maca_tjatt_avatar_url'] : '' ) );
		} else {
			$avatar_url = esc_url_raw( Maca_Tjatt_Service::get_bundled_avatar_url( $avatar_choice ) );
		}

		update_option( 'maca_tjatt_enabled', $enabled, false );
		update_option( 'maca_tjatt_floating', $floating, false );
		update_option( 'maca_tjatt_index_all_pages', $index_all_pages, false );
		update_option( 'maca_tjatt_index_posts', $index_posts, false );
		update_option( 'maca_tjatt_name', $name, false );
		update_option( 'maca_tjatt_avatar', $avatar_choice, false );
		update_option( 'maca_tjatt_avatar_url', $avatar_url, false );
		update_option( 'maca_tjatt_avatar_size', $avatar_size, false );
		update_option( 'maca_tjatt_avatar_bg_color', $avatar_bg_color, false );
		update_option( 'maca_tjatt_chat_model', $chat_model, false );
		update_option( 'maca_tjatt_rate_limit', max( 5, min( 200, $rate_limit ) ), false );
		update_option( 'maca_tjatt_page_ids', array_values( array_filter( $page_ids ) ), false );
		update_option( 'maca_tjatt_custom_knowledge', $custom_knowledge, false );

		// phpcs:enable WordPress.Security.NonceVerification.Missing

		Maca_Tjatt_Service::maybe_schedule_cron();

		if ( '1' === $enabled && Maca_Tjatt_Service::is_ai_available() ) {
			Maca_Tjatt_Service::schedule_reindex();
		}

		add_settings_error( 'maca_tjatt', 'maca_tjatt_saved', __( 'Settings saved.', 'maca-tjatt' ), 'success' );
	}

	/**
	 * AJAX index build.
	 */
	public function ajax_build_index() {
		check_ajax_referer( 'maca_tjatt_admin', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'maca-tjatt' ) ) );
		}

		$result = Maca_Tjatt_Indexer::build_index();

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
		}

		wp_send_json_success( $result );
	}

	/**
	 * AJAX admin test question.
	 */
	public function ajax_admin_ask() {
		check_ajax_referer( 'maca_tjatt_admin', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'maca-tjatt' ) ) );
		}

		$question = isset( $_POST['question'] ) ? sanitize_text_field( wp_unslash( $_POST['question'] ) ) : '';
		$history = array();

		if ( isset( $_POST['history'] ) ) {
			// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized in parse_request_history().
			$history = Maca_Tjatt_Service::parse_request_history( wp_unslash( $_POST['history'] ) );
		}

		$result = Maca_Tjatt_Service::ask(
			$question,
			$history,
			array( 'skip_rate_limit' => true )
		);

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
		}

		wp_send_json_success( $result );
	}

	/**
	 * Scripts on the Plugins screen (deactivation feedback modal).
	 *
	 * @param string $hook Current admin page hook.
	 */
	public function enqueue_plugins_screen_scripts( $hook ) {
		if ( 'plugins.php' !== $hook ) {
			return;
		}

		wp_enqueue_style(
			'maca-tjatt-admin-plugins',
			MACA_TJATT_PLUGIN_URL . 'assets/css/admin-plugins.css',
			array(),
			MACA_TJATT_VERSION
		);

		wp_enqueue_script(
			'maca-tjatt-admin-plugins',
			MACA_TJATT_PLUGIN_URL . 'assets/js/admin-plugins.js',
			array(),
			MACA_TJATT_VERSION,
			true
		);

		$reasons = array();
		foreach ( maca_tjatt_deactivation_feedback_reasons() as $id => $label ) {
			$reasons[] = array(
				'id'    => $id,
				'label' => $label,
			);
		}

		wp_localize_script(
			'maca-tjatt-admin-plugins',
			'macaTjattPlugins',
			array(
				'pluginSlug'         => plugin_basename( MACA_TJATT_PLUGIN_FILE ),
				'ajaxUrl'            => admin_url( 'admin-ajax.php' ),
				'nonce'              => wp_create_nonce( 'maca_tjatt_deactivation_feedback' ),
				'modalTitle'         => __( 'Before you deactivate Maca Tjatt', 'maca-tjatt' ),
				'modalIntro'         => __( 'Help us improve — what is the main reason you are deactivating?', 'maca-tjatt' ),
				'detailsPlaceholder' => __( 'Tell us a bit more (optional)', 'maca-tjatt' ),
				'cancelLabel'        => __( 'Cancel', 'maca-tjatt' ),
				'skipLabel'          => __( 'Skip and deactivate', 'maca-tjatt' ),
				'submitLabel'        => __( 'Send feedback and deactivate', 'maca-tjatt' ),
				'reasons'            => $reasons,
			)
		);
	}

	/**
	 * @param string $hook Admin page hook.
	 */
	public function enqueue_assets( $hook ) {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';

		if ( 'toplevel_page_maca-tjatt' !== $hook && 'maca-tjatt' !== $page ) {
			return;
		}

		wp_enqueue_style(
			'maca-tjatt',
			MACA_TJATT_PLUGIN_URL . 'assets/css/tjatt.css',
			array( 'wp-color-picker' ),
			MACA_TJATT_VERSION
		);

		wp_add_inline_style(
			'maca-tjatt',
			'.maca-tjatt-avatar-preview-wrap #maca_tjatt_avatar_preview_toggle{display:inline-flex;align-items:center;justify-content:center;padding:0;background:transparent;box-shadow:none;}' .
			'.maca-tjatt-avatar-preview-wrap #maca_tjatt_avatar_preview{width:var(--maca-tjatt-toggle-avatar-size)!important;height:var(--maca-tjatt-toggle-avatar-size)!important;max-width:var(--maca-tjatt-toggle-avatar-size)!important;max-height:var(--maca-tjatt-toggle-avatar-size)!important;display:block;object-fit:cover;border-radius:50%;}'
		);

		wp_enqueue_style( 'wp-color-picker' );

		wp_enqueue_media();

		wp_enqueue_script(
			'maca-tjatt-admin',
			MACA_TJATT_PLUGIN_URL . 'assets/js/admin-tjatt.js',
			array( 'wp-color-picker' ),
			MACA_TJATT_VERSION,
			true
		);

		wp_localize_script(
			'maca-tjatt-admin',
			'macaTjattAdmin',
			array(
				'ajaxUrl'            => admin_url( 'admin-ajax.php' ),
				'nonce'              => wp_create_nonce( 'maca_tjatt_admin' ),
				'thinking'           => __( 'Thinking…', 'maca-tjatt' ),
				'error'              => __( 'Could not get an answer.', 'maca-tjatt' ),
				'noIndex'            => __( 'Build the search index and connect an AI provider before testing the chatbot.', 'maca-tjatt' ),
				'defaultAvatarUrl'   => Maca_Tjatt_Service::get_default_avatar_url(),
				'defaultAvatarBg'    => Maca_Tjatt_Service::get_default_avatar_bg_color(),
				'avatarSizeClasses'  => array(
					'small'  => Maca_Tjatt_Service::get_avatar_size_class_for_size( 'small' ),
					'medium' => Maca_Tjatt_Service::get_avatar_size_class_for_size( 'medium' ),
					'large'  => Maca_Tjatt_Service::get_avatar_size_class_for_size( 'large' ),
				),
				'avatarDimensions'   => array(
					'small'  => Maca_Tjatt_Service::get_avatar_dimensions_for_size( 'small' ),
					'medium' => Maca_Tjatt_Service::get_avatar_dimensions_for_size( 'medium' ),
					'large'  => Maca_Tjatt_Service::get_avatar_dimensions_for_size( 'large' ),
				),
			)
		);
	}

	/**
	 * Render admin page.
	 */
	public function render_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to access this page.', 'maca-tjatt' ) );
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( isset( $_GET['maca_tjatt_notice'], $_GET['maca_tjatt_message'] ) ) {
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$type    = 'success' === sanitize_key( wp_unslash( $_GET['maca_tjatt_notice'] ) ) ? 'success' : 'error';
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$message = rawurldecode( sanitize_text_field( wp_unslash( $_GET['maca_tjatt_message'] ) ) );
			add_settings_error( 'maca_tjatt', 'maca_tjatt_build', $message, $type );
		}

		settings_errors( 'maca_tjatt' );

		include MACA_TJATT_PLUGIN_DIR . 'admin/views/settings-page.php';
	}
}
