<?php

namespace AAWP\Admin\Settings;

use AAWP_Functions as Functions;

/**
 * Class for handling AAWP API settings tab.
 *
 * @since 4.2.0
 */
class AAWP_API extends Functions {

	/**
	 * Construct the plugin object.
	 *
	 * @since 4.2.0
	 */
	public function __construct() {

		parent::__construct();

		$this->func_order = 12;
		$this->func_id    = 'aawp_api';

		add_filter( $this->settings_tabs_filter, [ &$this, 'add_settings_tabs_filter' ] );

		add_action( 'admin_init', [ $this, 'add_settings' ] );
		add_action( 'aawp_test_api_connection', [ $this, 'test_aawp_api'] );
	}

	/**
	 * Add AAWP API tab.
	 *
	 * @param array $tabs Existing Tabs.
	 *
	 * @since 4.2.0
	 *
	 * @return array Tabs with AAWP API.
	 */
	public function add_settings_tabs_filter( $tabs ) {

		$tabs[ $this->func_order ] = [
			'key'   => $this->func_id,
			'icon'  => is_aawp_api_eligible() ? 'plugins-checked' : 'admin-plugins',
			'title' => __( 'AAWP API', 'aawp' ),
		];

		return $tabs;
	}

	/**
	 * Add settings in AAWP API tab.
	 *
	 * @since 4.2.0
	 */
	public function add_settings() {

		register_setting( 'aawp_aawp_api', 'aawp_aawp_api', [ 'sanitize_callback' => 'aawp_sanitize_settings_fields' ] );
		// @see https://developer.wordpress.org/reference/functions/register_setting/

		add_settings_section( 'aawp_aawp_api_section', '', '', 'aawp_aawp_api' );
		// @see https://developer.wordpress.org/reference/functions/add_settings_section/

		/**
		 * AAWP API Headline Text section.
		 *
		 * @since 4.2.0
		 */
		add_settings_section(
			'aawp_aawp_api_section',
			__( '', 'Settings Section Headline', 'aawp' ),
			[ &$this, 'render_headline' ],
			'aawp_aawp_api'
		);

		/**
		 * AAWP API Connection Status.
		 *
		 * @since 4.2.0
		 */
		add_settings_field(
			'aawp_aawp_api_status',
			__( 'Status','aawp' ),
			[ $this, 'settings_aawp_aawp_api_status_render' ],
			'aawp_aawp_api',
			'aawp_aawp_api_section',
			[ 'label_for' => 'aawp_aawp_api_status' ]
		);

		/**
		 * AAWP API Usage.
		 *
		 * @since 4.2.0
		 */
		add_settings_field(
			'aawp_aawp_api_usage',
			$this->aawp_api_usage_title(),
			[ $this, 'settings_aawp_aawp_api_usage_render' ],
			'aawp_aawp_api',
			'aawp_aawp_api_section'
		);

		add_settings_field(
			'aawp_aawp_api_country',
			__( 'Country', 'aawp' ),
			[ &$this, 'settings_aawp_api_country_render' ],
			'aawp_aawp_api',
			'aawp_aawp_api_section',
			[ 'label_for' => 'aawp_aawp_api_country' ]
		);

		add_settings_field(
			'aawp_aawp_api_associate_tag',
			__( 'Tracking ID', 'aawp' ),
			[ &$this, 'settings_aawp_api_associate_tag_render' ],
			'aawp_aawp_api',
			'aawp_aawp_api_section',
			[ 'label_for' => 'aawp_aawp_api_associate_tag' ]
		);
	}

	/**
	 * Render Settings Title.
	 *
	 * @since 4.2.0
	 */
	public function title() {

		$title  = '<label>' . esc_html__( 'AAWP API', 'aawp' ) . '</label>';
		$title .= '<p class="description">
                    <a href="' . aawp_get_page_url( 'docs:aawp-api' ) . '">' . esc_html__( 'Learn More', 'aawp' ) . '</a> 
				</p>';

		return $title;
	}

	/**
	 * Render title for AAWP API Usage.
	 *
	 * @since 4.2.0
	 */
	public function aawp_api_usage_title() {

		ob_start();
		?>
			<label>
				<?php _e( 'Usage Quota', 'aawp' ); ?>
				<button name="aawp_aawp_api[usage_quota]" value="1" class="aawp-api-usage-quota-refresh-button dashicons dashicons-update"></button>
			</label>
		<?php

		return ob_get_clean();
	}

