<?php
/**
 * Plugin settings via WordPress Settings API.
 *
 * @package BOOSAIAS_For_WooCommerce
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class BOOSAIAS_Settings {

	public function init() {
		add_action( 'admin_menu', array( $this, 'add_menu_page' ) );
		add_action( 'admin_init', array( $this, 'register_settings' ) );
		add_action( 'admin_post_boosaias_sync_now', array( $this, 'handle_sync_now' ) );
		add_action( 'update_option_boosaias_license_key', array( $this, 'on_license_key_save' ), 10, 2 );

		$synced_options = array(
			'boosaias_language',
			'boosaias_telegram_chat_id',
			'boosaias_welcome_message',
			'boosaias_store_info',
		);
		foreach ( $synced_options as $option ) {
			add_action( 'update_option_' . $option, array( $this, 'push_settings' ) );
			add_action( 'add_option_' . $option, array( $this, 'push_settings' ) );
		}
	}

	public function add_menu_page() {
		add_submenu_page(
			'woocommerce',
			__( 'Boostanova AI', 'boostanova-ai-shop-assistant' ),
			__( 'AI Assistant', 'boostanova-ai-shop-assistant' ),
			'manage_woocommerce',
			'boostanova-ai-shop-assistant',
			array( $this, 'render_settings_page' )
		);
	}

	public function register_settings() {
		register_setting( 'boosaias_settings', 'boosaias_license_key', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'boosaias_settings', 'boosaias_language', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'boosaias_settings', 'boosaias_telegram_chat_id', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'boosaias_settings', 'boosaias_welcome_message', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'boosaias_settings', 'boosaias_store_info', array( 'sanitize_callback' => 'sanitize_textarea_field' ) );
		register_setting( 'boosaias_settings', 'boosaias_widget_color', array( 'sanitize_callback' => 'sanitize_hex_color' ) );
		register_setting( 'boosaias_settings', 'boosaias_show_branding', array( 'sanitize_callback' => 'absint' ) );
	}

	public function render_settings_page() {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions.', 'boostanova-ai-shop-assistant' ) );
		}
		require_once BOOSAIAS_PLUGIN_DIR . 'admin/settings-page.php';
	}

	public function on_license_key_save( $old_value, $new_value ) {
		if ( empty( $new_value ) || $old_value === $new_value ) {
			return;
		}
		$this->activate( $new_value );
	}

	/**
	 * Re-send settings to the backend when any synced option changes.
	 */
	public function push_settings() {
		$license_key = get_option( 'boosaias_license_key', '' );
		if ( empty( $license_key ) ) {
			return;
		}
		$this->activate( $license_key );
	}

	public function handle_sync_now() {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions.', 'boostanova-ai-shop-assistant' ) );
		}
		check_admin_referer( 'boosaias_sync_now' );

		do_action( 'boosaias_full_sync' );

		wp_safe_redirect( add_query_arg(
			array( 'page' => 'boostanova-ai-shop-assistant', 'synced' => '1' ),
			admin_url( 'admin.php' )
		) );
		exit;
	}

	private function activate( $license_key ) {
		// Settings API saves options one by one — push to the backend once per request.
		static $done = false;
		if ( $done ) {
			return;
		}
		$done = true;

		$client   = new BOOSAIAS_Api_Client();
		$settings = array(
			'language'         => get_option( 'boosaias_language', 'uk' ),
			'currency'         => get_woocommerce_currency(),
			'telegram_chat_id' => get_option( 'boosaias_telegram_chat_id', '' ),
			'welcome_message'  => get_option( 'boosaias_welcome_message', '' ),
			'store_info'       => get_option( 'boosaias_store_info', '' ),
		);

		$response = $client->activate_license( $license_key, $settings );

		if ( ! is_wp_error( $response ) && 200 === wp_remote_retrieve_response_code( $response ) ) {
			$data = json_decode( wp_remote_retrieve_body( $response ), true );
			if ( ! empty( $data['store_id'] ) ) {
				set_transient( 'boosaias_license_data', $data, 12 * HOUR_IN_SECONDS );
				update_option( 'boosaias_store_id', sanitize_text_field( $data['store_id'] ) );
			}
		}
	}
}
