<?php

namespace Simplyin\Simplyin_W_Plugin\Admin;

class SimplyIn_Admin {

	private $plugin_name;
	private $version;
	private Shipping_Mapping_Options $shipping_mapping_options;


	public function __construct( $plugin_name, $version ) {

		$this->plugin_name = $plugin_name;
		$this->version     = $version;
		add_action( 'admin_menu', [ $this, 'addPluginAdminMenu' ], 9 );
		add_action( 'admin_init', [ $this, 'registerAndBuildFields' ] );
		add_action( 'admin_enqueue_scripts',
			[ $this, 'enqueue_admin_styles' ] );

	}

	public function enqueue_admin_styles() {

		wp_enqueue_style( 'simplyinAdminCss',
			plugin_dir_url( __FILE__ ) . '../../admin/css/simplyin-admin.css',
			[],
			wp_rand(),
			'all' );
		wp_enqueue_script( $this->plugin_name,
			plugin_dir_url( __FILE__ ) . '../../admin/js/simplyin-admin.js',
			[ 'jquery' ],
			wp_rand(),
			false );
	}

	public function addPluginAdminMenu() {
		add_menu_page(
			$this->plugin_name,
			'Simply.IN',
			'administrator',
			$this->plugin_name . '-settings',
			[ $this, 'displayPluginAdminSettings' ],
			'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjEiIGhlaWdodD0iMjAiIHZpZXdCb3g9IjAgMCAyMSAyMCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTAuMDkzODY5NSAxMi40MDA0QzAuMDkzODY5NSAxMC43NDM1IDEuNDM3MDIgOS40MDAzOSAzLjA5Mzg3IDkuNDAwMzlDNC43NTA3MiA5LjQwMDM5IDYuMDkzODcgMTAuNzQzNSA2LjA5Mzg3IDEyLjQwMDRWMTcuMDAwNEM2LjA5Mzg3IDE4LjY1NzIgNC43NTA3MiAyMC4wMDA0IDMuMDkzODcgMjAuMDAwNEMxLjQzNzAyIDIwLjAwMDQgMC4wOTM4Njk1IDE4LjY1NzIgMC4wOTM4Njk1IDE3LjAwMDRWMTIuNDAwNFoiIGZpbGw9ImJsYWNrIi8+CjxwYXRoIGQ9Ik0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C4yNjgzQzQuMDE0MTIgNC42MzAzIDMuNTY1MTIgNC44MTEzIDMuMDE2MTIgNC44MTEzWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==',
			26
		);
	}


	public function displayPluginAdminDashboard() {
		require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/partials/' . $this->plugin_name . '-admin-display.php';
	}

	public function displayPluginAdminSettings() {
		$msg = get_option( 'SimplyInSettingsErrorMsg' );
		if ( is_string( $msg ) && ! is_numeric( $msg ) ) {
			simplyin()->update_option( 'SimplyInSettingsErrorMsg',
				0 );

			add_settings_error(
				'simplyin_api_key',
				'',
				$msg,
				'error'
			);
		}
		require_once 'partials/' . $this->plugin_name . '-admin-settings-display.php';
	}

	public function simplyinSettingsMessages( $error_message ) {
		switch ( $error_message ) {
			case '1':
				$message       = __( 'There was an error adding this setting. Please try again.  If this persists, shoot us an email.',
					'simplyin' );
				$err_code      = esc_attr( 'plugin_name_example_setting' );
				$setting_field = 'plugin_name_example_setting';
				break;
		}
		$type = 'error';
		add_settings_error(
			$setting_field,
			$err_code,
			$message,
			$type
		);
	}

	private function init_shipping_mapping() {
		$this->shipping_mapping_options = new Shipping_Mapping_Options();
	}


