<?php

namespace IconPress\IconFinder;

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

/**
 * Class Options
 * @package IconPress\IconFinder
 */
class Options
{
	/**
	 * Options constructor.
	 */
	public function __construct()
	{
		add_action( 'wp_ajax_refresh_user_data', [ $this, 'refreshUserData' ] );
		add_action( 'iconpress/pages/integrations', [ $this, 'addOptionsSection' ] );
	}

	// Add options section into Integrations page
	public function addOptionsSection()
	{
		$ifApi = Api::getInstance();
		$connected = $ifApi->isConnected();
		if ( $connected ) {
			$buttonID = 'iconfinder_disconnect_api_btn';
			$text = __( 'DISCONNECT', 'iconpress' );
			$class = 'ip-btn--red';
			$url = Api::getInstance()->getDeauthorizeLink();
			$title = __('Your IconFinder account', 'iconpress');
		}
		else {
			$buttonID = 'iconfinder_connect_api_btn';
			$text = __( 'CONNECT', 'iconpress' );
			$class = 'ip-btn--blue';
			// disable button if not connected to customers dashboard
			if ( !\IconPress\Dashboard\Base::isConnected() ) {
				$class .= ' u-pevn u-op5';
			}
			$url = Api::getInstance()->getAuthorizeLink();
			$title = __('Connect your IconFinder account', 'iconpress');
		}
		?>

		<div class="iconpress-pageSection ip-iconfinderSection">

			<h2 id="activate-iconfinder"><?php _e( 'IconFinder API Integration', 'iconpress' ) ?></h2>
			<p><?php echo sprintf(
					__( "Access over a 100.000 of free icons, and over 2 million premium icons from <a href='%s' target='_blank'>IconFinder.com</a> library. This is an integration with <a href='%s' target='_blank'>IconFinder's API service</a>.", 'iconpress' ),
					'http://iconfinder.com?ref=iconpress',
					'https://developer.iconfinder.com/?ref=iconpress'
				); ?>
			</p>


			<div class="ip-row">
				<div class="ip-col-12">

					<h3><?php echo esc_html($title); ?></h3>
					<?php if(!$connected): ?>
					<p><?php _e( 'If you don\'t have an IconFinder account, <a href="https://www.iconfinder.com/user/signup?ref=iconpress" target="_blank">create one here</a>. You\'ll be redirected to IconFinder, to login & authorize IconPress application.', 'iconpress' ); ?></p>
					<?php endif; ?>

					<div class="ip-ifAuth-details">
						<ul id="js-ip-ifAuth-details">
							<?php
							$ip_if_user_details = get_transient( 'iconpress_iconfinder_user_details' );
							if ( $ip_if_user_details ) {
								echo self::getIconFinderUserInfo( $ip_if_user_details );
							}
							else {
								if ( $user_details = Rest::iconfinder_getUserDetails() ) {
									echo self::getIconFinderUserInfo( $user_details );
								}
							}
							?>
						</ul>
					</div>
					<div>
						<span id="js-if-api-ajax-response" style="display: none;"></span>
					</div>

					<a href="<?php echo esc_url( $url ); ?>" id="<?php echo esc_attr( $buttonID ); ?>" class="ip-btn ip-btn--lined <?php echo $class; ?>"><?php echo $text; ?></a>

					<?php

						//#! Show notice if not connected to customers dashboard
						if ( !\IconPress\Dashboard\Base::isConnected() ) {
							echo '<span>&nbsp;&nbsp;&nbsp;<strong>Activate IconPress</strong> to be able to use this feature.</span>';
						}

					 ?>

					<?php
					if ( $ip_if_user_details && $connected ) {
						echo '<a href="#" class="ip-btn ip-btn--lined js-refreshData">' . __( 'REFRESH DATA', 'iconpress' ) . '</a>';
					}
					?>

					<?php if ( $connected ): ?>
						<p style="margin-top:25px;">Awesome! You can start
							<a href="<?php echo admin_url( 'admin.php?page='. \IconPress\Base::PLUGIN_SLUG .'#iconfinder' ) ?>">
								<?php _e('browsing icons from IconFinder', 'iconpress');?></a>.
						</p>
					<?php endif; ?>


				</div>

			</div>
		</div>
		<?php
	}

