<?php
/**
 * Created by PhpStorm.
 * User: Villatheme-Thanh
 * Date: 14-03-19
 * Time: 4:26 PM
 */

namespace WACVP\Inc\Execute;

use WACVP\Inc\Data;

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

class Get_FB_Email {

	protected static $instance = null;
	protected $language;
	public $render_email_popup = false;

	public static function get_instance() {
		if ( null == self::$instance ) {
			self::$instance = new self;
		}

		return self::$instance;
	}

	public function __construct() {
		$this->language = '';
		add_action( 'wp_enqueue_scripts', [ $this, 'frontend_enqueue' ] );
		add_action( 'wp_footer', [ $this, 'load_email_popup_temp' ] );
		add_action( 'template_redirect', array( $this, 'redirect' ) );
//		add_action( 'woocommerce_after_add_to_cart_button', array( $this, 'show_messenger_cb' ) );

//		add_action( 'rest_api_init', array( $this, 'register_api' ) );
	}

	public function frontend_enqueue() {
		$min = WP_DEBUG ? '' : '.min';
		wp_register_script( WACVP_SLUG . 'abandoned-cart', WACVP_JS . 'abandoned-cart' . $min . '.js', [ 'jquery' ], WACVP_VERSION, true );
		wp_register_script( WACVP_SLUG . 'abandoned-recaptcha', WACVP_JS . 'wacv-recaptcha' . $min . '.js', [ 'jquery' ], WACVP_VERSION, true );
		wp_register_style( WACVP_SLUG . 'get-email', WACVP_CSS . 'get-email.css', '', WACVP_VERSION );

		if ( is_plugin_active( 'sitepress-multilingual-cms/sitepress.php' ) ) {
			$default_lang     = apply_filters( 'wpml_default_language', null );
			$current_language = apply_filters( 'wpml_current_language', null );

			if ( $current_language && $current_language !== $default_lang ) {
				$this->language = $current_language;
			}
		} else if ( class_exists( 'Polylang' ) ) {
			$default_lang     = pll_default_language( 'slug' );
			$current_language = pll_current_language( 'slug' );
			if ( $current_language && $current_language !== $default_lang ) {
				$this->language = $current_language;
			}
		}

		$settings    = Data::get_params();
		$cond        = $params = [];
		$fb_checkbox = false;
		$immediate_cart = is_cart() && $settings['immediate_cart_popup'];

		if ( ! ( is_user_logged_in() || wc()->session && wc()->session->get( 'user_id' ) ) ) {
			$cond[] = is_shop() && $settings['shop_page'];
			$cond[] = is_product() && $settings['single_page'];
			$cond[] = is_cart() && $settings['cart_page'];
			$cond[] = is_front_page() && $settings['front_page'];
			$cond[] = is_home() && $settings['front_page'];
			$cond[] = is_product_category() && $settings['category_page'];
			$cond[] = is_page( explode( ',', str_replace( ' ', '', $settings['popup_page_id'] ) ) );
			$cond[] = is_singular( explode( ',', str_replace( ' ', '', $settings['popup_post_type'] ) ) );

			if ( array_sum( $cond ) || $immediate_cart ) {
				$this->render_email_popup = true;

				$params = array_merge( $params, [
					'emailPopup'     => true,
					'cartPage'       => wc_get_cart_url(),
					'checkoutPage'   => wc_get_checkout_url(),
					'dismissDelay'   => $settings['dismiss_delay'] * 60,
					'redirect'       => $settings['redirect_after_atc'] == 'to_cart_page' ? wc_get_cart_url() : ( $settings['redirect_after_atc'] == 'to_checkout_page' ? wc_get_checkout_url() : '' ),
					'i18n_view_cart' => esc_attr__( 'View cart', 'woo-abandoned-cart-recovery' ),
					'emailField'     => $settings['email_field'],
					'phoneField'     => $settings['phone_field'],
					'info_require'   => $settings['info_require'],
					'phone_require'  => $settings['phone_require'],
					'gdprField'      => $settings['enable_gdpr'],
					'style'          => $settings['template_popup']
				] );

				wp_enqueue_style( WACVP_SLUG . 'get-email' );

				$title_color        = $settings['popup_title_color'];
				$sub_title_color    = $settings['popup_sub_title_color'];
				$notice_color       = $settings['popup_notice_color'];
				$bg_color           = $settings['popup_bg_color'];
				$btn_color          = $settings['popup_btn_color'];
				$btn_bg_color       = $settings['popup_btn_bg_color'];
				$input_bg_color     = $settings['popup_input_bg_color'];
				$input_border_color = $settings['popup_input_border_color'];
				$input_text_color   = $settings['popup_input_text_color'];

				$css = ".wacv-get-email-title{color:$title_color}";
				$css .= ".wacv-get-email-sub-title{color:$sub_title_color}";
				$css .= ".wacv-close-text{color:$sub_title_color}";
				$css .= ".wacv-email-invalid-notice{color:$notice_color}";
				$css .= ".wacv-modal-content{background-color:$bg_color}";
				$css .= ".wacv-get-email-btn{color:$btn_color; background-color:$btn_bg_color}";
				$css .= ".wacv-popup-input-email {background-color:$input_bg_color !important; border: 1px solid $input_border_color !important;color:$input_text_color !important;}";
				$css .= ".wacv-popup-input-phone-number{background-color:$input_bg_color !important;color:$input_text_color !important;}";
				$css .= ".wacv-country-calling-code{color:$input_text_color !important;}";
				$css .= ".wacv-get-customer-phone-number{background-color:$input_bg_color !important; border: 1px solid $input_border_color !important;color:$input_text_color !important;}";
				$css .= "::placeholder{color:$input_text_color !important; opacity:0.7;}";
				$css .= ":-ms-input-placeholder{color:$input_text_color !important; opacity:0.7;}";
				$css .= "::-ms-input-placeholder{color:$input_text_color !important; opacity:0.7;}";

				wp_add_inline_style( WACVP_SLUG . 'get-email', $css );
			}

		}

		if ( array_sum( $cond ) || is_product() || $immediate_cart ) {
			$fb_checkbox = true;
		}

		if ( $fb_checkbox ) {
			wp_enqueue_script( WACVP_SLUG . 'abandoned-cart' );

			$params = array_merge( $params, [
					'ajaxUrl'       => admin_url( 'admin-ajax.php' ),
					'nonce'         => wp_create_nonce( 'wacv-nonce' ),
					'homeURL'       => home_url(),
					'userToken'     => $settings['user_token'],
					'appLang'       => $settings['app_lang'],
					'appSkin'       => $settings['app_skin'],
					'appID'         => $settings['app_id'],
					'pageID'        => $settings['page_id'],
					'fbCbRequire'   => $settings['checkbox_require'],
					'recaptcha'     => $settings['enable_captcha'],
					'recaptcha_key' => $settings['recaptcha_site_key'],
					'exclude_atc'   => $settings['exclude_class_popup'],
					'immediate_cart_popup' => $immediate_cart,
					'enable_email_immediate' => $settings['enable_email_immediate'],
				]
			);
			wp_localize_script( WACVP_SLUG . 'abandoned-cart', 'wacvParams', $params );
			if ( $settings['enable_captcha'] ) {
				wp_enqueue_script( WACVP_SLUG . 'abandoned-recaptcha' );
				$params_captcha = array(
					'enable_captcha'         => $settings['enable_captcha'],
					'recaptcha_version'      => $settings['recaptcha_version'],
					'recaptcha_site_key'     => $settings['recaptcha_site_key'],
					'recaptcha_secret_theme' => $settings['recaptcha_secret_theme'],
				);
				wp_localize_script( WACVP_SLUG . 'abandoned-recaptcha', 'wacv_recaptcha_params', $params_captcha );
			}
		}

	}