	public function registerAndBuildFields() {
		$this->init_shipping_mapping();

		add_settings_section(
			'simplyin_settings_page_general_section',
			'API Key',
			[ $this, 'settings_page_display_general_account' ],
			'simply_settings_main'
		);

		// SimplyIN API Key field
		add_settings_field(
			'simplyin_api_key',
			'SimplyIN API Key',
			[ $this, 'settings_page_render_settings_field' ],
			'simply_settings_main',
			'simplyin_settings_page_general_section',
			[
				'type'       => 'input',
				'subtype'    => 'password',
				'id'         => 'simplyin_api_key',
				'name'       => 'simplyin_api_key',
				'required'   => 'true',
				'value_type' => 'normal',
				'wp_data'    => 'option',
			]
		);

		$disabled = get_option( "SimplyInRegisterByDefaultDisabled" );
		// Register by Default checkbox field  - show only when option disabled is not set

		if ( empty( $disabled ) ) {
			add_settings_field(
				'simplyin_register_by_default',
				'Register by Default',
				[ $this, 'settings_page_render_settings_field' ],
				'simply_settings_main',
				'simplyin_settings_page_general_section',
				[
					'type'       => 'input',
					'subtype'    => 'checkbox',
					'id'         => 'simplyin_register_by_default',
					'name'       => 'simplyin_register_by_default',
					'value_type' => 'normal',
					'wp_data'    => 'option',
				]
			);

			// Register settings
			register_setting(
				'simply_settings_main',
				'simplyin_register_by_default',
				[
					'type'              => 'string',
					'sanitize_callback' => 'sanitize_text_field',
				]
			);
		}


		// SimplyIN API Key field
		add_settings_field(
			'simplyin_shipping_mapping',
			'Shipping mapping',
			[ $this, 'settings_page_render_settings_field' ],
			'simply_settings_main',
			'simplyin_settings_page_general_section',
			[
				'type'           => 'shipping_mapping',
				'subtype'        => 'text',
				'id'             => 'simplyin_shipping_mapping',
				'name'           => 'simplyin_shipping_mapping',
				'required'       => 'true',
				'value_type'     => 'normal',
				'wp_data'        => 'option',
				'mapping_config' => $this->get_shipping_mapping_options(),
			]
		);


		$this->shipping_mapping_options->register_settings();

		// Register settings
		register_setting(
			'simply_settings_main',
			'simplyin_api_key',
			[
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
			]
		);

	}

	public function settings_page_display_general_account() {
		echo '<p>To activate <a href="https://www.simply.in" target="_blank">Simply.IN</a> in your store, paste below the API key generated in the <a href="https://merchant.simplyin.app/" target="_blank">merchant panel</a>. Detailed instructions are available in the panel.</p>';
	}

	/**
	 * Sanitize/validate API key – prevent saving empty value.
	 *
	 * - If submitted value is an empty string, add settings error and return old value (block update)
	 * - Otherwise trim and sanitize
	 * - Validates against SimplyIN API with proper error handling
	 *
	 * @param mixed $value Submitted value
	 * @return string Sanitized value or previous value when empty/invalid
	 */
	public function sanitize_required_api_key( $value ) {
		// Security check: ensure user has proper capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			return get_option( 'simplyin_api_key' );
		}

		$trimmed = is_string( $value ) ? trim( $value ) : '';
		if ( $trimmed === '' ) {
			// Block saving empty value: show error and keep previous.
			add_settings_error( 'simplyin_api_key', 'simplyin_api_key_required', esc_html__( 'Enter API key', 'simplyin' ), 'error' );
			return get_option( 'simplyin_api_key' );
		}

		$sanitized = sanitize_text_field( $trimmed );

		// Remote validation against SimplyIN API before saving.
		// Use transients to cache validation results for better performance.
		$cache_key = 'simplyin_api_validation_' . md5( $sanitized );
		$cached_result = get_transient( $cache_key );

		if ( $cached_result !== false ) {
			if ( $cached_result === 'valid' ) {
				return $sanitized;
			} else {
				add_settings_error( 'simplyin_api_key', 'simplyin_api_key_invalid', esc_html__( 'Invalid API key', 'simplyin' ), 'error' );
				return get_option( 'simplyin_api_key' );
			}
		}

