<?php
if( ! function_exists( 'add_coupon_notification_checkbox' ) ) {
function add_coupon_notification_checkbox() { 
    woocommerce_wp_checkbox( array( 'id' => 'coupon_push_notification', 'label' => __( 'Push Notification', 'woocommerce' ), 'description' => sprintf( __( 'Send Push notification to all user', 'woocommerce' ) ) ) );
}

add_action( 'woocommerce_coupon_options', 'add_coupon_notification_checkbox', 10, 0 );
}

function save_coupon_notification_ionicecommerce( $post_id ) { global $wpdb;
    $include_stats = isset( $_POST['coupon_push_notification'] ) ? 'yes' : 'no';
    update_post_meta( $post_id, 'coupon_push_notification', $include_stats );
	
	if($include_stats == 'yes'){
		
		$post_coupon_ae   = get_post( $post_id );
		$title_ae    = $post_coupon_ae->post_title;
		$output_ae   = $post_coupon_ae->post_excerpt;
		$expire_date = get_post_meta( $post_id, 'expiry_date', true ); 
		
		$content_ae  = array( "en" => $output_ae );		
		$headings_ae = array( "en" => 'A New Scaratch Card!' );

		$get_include_player_ids	  = "SELECT * FROM `".IONIC_NOTIFICATION_DEVICES."` where `device_id`!='' && `user_id`>='1'";
		$show_include_player_ids  = $wpdb->get_results($get_include_player_ids);	
		foreach($show_include_player_ids as $sipi){						
			$all_ae_devices[] = $sipi->device_id;
			$all_ae_users[]   = $sipi->user_id;				
		}	

		if(get_option( 'ionic_ecommerce_app_settings')) { 
			$all_app_settings = get_option( 'ionic_ecommerce_app_settings');
		}

		$app_id  = $all_app_settings['one_signal_app_id'];   //'02a78165-197f-46f7-929e-8f2bbb1b1253'; 
		$api_key = $all_app_settings['one_signal_app_key'];  //'MGJjNDQ1MTYtNDhmOC00ZWYzLWIyMzQtNmI5OWE4ZTA0Mjgx';

		if($app_id != "" && $api_key != ""){
		
			$fields_ae = array(
			   'app_id' => $app_id,
			   'include_player_ids' => $all_ae_devices,		   
			   'contents' => $content_ae,
			   'headings'=>$headings_ae,
               'code'=>$title_ae,
               'type'=>'1'
			);
			
			
			
			$fields_ae = json_encode($fields_ae);
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
					   'Authorization: Basic $api_key'));
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
			curl_setopt($ch, CURLOPT_HEADER, FALSE);
			curl_setopt($ch, CURLOPT_POST, TRUE);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_ae);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		
			$result = curl_exec($ch);
			$data = json_decode($result);
			curl_close($ch);
	
			if(!empty($data->recipients) and $data->recipients >= 1){
				$response = '1';
				
				
			
				foreach($all_ae_users as $user_num){
					$insert_user_note = "insert into `".IONIC_ALL_NOTIFICATION."` set `user_id`='".$user_num."' , `code`='".$title_ae."', `message`='".$output_ae."' , `expire_date`='".$expire_date."'";
					$wpdb->query($insert_user_note);
				}
			}	
		}			
	}
	
} ?>