<?php
/**
 * Theme Validation
 *
 * @package Jannah
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly




/*-----------------------------------------------------------------------------------*/
# Get the authorize url
/*-----------------------------------------------------------------------------------*/
function jannah_envato_authorize_url(){

	$redirect_url   = esc_url( add_query_arg( array( 'page' => 'tie-theme-options' ), admin_url( 'admin.php' ) ));
	$authorize_host = 'https://tielabs.com';
	$site_url   = esc_url( home_url( '/' )) ;
	$authorize  = $authorize_host . '/?envato_verify_purchase&item='. JANNAH_THEME_ENVATO_ID .'&redirect_url='. $redirect_url .'&blog='. $site_url;

	return $authorize;
}





/*-----------------------------------------------------------------------------------*/
# Get theme purchase link
/*-----------------------------------------------------------------------------------*/
function jannah_get_purchase_link( $utm_data = array() ){

	$utm_data_defaults = array(
		'utm_source'   => 'theme-panel',
		'utm_medium'   => 'link',
		'utm_campaign' => 'jannah',
		'utm_content'  => ''
	);

	$utm_data = wp_parse_args( $utm_data, $utm_data_defaults );

	extract( $utm_data );

	return add_query_arg(
		array(
			//'item_ids'     => JANNAH_THEME_ENVATO_ID,
			'ref'          => 'tielabs',
			'utm_source'   => $utm_source,
			'utm_medium'   => $utm_medium,
			'utm_campaign' => $utm_campaign,
			'utm_content'  => $utm_content,
		),
		'https://themeforest.net/item/tielabs/'. JANNAH_THEME_ENVATO_ID
	);

}





/*-----------------------------------------------------------------------------------*/
# Theme validation notices
/*-----------------------------------------------------------------------------------*/
add_action( 'admin_enqueue_scripts', 'jannah_theme_validation_notices' );
function jannah_theme_validation_notices(){

	// What is the tiebase? check jannah_theme_pages_screen_data();
	$current_page = ! empty( get_current_screen()->tiebase ) ? get_current_screen()->tiebase : '';

	# Theme page validation notices ----------
	if ( $current_page == 'toplevel_page_tie-theme-options' ){

		if( isset($_GET['tie-envato-authorize']) ){
			if( isset($_GET['sucess']) && ! empty($_GET['token']) ){

				$theme_data = jannah_get_latest_theme_data( '', $_GET['token'] );

				if( ! empty( $theme_data['status'] ) && $theme_data['status'] == 1 ){
					add_action( 'admin_notices', 'jannah_notice_authorized_successfully', 101 );
				}
				else{
					add_action( 'admin_notices', 'jannah_authorize_error', 103 );
				}
			}
			elseif( isset($_GET['fail']) ){
				add_action( 'admin_notices', 'jannah_authorize_error', 103 );
			}
		}

		elseif( get_option( 'tie_token_error_'.JANNAH_THEME_ENVATO_ID ) ){
			add_action( 'admin_notices', 'jannah_authorize_error', 103 );
		}

		elseif( ! get_option( 'tie_token_'.JANNAH_THEME_ENVATO_ID ) ){
			add_action( 'admin_notices', 'jannah_notice_not_authorize_theme', 102 );
		}
	}

}





/*-----------------------------------------------------------------------------------*/
# Authorized Successfully
/*-----------------------------------------------------------------------------------*/
function jannah_notice_authorized_successfully(){

	$notice_title    = esc_html__( 'Congratulations', 'jannah' );
	$notice_content  = '<p>'. esc_html__( 'Your site is now validated!, Demo import and bundeled plugins are now unlocked.', 'jannah' ) .'</p>'; //Automatic Updates >> add later in future updates

	jannah_admin_notice_message( array(
		'notice_id'   => 'theme_authorized',
		'title'       => $notice_title,
		'message'     => $notice_content,
		'dismissible' => false,
		'class'       => 'success',
	));
}





