<?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="<?php echo $notification['nbt_product_notification_sitekey'];?>"<?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: nbt_solutions.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');

		$post_data = http_build_query(
			array(
				'secret' => $product_notification['nbt_product_notification_secret'],
				'response' => $_REQUEST['recaptcha'],
				'remoteip' => $_SERVER['REMOTE_ADDR']
			)
		);
		$opts = array('http' =>
			array(
				'method'  => 'POST',
				'header'  => 'Content-type: application/x-www-form-urlencoded',
				'content' => $post_data
			)
		);
		$context  = stream_context_create($opts);
		
		$notice = array();
		$error = false;
      	if(!$email || !is_email($email) ){
      		$notice[] = __('No email address was provided', 'nbt-solution');
      		$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(__('The email address you have entered is already registered.', 'nbt-solution'), '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.', 'nbt-solution'), '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'];
			    }

				$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
				$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(__('The email address you have entered is already registered.', 'nbt-solution'), '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.', 'nbt-solution'), 'message');
						}
      				}


			    }else{
			        $json['msg'] = $this->show_notice(__('Captcha is wrong, please refresh this page and try again!', 'nbt-solution'), '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();