	/**
	 * Render headline text for AAWP API tab.
	 *
	 * @since 4.2.0
	 */
	public function render_headline() {
		?>
		<table>
			<tbody>
				<tr>
					<td>
						<?php echo '<label class="title">' . esc_html__( 'AAWP API', 'aawp' ) . '</label>'; ?>
						<p>
							<?php echo esc_html__( 'If you do not have access to the official Amazon Product Advertising API, you can alternatively use our AAWP API to retrieve product data.', 'aawp' ); ?>
						</p>
						<p>
							<?php printf( esc_html__( 'Please note that access is limited both in terms of time and functionality. Once you have generated your first commissions via Amazon, we strongly advise you to switch to the %s to use the full functionality of our plugin.', 'aawp' ),
									'<a href="' . admin_url( 'admin.php?page=aawp-settings&tab=api' ) . '">' . esc_html__('official Amazon API', 'aawp' ) . '</a>'
								);
							?>
						</p>
						<p>
							<strong><?php echo esc_html__( 'Documentation:', 'aawp' ); ?></strong>
							<a href="<?php echo aawp_get_page_url( 'docs:aawp-api' );?>" title="<?php _e( 'AAWP API', 'aawp' ); ?>" target="_blank" rel="noopener noreferrer"><?php _e( 'AAWP API', 'aawp' ); ?></a>
						</p>
					</td>
				</tr>
			</tbody>
		</table>
		<?php
	}

	/**
	 * Section for AAWP API status.
	 *
	 * @since 4.2.0
	 */
	public function settings_aawp_aawp_api_status_render() {

		echo is_aawp_api_eligible() && empty( get_option( 'aawp_products_api_error' ) )
			? '<span class="message success">' . __( 'Connected', 'aawp' ) . '</span>'
			: '<span class="message error">' . __( 'Disconnected', 'aawp' ) . '</span>';

		$options_api    = aawp_get_options( 'aawp_api' );
		$connect        = ! empty( $options_api['connect'] );
		$connect_error  = get_option( 'aawp_products_api_error' );

		?>
			<div class="aawp-api-connect-additional-info-block">
				<?php if ( $connect ) : ?>
					<?php
					if ( ! empty( $connect_error ) ) {
							echo '<div style="margin-top: 15px;">';
							echo '<p class="message error" style="line-height: 25px;">';
							echo esc_html__( 'Error', 'aawp' ) . ' ' . esc_html( $connect_error );
							echo '</p>';
					}
					?>
				<?php endif; ?>
			</div>
		<?php

		echo $this->settings_aawp_aawp_api_connect_render();
	}

	/**
	 * Checkbox for connecting to AAWP API.
	 *
	 * @since 3.30
	 */
	public function settings_aawp_aawp_api_connect_render() { //phpcs:ignore Generic.Metrics.CyclomaticComplexity.MaxExceeded

		$options_api    = aawp_get_options( 'aawp_api' );
		$connect        = ! empty( $options_api['connect'] );
		?>
			<p style="margin-top:10px">
				<input type="checkbox" id="aawp_api_connect" name="aawp_aawp_api[connect]" value="1" <?php echo( $connect ? 'checked' : '' ); ?> />
				<label for="aawp_api_connect"><?php esc_html_e( 'Check to retrieve products from the AAWP API instead of the Amazon API.', 'aawp' ); ?></label>
			</p>
			<p class="message info">
				<?php
				printf(
					/* translators: %s - AAWP API documentation link */
					esc_html__( 'Activate only if you can\'t retrieve products from the official Amazon API yet. More information about the AAWP API can be found %s. This feature is available exclusively to owners of an active license.', 'aawp' ),
					'<a href="' . aawp_get_page_url( 'docs:aawp-api' ) . '" target="_blank" rel="nofollow noopener noreferrer">here</a>'
				);
				?>
			</p>
		<?php
	}

