<?php

class NBT_Notification_Frontend{
	function __construct() {
		add_action( 'woocommerce_before_single_product', array($this, 'notification_register_hooks') );
		add_action('wp_enqueue_scripts', array($this, 'embed_style'));


		add_action( 'wp_ajax_nopriv_nbtpn_notification', array($this, 'nbtpn_notification') );
		add_action( 'wp_ajax_nbtpn_notification', array($this, 'nbtpn_notification') );

		add_action( 'save_post', array($this, 'update_post_meta'), 10, 3  );
	}

	public function update_post_meta($post_id, $post, $update){
		$post_type = get_post_type($post_id);

		if ( "product" != $post_type ) return;

		$product = wc_get_product($post_id);
		if( $product->is_in_stock() ){
			$in_stock = true;
		}

		if($product->managing_stock() && get_post_meta($post_id, '_stock', true)){
			$in_stock = true;
		}

		if(isset($in_stock)){
			$_product_notification = get_post_meta($post_id, '_product_notification', true);
			if(is_array($_product_notification) && !empty($_product_notification)){
				$to = array();
				foreach ($_product_notification as $k_noti => $v_noti) {
					if(!$v_noti){
						$email_name = explode('@', $k_noti);
						$to[] = $email_name[0] .' <'.$k_noti.'>';

						$_product_notification[$k_noti] = true;
					}

				}

				if(!empty($to)){
					$subject = "Learning how to send an Email in WordPress";
					$content = "WordPress knowledge";
					$status = wp_mail($to, $subject, $content);
					update_post_meta( $post_id, '_product_notification', $content );
				}


			}
		}
		
	}

	public function notification_register_hooks(){
		global $product;

		if( !$product->is_in_stock() ){
			$out_stock = true;
		}

		if($product->managing_stock()){
			$allow_backorders = get_post_meta( $product->get_id(), '_backorders', true );
			if($allow_backorders == 'no'){
				$out_stock = true;
			}
		}

		if(isset($out_stock)){
			$this->out_stock = $out_stock;
			add_action('woocommerce_single_product_summary', array($this, 'show_out_stock'), 20);
			add_filter( 'woocommerce_get_stock_html', '__return_empty_string' );
			

		}
	}

	public function show_out_stock(){
		global $product;
		$notification = get_option('product-notification_settings');
		if($notification){
		?>
		<div class="nbt-alert-msg"></div>
		<div id="nbt-alert">
			<h4 class="nbt_alerts_headline"><?php echo $notification['nbt_product_notification_title'];?></h4>
			<p><?php echo str_replace('\\', '', $notification['nbt_product_notification_desc']);?></p>
			<form>
				<?php
				$email = '';
				$email_class = '';
				$captcha_class = '';
				if ( is_user_logged_in() ) {
					$current_user = wp_get_current_user();
					$email = $current_user->data->user_email;
					$email_class = ' style="display: none"';
					$captcha_class = ' style="display: none"';
				}?>
	
				<input type="email" name="nbt_alerts_email" id="nbt_alerts_email" value="<?php echo $email;?>" placeholder="Email Address"<?php echo $email_class;?>>
				<div class="g-recaptcha" data-sitekey="6LfkCC0UAAAAACNO67926ogFbUVPzA-Tuea-_OsY"<?php echo $captcha_class;?>></div>
				<input type="submit" class="button" name="update_cart" id="nbt_alerts_submit" value="<?php echo $notification['nbt_product_notification_button'];?>">
				<?php if ( is_user_logged_in() ) {?>
					<a href="#" class="nbt-notifi-change"><?php echo $notification['nbt_product_notification_change_email'];?></a>
				<?php }?>
			</form>
		</div>
		<script type="text/javascript">
			jQuery(document).ready(function($){
				$(document).on('click', '#nbt_alerts_submit', function(){
					$('.nbt-alert-msg').hide();
					$('#nbt-alert').block({
						message: null,
						overlayCSS: {
							background: '#fff',
							opacity: 0.6
						}
					});
					$.ajax({
						url: wc_add_to_cart_params.ajax_url,
						data: {
							action:     'nbtpn_notification',
							product_id: <?php echo $product->get_id();?>,
							email: $('#nbt_alerts_email').val(),
							recaptcha: grecaptcha.getResponse()
						},
						type: 'POST',
						datatype: 'json',
						success: function( response ) {
							var rs = JSON.parse(response);
							if(rs.complete != undefined){
								$('#nbt-alert').remove();
								$('.nbt-alert-msg').html(rs.msg).hide().slideToggle(500);
							}else{
								$('.nbt-alert-msg').html(rs.msg).hide().slideToggle(500);
							}
			
							$('#nbt-alert').unblock();

						},
						error:function(){
							alert('There was an error when processing data, please try again !');
							$('#nbt-alert').unblock();
						}
					});
					return false;
				});

				$(document).on('click', '.nbt-notifi-change', function(){
					$('#nbt_alerts_email').slideDown();

					return false;

				});

			});
		</script>

		<?php
		}
	}