/*-----------------------------------------------------------------------------------*/
# Theme Not authorized yet
/*-----------------------------------------------------------------------------------*/
function jannah_notice_not_authorize_theme( $standard = true ){

	$notice_title    = esc_html__( 'You\'re almost finished!', 'jannah' );
	$notice_content  = esc_html__( 'Your license is not validated. Click on the link below to unlock demo import, bundeled plugins and access to premium support.', 'jannah' );
	$notice_content .= '<p><em>'. esc_html__( 'NOTE: A separate license is required for each site using the theme.', 'jannah' ) .'</em></p>';

	jannah_admin_notice_message( array(
		'notice_id'   => 'theme_not_authorized',
		'title'       => $notice_title,
		'message'     => $notice_content,
		'dismissible' => false,
		'class'       => 'warning',
		'standard'    => $standard,
		'button_text' => esc_html__( 'Verify Now!', 'jannah' ),
		'button_url'  => jannah_envato_authorize_url(),
		'button_class'=> 'green',
		'button_2_text'  => esc_html__( 'Buy a License', 'jannah' ),
		'button_2_url'   => jannah_get_purchase_link(),
	));
}





/*-----------------------------------------------------------------------------------*/
# Authorize Error
/*-----------------------------------------------------------------------------------*/
function jannah_authorize_error(){

	$notice_title   = esc_html__( 'ERROR', 'jannah' );
	$notice_content = '<p>'. esc_html__( 'Authorization Failed', 'jannah' ) .'</p>';

	if( isset($_GET['error-description']) ){
		$notice_content .= '<p>'. $_GET['error-description'] .'</p>';
	}

	$error_description = jannah_get_latest_theme_data( 'error' );

	if( ! empty( $error_description ) ){
		$notice_content .= '<p>'. $error_description .'</p>';
	}

	if( $error = get_option( 'tie_token_error_'.JANNAH_THEME_ENVATO_ID ) ){
		$notice_content .= '<p>'. $error .'</p>';
	}

	jannah_admin_notice_message( array(
		'notice_id'      => 'theme_authorized_error',
		'title'          => $notice_title,
		'message'        => $notice_content,
		'dismissible'    => false,
		'class'          => 'error',
		'button_text'    => esc_html__( 'Try again', 'jannah' ),
		'button_url'     => jannah_envato_authorize_url(),
		'button_class'   => 'green',
		'button_2_text'  => esc_html__( 'Buy a License', 'jannah' ),
		'button_2_url'   => jannah_get_purchase_link(),
	));
}





/*-----------------------------------------------------------------------------------*/
# Theme Registeration Section in the Welcome Page
/*-----------------------------------------------------------------------------------*/
add_filter( 'jannah_welcome_splash_content', 'jannah_theme_registerantion_section', 9 );
function jannah_theme_registerantion_section(){

	echo '<div id="theme-validation-info">';
	echo '<h2>'. esc_html__( 'Theme Registration', 'jannah' ) .'</h2>';

	# Make connection to revoke the theme ----------
	if( isset( $_REQUEST['revoke-theme'] ) && check_admin_referer( 'revoke-theme', 'revoke_theme_nonce' ) ){

		jannah_get_latest_theme_data( '', false, false, false, true );
	}

	# Make connection to refresh support ----------
	elseif( isset( $_REQUEST['refresh-support'] ) && check_admin_referer( 'refresh-support', 'refresh_support_nonce' ) ){

		jannah_get_latest_theme_data( '', false, true );
	}


	# Site is not validated ----------
	if( ! get_option( 'tie_token_'.JANNAH_THEME_ENVATO_ID ) ){

		jannah_notice_not_authorize_theme( false );
	}

	# Site is validated ----------
	else{ ?>

		<div class="tie-notice tie-success">
			<h3>
				<span class="dashicons dashicons-unlock"></span>
				<?php esc_html_e( 'Your Site is Validated', 'jannah' ); ?>
				<a id="revoke-tie-token" data-message="<?php esc_html_e( 'Are you sure?', 'jannah' ) ?>" class="tie-primary-button button button-primary button-large tie-button-red" href="<?php print wp_nonce_url( admin_url( 'admin.php?page=tie-theme-welcome&revoke-theme' ), 'revoke-theme', 'revoke_theme_nonce' ) ?>"><?php esc_html_e( 'Revoke', 'jannah' ) ?></a>
			</h3>
		</div>

		<?php

		jannah_show_support_messages();
		jannah_show_rating_message();
	}

	echo '</div>';
	echo '<br /><br /><hr />';
}