	/**
	 * AAWP API Usage field render.
	 *
	 * @since 4.2.0
	 */
	public function settings_aawp_aawp_api_usage_render() {

		$usage_count    = (int) get_option( 'aawp_products_api_usage_count', 0 );
		$usage_limit    = (int) get_option( 'aawp_products_api_usage_limit', 150 );

		?>
			<p>
				<?php _e( 'Products Fetched This Month', 'aawp' ); ?>
						<progress style="<?php echo $usage_count >= $usage_limit ? 'accent-color: #ff364f;' : 'accent-color: #7bf0ba;'; ?>" value="<?php echo $usage_count; ?>" max="<?php echo $usage_limit; ?>"></progress><br>
				<?php printf( esc_html__( 'Retrieved %s from a max of %s products this month.', 'aawp' ), $usage_count, $usage_limit ); ?>
			</p>
		<?php
	}

	/**
	 * Render the country dropdown for AAWP API.
	 *
	 * @since 4.2.0
	 */
	public function settings_aawp_api_country_render() {

		$country_tags = aawp_get_amazon_stores();

		$country = ( isset( $this->options['aawp_api']['country'] ) ) ? esc_attr( $this->options['aawp_api']['country'] ) : 'de';

		ksort( $country_tags );
		?>
		<select id="aawp_api_country" name="aawp_aawp_api[country]" data-aawp-api-country-selector="true" 
		<?php
		if ( ! aawp_is_user_admin() ) {
			echo 'readonly';}
		?>
		>
			<?php foreach ( $country_tags as $tag => $label ) { ?>
				<option value="<?php echo $tag; ?>" <?php selected( $country, $tag ); ?>>amazon.<?php echo $tag; ?></option>
			<?php } ?>
		</select>
		<span id="aawp_api_country_icon" data-aawp-api-country-preview="true"><?php aawp_the_icon_flag( $country ); ?></span>
		<?php
	}

	/**
	 * Render the Tracking ID input for AAWP API.
	 *
	 * @since 4.2.0
	 */
	public function settings_aawp_api_associate_tag_render() {

		$associate_tag = ( isset( $this->options['aawp_api']['associate_tag'] ) ) ? esc_attr( $this->options['aawp_api']['associate_tag'] ) : '';

		?>
		<input type="text" id="aawp_api_associate_tag" class="regular-text" name="aawp_aawp_api[associate_tag]" value="<?php echo $associate_tag; ?>" 
																															<?php
																															if ( ! aawp_is_user_admin() ) {
																																echo 'readonly';}
																															?>
		/>
		<p class="description">
			<small><?php _e( 'Without the tracking id, conversions cannot be assigned to your affiliate account.', 'aawp' ); ?><br /><?php _e( 'Your tracking id should look similar to this: <strong>aawp-21</strong> (might differ depending on the country).', 'aawp' ); ?></small>
		</p>
		<p>
		<?php
		printf(
					/* translators: %s - geotargeting tab link and text. */
			esc_html__( 'Do you want to promote more than one Amazon Associates Program at the same time? Simply %s.', 'aawp' ),
			'<a href="' . admin_url( 'admin.php?page=aawp-settings&tab=geotargeting' ) . '">' . esc_html__( 'configure geotargeting' ) . '</a>'
		);
		?>
			</p>
		<?php
	}

	/**
	 * Send a test call to AAWP API.
	 *
	 * @since 3.30.2
	 */
	public function test_aawp_api() { // phpcs:ignore Generic.Metrics.CyclomaticComplexity.MaxExceeded

		if ( empty( get_option( 'aawp_products_api_error') ) ) {
			return;
		}

		$options = [
			'headers' => [
				'Content-Type'        => 'application/json',
				'Authorization'       => ! empty( aawp_fs()->_get_license()->secret_key ) ? aawp_fs()->_get_license()->secret_key : '',
				'AAWP-Version'        => AAWP_VERSION,
				'AAWP-Referer-Domain' => wp_parse_url( site_url(), PHP_URL_HOST ),
			],
		];

		$endpoint = defined( 'AAWP_API_URL' ) ? AAWP_API_URL . '/test/product' : 'https://api.getaawp.com/v1/test/product';

		$response = wp_remote_post( $endpoint, $options );

		if ( is_wp_error( $response ) ) {
			aawp_log( 'AAWP Products Test API', '<code>' . $response->get_error_message() . '</code>' ); //phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_print_r
			return;
		}

		$body = wp_remote_retrieve_body( $response);
		$body = json_decode( $body, true );

		if ( isset( $body['code'] ) && '200' === $body['code'] ) {
			delete_option( 'aawp_products_api_error' );
		}
	}
}
