<?php

namespace Simplyin\Simplyin_W_Plugin\Admin;

use Simplyin\Simplyin_W_Plugin\Lib\Remote\Sin_Core_Api\Simplyin_Api_Legacy_Client;
use Simplyin\Simplyin_W_Plugin\Sync\Simplyin_Sync;

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,PHN2ZyB3aWR0aD0iMjEiIGhlaWdodD0iMjAiIHZpZXdCb3g9IjAgMCAyMSAyMCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTAuMDkzODY5NSAxMi40MDA0QzAuMDkzODY5NSAxMC43NDM1IDEuNDM3MDIgOS40MDAzOSAzLjA5Mzg3IDkuNDAwMzlDNC43NTA3MiA5LjQwMDM5IDYuMDkzODcgMTAuNzQzNSA2LjA5Mzg3IDEyLjQwMDRWMTcuMDAwNEM2LjA5Mzg3IDE4LjY1NzIgNC43NTA3MiAyMC4wMDA0IDMuMDkzODcgMjAuMDAwNEMxLjQzNzAyIDIwLjAwMDQgMC4wOT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zQzIDQuOTA3MTIgMi4zODMzIDQuOTA3MTIgMi45MjAzQzQuOTA3MTIgMy40NTczIDQuNzI2MTIgMy45MDYzIDQuMzY0MTIgNC4yNjgzQzQuMDE0MTIgNC42MzAzIDMuNTY1MTIgNC44MTEzIDMuMDE2MTIgNC44MTEzWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==',
			26
		);
	}


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

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

			add_settings_error(
				'simplyin_api_key',
				'',
				$msg_err,
				'error'
			);
		}

		$msg_success = get_option( 'SimplyInSettingsSuccessMsg' );

		if ( is_string( $msg_success ) && ! is_numeric( $msg_success ) ) {
			simplyin()->update_option( 'SimplyInSettingsSuccessMsg',
				0 );

			add_settings_error(
				'simplyin_api_key',
				'',
				$msg_success,
				'success'
			);
		}


		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',
			esc_html( __( 'API Key', 'simplyin' ) ),
			[ $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() {
		printf(
			'<p>%s</p>',
			sprintf(
			/* translators: 1: Simply.IN link open tag, 2: Simply.IN link close tag, 3: Merchant Panel link open tag, 4: Merchant Panel link close tag */
				esc_html__( 'To activate %1$sSimply.IN%2$s in your store, paste below the API key generated in the %3$smerchant panel%4$s. Detailed instructions are available in the panel.',
					'simplyin' ),
				'<a href="https://www.simply.in" target="_blank">',
				// %1$s
				'</a>',
				// %2$s
				'<a href="https://merchant.simplyin.app/" target="_blank">',
				// %3$s
				'</a>'                                                      // %4$s
			)
		);

	}

	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 {
					$is_checked = ( $wp_data_value ) ? 'checked="checked"' : '';
					$brand_link = sprintf(
						'<a href="https://www.simply.in" target="_blank">%s</a>',
						esc_html__( 'Simply.IN', 'simplyin' )
					);


					$allowed_tags_brand_link = [
						'a' => [
							'href'   => true,
							'rel'    => true,
							'target' => true,
						],
					];


					printf(
						'<div class="registerByDefaultContainer">
                            <div>
                                <h2>%s</h2>
                                <div class="row">
                                    <p>%s</p>
                                    <div>
                                        <label class="switch">
                                            <input type="%s" id="%s" name="%s" value="1" %s />
                                            <span class="slider round"></span>
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>',
						// Arg 1: H2
						esc_html__( 'User registration during checkout',
							'simplyin' ),
						// Arg 2: text with links
						sprintf(
						/* translators: 1: Link inside quote, 2: Link at end of sentence */
							esc_html__( 'The "Save your details %1$s" checkbox is selected by default for users who do not have an account at %2$s',
								'simplyin' ),
							wp_kses( $brand_link, $allowed_tags_brand_link ),
							wp_kses( $brand_link, $allowed_tags_brand_link )
						),
						// input attributes
						esc_attr( $args['subtype'] ),
						esc_attr( $args['id'] ),
						esc_attr( $args['name'] ),
						esc_html( $is_checked )
					);
				}
				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;
	}
}