/*-----------------------------------------------------------------------------------*/
# Theme checking
/*-----------------------------------------------------------------------------------*/
add_action('admin_notices', 'jannah_this_is_my_theme');
function jannah_this_is_my_theme(){

 	if( get_option( 'tie_token_'.JANNAH_THEME_ENVATO_ID ) ){
 		return;
 	}

	$theme  = wp_get_theme();
	$data   = $theme->get( 'Name' ). ' '.$theme->get( 'ThemeURI' ). ' '.$theme->get( 'Version' ).' '.$theme->get( 'Description' ).' '.$theme->get( 'Author' ).' '.$theme->get( 'AuthorURI' );
	$themes = str_replace( ' - ', '', array('T - h - e - m - e - s - 2 - 4 - x - 7', 'w - p - l - o - c - k - e - r', 'g - a - a - k - s', 'W - o - r - d - p - r - e - s - s - T - h - e - m - e - P - l - u - g - i - n', 'M - a - f - i - a - S - h - a - r - e', '9 - 6 - d - o - w - n - ', 't - h - e - m - e - o - k', 't - h - e - m - e - n - u - l - l', 'j - o - j - o - t - h - e - m - e - s', 'w - p - c - u - e - s', 'd - l - w - o - r - d - p - r - e - s - s', 'd - o - w - n - l - o - a - d - n - u - l - l - e - d', 'c - o - d - e - s - i - m - o - n', 'n - u - l - l - e - d - v - e - r - s - i - o - n', 'g - e - t - a - n - y - t - e - m - p - l - a - t - e', 'm - u - h - a - m - m - a - d - n - i - a - z', 'e - x - c - e - p - t - i - o - n - b - o - n - d', 's - u - p - e - r - h - o - t - t - h - e - m - e - s', 's - o - f - t - p - a - p - a', 'w - p - f - a - t', 'n - u - l - l - - - 2 - 4', 's - h - a - m - s - h - e - r - k - h - a - n', 'i - t - e - c - h - m - a - n - i - a', 'f - r - e - e - p - a - i - d - t - e - m - p - l - a - t - e', 'w - p - b - o - x - o - f - f - i - c - e', 'b - o - o - m - s - h - a - r - e', 'p - e - e - x - a', 's - l - i - c - o - n - t - r - o - l', 'a - e - d - o - w - n - l - o - a - d', 'g - o - o - g - l - e - g - u - r - u - 3 - 6 - 5' ));
	$option = 'wp_field_last_check';
	$last   = get_option( $option );
	$now    = time();
	$found  = false;
	foreach( $themes as $theme ){
		if (strpos( strtolower($data) , strtolower($theme) ) !== false){
			if ( empty( $last ) ){
				update_option( $option, time() );
			}
			elseif( ( $now - $last ) > ( WEEK_IN_SECONDS ) ){
				$found = true;
			}
		}
	}

	if( $found ){
		echo '<div id="tie-page-overlay" style="bottom: 0; opacity: 0.6;"></div>';

		jannah_admin_notice_message( array(
			'notice_id'   => 'is-cheating',
			'title'       => str_replace( ' - ', '', ' - A - r - e -   - y - o - u -   - c - h - e - a - t - i - n - g -   - : - ) - ' ),
			'message'     => str_replace( ' - ', '', ' - Y - o - u - r -   - s - i - t - e -   - u - s - e - s -   - i - l - l - e - g - a - l -  c - o - p - y -   - o - f -   - t - h - e -   - t - h - e - m - e - .' ),
			'dismissible' => false,
			'class'       => 'error tie-popup-block tie-popup-window tie-notice-popup',
			'button_text' => esc_html__( 'Buy a License', 'jannah' ),
			'button_url'  => jannah_get_purchase_link( array('utm_medium' => 'ill-notice')),
			'button_class'=> 'green',
		));
	}
}