	public function embed_style(){
		if(is_product()){
			wp_enqueue_script( 'recaptcha-solutions', 'https://www.google.com/recaptcha/api.js', null, null, true );
		}
		
	}

	public function nbtpn_notification(){
		$product_id = absint($_REQUEST['product_id'] );
		$recaptcha    = $_REQUEST['recaptcha'];
		$email    = $_REQUEST['email'];
		$product = wc_get_product($product_id);

		$product_notification = get_option('product_notification_settings');

		$api_url     = 'https://www.google.com/recaptcha/api/siteverify';
		$site_key    = '6LfkCC0UAAAAACNO67926ogFbUVPzA-Tuea-_OsY';
		$secret_key  = '6LfkCC0UAAAAAPTTWOBbrQCPz904HAMoADZAr_lu';
		if(isset($product_notification['nbt_product_notification_sitekey'])){
			$site_key = $product_notification['nbt_product_notification_sitekey'];
		}
		if(isset($product_notification['nbt_product_notification_secret'])){
			$secret_key = $product_notification['nbt_product_notification_secret'];
		}
		$notice = array();
		$error = false;
      	if(!$email || !is_email($email) ){
      		$notice[] = 'No email address was provided';
      		$error = true;
      	}

      	if(!$recaptcha && !is_user_logged_in()){
      		$notice[] = 'Please check the captcha form.';
      		$error = true;
      	}

      	if(!$error){
      		if( is_user_logged_in() ){
				$current_user = wp_get_current_user();
      			$product_notifi = get_post_meta( $product_id, '_product_notification', true );
      			if(!$product_notifi){
      				$product_notifi = array(
      					$email => false
      				);
			    	$true = true;
      			}else{
      				if(isset($product_notifi[$email])){
      					$json['msg'] = $this->show_notice('Da dang ky', 'error');
      				}else{
	      				$product_notifi = array_merge($product_notifi, array(
	      					$email => false
	      				));
				    	$true = true;
      				}
      			}
      			update_post_meta( $product_id, '_product_notification', $product_notifi);

      			if(isset($true)){
			    	$notification = get_option('product-notification_settings' );
					$subject = str_replace('%product%', $product->get_name(), $notification['nbt_product_notification_email_title']);
					$message = str_replace('%product%', $product->get_name(), $notification['nbt_product_notification_email_desc']);
					$result = wp_mail($email, $subject, $message);
					if($result){
				    	$json['complete'] = true;
				        $json['msg'] = $this->show_notice('Thank you! We will notify you when your item is back in stock.', 'message');
					}
      			}
      		}else{
			    //lấy IP của khach
			    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
			        $remoteip = $_SERVER['HTTP_CLIENT_IP'];
			    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
			        $remoteip = $_SERVER['HTTP_X_FORWARDED_FOR'];
			    } else {
			        $remoteip = $_SERVER['REMOTE_ADDR'];
			    }

			    //tạo link kết nối
			    $api_url = $api_url.'?secret='.$secret_key.'&response='.$recaptcha.'&remoteip='.$remoteip;
			    //lấy kết quả trả về từ google
			    $response = file_get_contents($api_url);
			    //dữ liệu trả về dạng json
			    $response = json_decode($response);

			    if($response->success == true)
			    {

			    	$product_notifi = get_post_meta( $product_id, '_product_notification', true );
	      			if(!$product_notifi){
	      				$product_notifi = array(
	      					$email => false
	      				);
				    	$true = true;
	      			}else{
	      				if(isset($product_notifi[$email])){
	      					$json['msg'] = $this->show_notice('Da dang ky', 'error');
	      				}else{
		      				$product_notifi = $product_notifi + array(
		      					$email => false
		      				);
					    	$true = true;
	      				}
	      			}
	      			update_post_meta( $product_id, '_product_notification', $product_notifi);

      				if(isset($true)){
				    	$notification = get_option('product-notification_settings' );
						$subject = str_replace('%product%', $product->get_name(), $notification['nbt_product_notification_email_title']);
						$message = str_replace('%product%', $product->get_name(), $notification['nbt_product_notification_email_desc']);
						$result = wp_mail($email, $subject, $message);
						if($result){
					    	$json['complete'] = true;
					        $json['msg'] = $this->show_notice('Thank you! We will notify you when your item is back in stock.', 'message');
						}
      				}


			    }else{
			        $json['msg'] = $this->show_notice('Captcha khong dung', 'error');
			    }
      		}

		}else{
			$json['msg'] = $this->show_notice($notice, 'error');
		}
	    echo wp_json_encode($json, TRUE);
		wp_die();
	}

	public function show_notice($msg, $class){
		$html = '<ul class="woocommerce-'.$class.'" style="display: block;">';
		if(is_array($msg)){
			foreach ($msg as $m) {
				$html .= '<li>'.$m.'</li>';
			}
		}else{
			$html .= '<li>'.$msg.'</li>';
		}
		$html .= '</ul>';
		return $html;
	}
}
new NBT_Notification_Frontend();