	// Refresh user data in authorization block
	public function refreshUserData()
	{
		if ( 'POST' != strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
			wp_send_json_error( __( 'Invalid Request.', 'iconpress' ) );
		}
		if ( ! isset( $_POST[Api::NONCE_NAME] ) || ! wp_verify_nonce( $_POST[Api::NONCE_NAME], Api::NONCE_ACTION ) ) {
			wp_send_json_error( __( 'Invalid nonce.', 'iconpress' ) );
		}

		delete_transient( 'iconpress_iconfinder_user_details' );

		if ( $details = Rest::iconfinder_getUserDetails() ) {
			wp_send_json_success( self::getIconFinderUserInfo( $details ) );
		}
		wp_send_json_error( __( 'Invalid request.', 'iconpress' ) );
	}

	/**
	 * Retrieve the markup to display the IconFinder user info
	 * @param array $data
	 * @return string
	 */
	public static function getIconFinderUserInfo( $data = array() )
	{
		$html = '';
		$pro = sprintf( '<li>%s <strong>%s</strong>. <a href="https://www.iconfinder.com/pro?ref=iconpress" target="_blank">%s</a>.</li>',
			__( 'PRO Subscription:', 'iconpress' ),
			__( 'NO', 'iconpress' ),
			__( 'Upgrade to PRO to download millions of icons', 'iconpress' )
		);

		if ( ! empty( $data ) && is_array( $data ) ) {
			foreach ( $data as $key => $value ) {

				if ( $key == 'username' ) {
					$html .= '<li>' . ucfirst( $key ) . ': <strong>' . $value . '</strong></li>';
				}

				// If PRO
				if ( $key == 'organization' && isset( $value['pro_subscription'] ) ) {
					$pro = '<li><h4>' . __( 'PRO Subscription: ', 'iconpress' ) . '</h4>';
					$pro .= '<ul>';

					if ( isset( $value['pro_subscription']['max_downloads'] ) ) {
						$pro .= '<li>' . __( 'Max. downloads:', 'iconpress' ) . ' <strong>' . $value['pro_subscription']['max_downloads'] . '</strong></li>';
					}
					if ( isset( $value['pro_subscription']['is_usable'] ) ) {
						$pro .= '<li>' . __( 'Is Usable:', 'iconpress' ) . ' <strong>' . ( $value['pro_subscription']['is_usable'] ? __( 'Yes', 'iconpress' ) : __( 'No', 'iconpress' ) ) . '</strong></li>';
					}
					if ( isset( $value['pro_subscription']['is_unlimited'] ) ) {
						$pro .= '<li>' . __( 'Is Unlimited:', 'iconpress' ) . ' <strong>' . ( $value['pro_subscription']['is_unlimited'] ? __( 'Yes', 'iconpress' ) : __( 'No', 'iconpress' ) ) . '</strong></li>';
					}
					if ( isset( $value['pro_subscription']['current_downloads'] ) ) {
						$pro .= '<li>' . __( 'Current downloads:', 'iconpress' ) . ' <strong>' . $value['pro_subscription']['current_downloads'] . '</strong></li>';
					}
					if ( isset( $value['pro_subscription']['downloads_reset_on'] ) ) {
						$pro .= '<li>' . __( 'Download reset on:', 'iconpress' ) . ' <strong>' . $value['pro_subscription']['downloads_reset_on'] . '</strong></li>';
					}
					$pro .= '</ul></li>';
				}
			}
			$html .= $pro;
		}
		return $html;
	}

}

new Options();