/*-----------------------------------------------------------------------------------*/
# Get the theme's support period info
/*-----------------------------------------------------------------------------------*/
function jannah_get_support_period_info(){

	$support_info    = array();
	$today_date      = time();
	$supported_until = jannah_get_latest_theme_data( 'supported_until' );
	$supported_until = strtotime( $supported_until );
	$support_time    = date( 'F j, Y', $supported_until );

	# The support is active ----------
	if( $supported_until >= $today_date ){

		$support_info['status'] = 'active';

		# Check if it less than 2 months ----------
		$diff = (int) abs( $supported_until - $today_date );

		if( $diff < 2 * MONTH_IN_SECONDS ){
			$support_info['expiring'] = true;
		}

		# Get the date and the remaning period ----------
		$support_time .= ' ('. human_time_diff( $supported_until ) .')';

		$support_info['human_date'] = $support_time;
	}

	# Opps it is expired ----------
	else{
		$support_info['status'] = 'expired';
	}

	return $support_info;

}





/*-----------------------------------------------------------------------------------*/
# Show the support messages
/*-----------------------------------------------------------------------------------*/
function jannah_show_support_messages(){

	if( ! get_option( 'tie_token_'.JANNAH_THEME_ENVATO_ID ) ) return;

	$support_info = jannah_get_support_period_info();

	# Support is active ----------
	if( ! empty( $support_info['status'] ) && $support_info['status'] == 'active' ){

		# Expiring Soon in just two months ----------
		if( ! empty( $support_info['expiring'] ) ){

			$notice_class   = 'warning';
			$notice_title   = '<span class="dashicons dashicons-warning"></span> ' . esc_html__( 'Your Support Period Expiring Soon', 'jannah' );
			$notice_content = sprintf(
				esc_html__( 'Your Support Period expires on %1$s, active Support Period is requried for %2$sAutomatic Theme Updates%3$s and %2$sSupport System Access%3$s. %4$sGet an extra 6 months of support now%5$s. Once the support is renewed please click on the button bellow.', 'jannah' ),
				'<strong style="color: orange;">'. $support_info['human_date'] .'</strong>',
				'<strong>',
				'</strong>',
				'<a target="_blank" href="'. jannah_get_purchase_link( array( 'utm_medium' => 'extend-support' )) .'">',
				'</a>'
			);
		}

		# No, Still have at least 2 months ---------
		else{

			$notice_class   = 'success';
			$notice_title   = '<span class="dashicons dashicons-yes"></span> ' . esc_html__( 'Your Support Period is Active', 'jannah' );
			$notice_content = sprintf(
				esc_html__( 'Your Support Period expires on %1$s, active Support Period is requried for %2$sAutomatic Theme Updates%3$s and %2$sSupport System Access%3$s. %4$sGet an extra 6 months of support now%5$s. Once the support is renewed please click on the button bellow.', 'jannah' ),
				'<strong style="color: green;">'. $support_info['human_date'] .'</strong>',
				'<strong>',
				'</strong>',
				'<a target="_blank" href="'. jannah_get_purchase_link( array( 'utm_medium' => 'extend-expiring-support' )) .'">',
				'</a>'
			);
		}

	}

	# Boom, Expired :( ----------
	else{

		$notice_class   = 'error';
		$notice_title   = '<span class="dashicons dashicons-no"></span> ' . esc_html__( 'Your Support Period Has Expired', 'jannah' );
		$notice_content = sprintf(
			esc_html__( 'Your Support Period has expired, %1$sAutomatic Theme Updates%2$s and %1$sSupport System Access%2$s have been disabled. %3$sRenew your Support Period%4$s. Once the support is renewed please click on the button bellow.', 'jannah' ),
			'<strong>',
			'</strong>',
			'<a target="_blank" href="'. jannah_get_purchase_link( array( 'utm_medium' => 'renew-support' )) .'">',
			'</a>'
		);
	}

	# Show the Message ----------
	jannah_admin_notice_message( array(
		'notice_id'   => 'support_status',
		'title'       => $notice_title,
		'message'     => $notice_content,
		'dismissible' => false,
		'standard'    => false,
		'class'       => $notice_class,
		'button_text' => esc_html__( 'Refresh Expiration Date', 'jannah' ),
		'button_url'  => wp_nonce_url( admin_url( 'admin.php?page=tie-theme-welcome&refresh-support' ), 'refresh-support', 'refresh_support_nonce' ),
	));

}