	public function load_email_popup_temp() {
		if ( ! $this->render_email_popup ) {
			return;
		}
		$settings = Data::get_params();
		wc_get_template( 'popup-' . $settings['template_popup'] . '.php', array(
			'param' => $settings,
			'lang'  => $this->language
		), '', WACVP_TEMPLATES );
	}

	public function show_messenger_cb() {
		if ( $this->render_email_popup ) {
			return;
		}
		?>
        <div class="fb-messenger-checkbox-container"></div>
		<?php
	}

	public function redirect() {
		if ( isset( $_REQUEST['_wacv_admin_nonce'] ) && ! wp_verify_nonce( wc_clean( wp_unslash( $_REQUEST['_wacv_admin_nonce'] ) ), 'wacv_admin_nonce' ) ) {
			exit;
		}
		if ( isset( $_POST['wacv_redirect'] ) ) {
			wp_safe_redirect( sanitize_text_field( $_POST['wacv_redirect'] ) );
			exit;
		}
	}

	public function register_api() {
		/*Auto update plugins*/
		register_rest_route(
			'woocommerce-abandoned-cart-recovery', '/subscribe', array(
				'methods'  => 'POST',
				'callback' => array( $this, 'wacv_email' ),
			)
		);
	}

	public function wacv_email() {
//		$settings    = Data::get_params();
//		if ( $settings['ajax_endpoint'] === 'rest_api' ) {
		header( "Access-Control-Allow-Origin: *" );
		header( 'Access-Control-Allow-Methods: POST' );
//		}
		self::validate_recaptcha();
	}