		try {
			$params = [
				'platform'      => 'WooCommerce',
				'pluginVersion' => function_exists( 'SimplyInGetPluginVersion' ) ? SimplyInGetPluginVersion() : '',
				'shopName'      => addslashes( sanitize_text_field( get_bloginfo( 'name' ) ) )
			];

			$client = new \Simplyin\Simplyin_W_Plugin\Lib\Remote\Sin_Core_Api\Simplyin_Api_Legacy_Client( 'simplyin', defined( 'SIMPLYIN_VERSION' ) );

			// Set timeout to prevent blocking.
			$response = $client->sendRequest( 'plugin-sync/info', 'GET', null, $params, $sanitized );

			if ( $response && isset( $response->transactionHistoryLengthDays ) ) {
				// Cache valid result for 5 minutes.
				set_transient( $cache_key, 'valid', 5 * MINUTE_IN_SECONDS );
				return $sanitized;
			} else {
				// Cache invalid result for 1 minute.
				set_transient( $cache_key, 'invalid', MINUTE_IN_SECONDS );
				add_settings_error( 'simplyin_api_key', 'simplyin_api_key_invalid', esc_html__( 'Invalid API key', 'simplyin' ), 'error' );
				return get_option( 'simplyin_api_key' );
			}
		} catch ( \Exception $e ) {
			// Log error for debugging purposes.
			if ( function_exists( 'simplyin' ) && method_exists( simplyin(), 'get_simplyin_logger' ) ) {
				simplyin()->get_simplyin_logger()->log_if_wpdebug_on(
					'API key validation error: ' . $e->getMessage(),
					'settings'
				);
			}

			add_settings_error( 'simplyin_api_key', 'simplyin_api_key_validation_error', esc_html__( 'Could not validate API key. Please try again.', 'simplyin' ), 'error' );
			return get_option( 'simplyin_api_key' );
		}
	}


	public $allowed_tags = [
		'form',
		'label',
		'input',
		'textarea',
		'iframe',
		'script',
		'style',
		'strong',
		'small',
		'table',
		'span',
		'abbr',
		'code',
		'pre',
		'div',
		'img',
		'h1',
		'h2',
		'h3',
		'h4',
		'h5',
		'h6',
		'ol',
		'ul',
		'li',
		'em',
		'hr',
		'br',
		'tr',
		'td',
		'p',
		'a',
		'b',
		'i',
	];
	public $allowed_atts = [
		'align',
		'class',
		'type',
		'id',
		'dir',
		'lang',
		'style',
		'xml:lang',
		'src',
		'alt',
		'href',
		'rel',
		'rev',
		'target',
		'novalidate',
		'value',
		'name',
		'tabindex',
		'action',
		'method',
		'for',
		'width',
		'height',
		'data',
		'title',
	];


	public function settings_page_render_settings_field( $args ) {

		if ( $args['wp_data'] == 'option' ) {
			$wp_data_value = get_option( $args['name'] );
		} elseif ( $args['wp_data'] == 'post_meta' ) {
			$wp_data_value = get_post_meta( $args['post_id'],
				$args['name'],
				true );
		}

		global $allowedposttags;

		foreach ( $this->allowed_tags as $tag ) {
			$allowedposttags[ $tag ] = array_combine( $this->allowed_atts,
				array_fill( 0, count( $this->allowed_atts ), true ) );
		}

		switch ( $args['type'] ) {
			case 'input':
				$value = ( $args['value_type'] == 'serialized' ) ? serialize( $wp_data_value ) : $wp_data_value;
				if ( $args['subtype'] != 'checkbox' ) {
					// Render input fields
					$prependStart  = ( isset( $args['prepend_value'] ) ) ? '<div class="input-prepend"> <span class="add-on">' . $args['prepend_value'] . '</span>' : '';
					$prependEnd    = ( isset( $args['prepend_value'] ) ) ? '</div>' : '';
					$step          = ( isset( $args['step'] ) ) ? 'step="' . $args['step'] . '"' : '';
					$min           = ( isset( $args['min'] ) ) ? 'min="' . $args['min'] . '"' : '';
					$max           = ( isset( $args['max'] ) ) ? 'max="' . $args['max'] . '"' : '';
					$disabled_attr = ( isset( $args['disabled'] ) ) ? 'disabled' : '';
					$required_attr = ( isset( $args['required'] ) && $args['required'] == 'true' ) ? 'required' : '';

					echo wp_kses( $prependStart . '<input type="' . $args['subtype'] . '" id="' . $args['id'] . '" ' . $required_attr . ' ' . $step . ' ' . $max . ' ' . $min . ' name="' . $args['name'] . '" size="40" value="' . esc_attr( $value ) . '" ' . $disabled_attr . ' />' . $prependEnd,
						$allowedposttags );

				} else {
					// Render checkbox
					$checked = ( $wp_data_value ) ? 'checked' : 'false';
					echo '<div class="registerByDefaultContainer">
							<div>
								<h2>User registration during checkout</h2>
								<div class="row">
								<p>The "Save your details <a href="https://www.simply.in" target="_blank">Simply.IN</a>" checkbox is selected by default for users who do not have an account at <a href="https://www.simply.in" target="_blank">Simply.IN</a></p>
									<div>
										<label class="switch">
											<input type="' . esc_attr( $args['subtype'] ) . '" id="' . esc_attr( $args['id'] ) . '" name="' . esc_attr( $args['name'] ) . '" value="1" ' . esc_attr( $checked ) . '" ' . esc_attr( $checked ) . ' />
											<span class="slider round"></span>
										</label>
									</div>
								</div>
								</div>
						</div>';
					// echo '';

				}
				break;

			case 'shipping_mapping':


				$this->shipping_mapping_options->render_fields( $args );


			default:
				break;
		}
	}

	public function get_shipping_mapping_options(): Shipping_Mapping_Options {
		return $this->shipping_mapping_options;
	}
}