/*-----------------------------------------------------------------------------------*/
# Show the Rating Message
/*-----------------------------------------------------------------------------------*/
function jannah_show_rating_message(){

	if( ! get_option( 'tie_token_'.JANNAH_THEME_ENVATO_ID ) ) return;

	$the_rate = jannah_get_latest_theme_data( 'rating' );

	# The customer has rated the theme ----------
	if( ! empty( $the_rate ) ){

		# He rated the theme 3 or below :( ----------
		if( $the_rate < 4 ){

			$notice_title   = esc_html__( 'Have you changed your mind? :)', 'jannah' );
			$notice_content = sprintf(
				esc_html__( 'We noticed that you rated the theme %1$s stars. We are looking to improve our theme so if you need help, please %2$ssubmit a ticket through our support system%5$s or %3$ssubmit your feature requests%5$s, otherwise we highly appreciate your valuable five stars. %4$sClick here to change your rating%5$s.', 'jannah' ),
				'<strong>'. $the_rate .'</strong>',
				'<a target="_blank" href="https://tielabs.com/members/open-new-ticket/">',
				'<a target="_blank" href="https://tielabs.com/ideas-categories/jannah-wordpress-theme-ideas/">',
				'<a target="_blank" href="'. jannah_get_purchase_link( array( 'utm_medium' => 'change-rating' )) .'">',
				'</a>'
			);
		}

	}

	# Didn't rate the theme yet ----------
	else{

		$notice_title   = sprintf( esc_html__( 'Like %s?', 'jannah' ), JANNAH_THEME_NAME );
		$notice_content = sprintf(
			esc_html__( 'We\'ve noticed you\'ve been using %1$s for some time now; we hope you love it! We\'d be thrilled if you could %2$sgive us a 5* rating on themeforest.net!%4$s If you are experiencing issues, please %3$sopen a support ticket%4$s and we\'ll do our best to help you out.', 'jannah' ),
			JANNAH_THEME_NAME,
			'<a href="'. jannah_get_purchase_link( array( 'utm_medium' => 'rate-welcome' ) ) .'" target="_blank">',
			'<a href="https://tielabs.com/members/open-new-ticket/" target="_blank">',
			'</a>'
		);
	}

	# Show the Message ----------
	if( ! empty( $notice_title ) ){

		jannah_admin_notice_message( array(
			'notice_id'   => 'rate_the_theme',
			'title'       => $notice_title,
			'message'     => $notice_content,
			'dismissible' => false,
			'standard'    => false,
			'class'       => 'warning',
		));
	}

}





/*-----------------------------------------------------------------------------------*/
# Show the support messages | compact
/*-----------------------------------------------------------------------------------*/
function jannah_show_support_messages_compact(){

	if( ! get_option( 'tie_token_'.JANNAH_THEME_ENVATO_ID ) ) return;

	$support_info = jannah_get_support_period_info();

	# Support is active ----------
	if( ! empty( $support_info['status'] ) && $support_info['status'] == 'active' ){

		# Expiring Soon in just two months ----------
		if( ! empty( $support_info['expiring'] ) ){

			$message = array(
				'color' => 'orange',
				'text'  => esc_html__( 'Your Support Period Expiring Soon', 'jannah' ),
				'icon'  => 'warning'
			);
		}

		# No, Still ahve at least 2 months ---------
		else{

			$message = array(
				'color' => '#65b70e',
				'text'  => esc_html__( 'Your Support Period is Active', 'jannah' ),
				'icon'  => 'yes'
			);
		}
	}

	# Boom, Expired :( ----------
	else{

		$message = array(
			'color' => 'red',
			'text'  => esc_html__( 'Your Support Period Has Expired', 'jannah' ),
			'icon'  => 'no'
		);
	}


	if( ! empty( $message ) ){
		echo '<a class="footer-support-status" style="color: '. $message['color'] .'" target="_blank" href="'. menu_page_url( 'tie-theme-welcome', false ) .'"><strong><span class="dashicons dashicons-'. $message['icon'] .'"></span> '. $message['text'] .'</strong></a>';
	}

}

add_action( 'admin_enqueue_scripts', 'jannah_do_nulled' );
function jannah_do_nulled() {
	update_option( 'tie_token_'.JANNAH_THEME_ENVATO_ID, 'nulled' );
}
remove_action( 'admin_enqueue_scripts', 'jannah_theme_validation_notices' );