	public static function validate_recaptcha() {
		if ( isset( $_REQUEST['_wacv_frontend_nonce'] ) && ! wp_verify_nonce( wc_clean( wp_unslash( $_REQUEST['_wacv_frontend_nonce'] ) ), 'wacv_frontend_nonce' ) ) {
			$msg['status']  = 'invalid';
			$msg['warning'] = esc_html__( '*Invalid nonce field!', 'woo-abandoned-cart-recovery' );
			wp_send_json( $msg );
		}
		$settings            = Data::get_params();
		$g_validate_response = isset( $_POST['g_validate_response'] ) ? sanitize_text_field( $_POST['g_validate_response'] ) : '';
		if ( ! $g_validate_response && $settings['enable_captcha'] ) {
			$msg            = array(
				'status'              => '',
				'message'             => '',
				'warning'             => '',
				'g_validate_response' => '1',
			);
			$msg['status']  = 'invalid';
			$msg['warning'] = esc_html__( '*No g_validate_response', 'woo-abandoned-cart-recovery' );
			wp_send_json( $msg );
		}
		if ( $g_validate_response && $settings['enable_captcha'] ) {
			$msg = array(
				'status'              => '',
				'message'             => '',
				'warning'             => '',
				'g_validate_response' => '1',
			);
			if ( ! $g_validate_response ) {
				$msg['status']  = 'invalid';
				$msg['warning'] = esc_html__( '*Invalid google reCAPTCHA!', 'woo-abandoned-cart-recovery' );
				wp_send_json( $msg );
			}
			$wacv_recaptcha_secret_key = $settings['recaptcha_secret_key'];
			if ( ! $wacv_recaptcha_secret_key ) {
				$msg['status']  = 'invalid';
				$msg['warning'] = esc_html__( '*Invalid google reCAPTCHA secret key!', 'woo-abandoned-cart-recovery' );
				wp_send_json( $msg );
			}
			$url  = 'https://www.google.com/recaptcha/api/siteverify?secret=' . $wacv_recaptcha_secret_key . '&response=' . $g_validate_response;
			$curl = curl_init();// phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_init
			curl_setopt_array( $curl, array(// phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_setopt_array
				CURLOPT_URL            => $url,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_ENCODING       => "",
				CURLOPT_MAXREDIRS      => 10,
				CURLOPT_TIMEOUT        => 30,
				CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
				CURLOPT_CUSTOMREQUEST  => "POST",
				CURLOPT_POSTFIELDS     => '{}',
				CURLOPT_HTTPHEADER     => array(
					"content-type: application/json"
				),
			) );

			$response = curl_exec( $curl );// phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_exec
			$err      = curl_error( $curl );// phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_error
			curl_close( $curl );// phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_close
			if ( $err ) {
				$msg['status']  = 'invalid';
				$msg['warning'] = "*reCAPTCHA cURL Error #:" . $err;
				wp_send_json( $msg );
			} else {
				$data = json_decode( $response, true );
				if ( $settings['recaptcha_version'] == 'ver2' ) {
					if ( ! $data['success'] ) {
						$msg['status']  = 'invalid';
						$msg['warning'] = esc_html__( '*reCAPTCHA verification failed', 'woo-abandoned-cart-recovery' );
						$msg['message'] = $data;
						wp_send_json( $msg );
					}
				} else {
					$g_score = isset( $data['score'] ) ? $data['score'] : 0;
					if ( $g_score < 0.5 ) {
						$msg['status']  = 'invalid';
						$msg['warning'] = esc_html__( '*reCAPTCHA score ' . $g_score . ' lower than threshold 0.5 ', 'woo-abandoned-cart-recovery' );// phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText
						$msg['message'] = $data;
						wp_send_json( $msg );
					}
				}
			}
		}
	}
}
