<?php 
/*
 Controller name: AppUsers
 Controller description: JSON API Login , Validate login , registeration of users
 
* Plugin URI: http://ionicecommerce.com/
 * Description: A wordpress Plugin for ionicecommerce.com  app template  
 * Author: vectorcoder
 * Author URI: http://vectorcoder.com
 */

class json_api_appusers_controller

{
    public function __construct(){
        global $json_api;
        // Only Allow HTTPS. Else send an extra parameter: insecure=cool
        if (empty($_SERVER['HTTPS']) || (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'off')) {
            if (empty($_REQUEST['insecure']) || $_REQUEST['insecure'] != 'cool') {
                $json_api->error("SSL is not enabled. Use _https_ or provide a var as insecure=cool to use http protocol.");
            }
        }
    }
    public function register(){

		global $json_api;
		if(!$json_api->query->first_name){$json_api->error(" first_name is required. ");}
		if(!$json_api->query->last_name){$json_api->error(" last_name is required. ");}
		if(!$json_api->query->username){$json_api->error(" Username is required. ");}
		if(!$json_api->query->password){$json_api->error("Password is Required.");}
		if(!$json_api->query->email){$json_api->error(" Email is required. ");}
		if(!$json_api->query->display_name){$json_api->error("display_name is Required.");}
		if(!$json_api->query->nonce){$json_api->error("nonce var is required. Use the 'get_nonce' Core API method.");}		

		$username 		= sanitize_user( $json_api->query->username );
		$first_name		= sanitize_user( $json_api->query->first_name );
		$last_name 		= sanitize_user( $json_api->query->last_name );
		$password 		= sanitize_text_field( $json_api->query->password);
		$email 	  		= sanitize_email( $json_api->query->email );
		$display_name   = sanitize_text_field($json_api->query->display_name);
		$nonce 			= sanitize_text_field( $json_api->query->nonce );
		$nonce_id 		= $json_api->get_nonce_id('appusers', 'register');	
		$timeinsec 		= 1296000; /* 15*24*60*60 */		
		$notify			= 'both';		

		if(username_exists($username) || $username == 'admin'){$json_api->error(" This username Already Exist ");}
		if(email_exists($email)){$json_api->error(" This Email Already exist ");}
		if(!is_email($email)){$json_api->error(" The Email not Valid exist ");}
		//if(!wp_verify_nonce( $nonce, $nonce_id )){$json_api->error(" Invalid Nonce Value , Use the 'get_nonce' Core API method ");}		

		$userdata = array(
			'first_name'		=>	$first_name,
			'last_name'			=>	$last_name,
			'user_login'		=>	$username,
			'user_email'		=>	$email,
			'user_pass'			=>  $password,
			'display_name'		=>  $username,
			'user_nicename'		=>  $username,
			'nickname'			=>  $$username,
			'role'				=>  get_option('default_role')
		);

		

		$user_id 			= 	wp_insert_user($userdata);
		$result 			= 	wp_new_user_notification($user_id);
		$expire_time		=   time() + apply_filters('auth_cookie_expiration', $timeinsec, $user_id, true);		
		$cookie				= 	wp_generate_auth_cookie($user_id ,$expire_time , 'logged_in' );		
		$user_cookie_info   =   array('cookie'=>$cookie , 'user_id' =>$user_id);
		return $userdata;		

	} 
	public function generate_cookie(){

		global $json_api;

		if(!$json_api->query->username){$json_api->error(" Username is required. ");}

		if(!$json_api->query->password){$json_api->error("Password is Required.");}

		

		$username 		= sanitize_user( $json_api->query->username );

		$password 		= sanitize_text_field( $json_api->query->password);		

		$timeinsec 		= 1296000; /* 15*24*60*60 */	

		$user_data 		= wp_authenticate($username , $password);

		

		if(is_wp_error($user_data)){$json_api->error("Invalid username or password.", 'error', '401');

			remove_action('wp_login_failed', $json_api->query->username);

		}		

		

		$expire_time		=   time() + apply_filters('auth_cookie_expiration', $timeinsec, $user_data->id, true);		

		$cookie				= 	wp_generate_auth_cookie($user_data->id ,$expire_time , 'logged_in' );

		

		$all_user_data = array(

			"cookie" 		=> $cookie,

			"user" 			=> array(

									"id" 			=> $user_data->ID,

									"username" 		=> $user_data->user_login,

									"nicename" 		=> $user_data->user_nicename,

									"email" 		=> $user_data->user_email,

									"display_name" 	=> $user_data->display_name,

									"first_name" 	=> $user_data->user_firstname,

									"last_name" 	=> $user_data->last_name,

									"nickname" 		=> $user_data->nickname,

									"description" 	=> $user_data->user_description,

								),

						);

		return $all_user_data;		

	}	
	public function validate_cookie(){

		global $json_api;

		if(!$json_api->query->cookie){$json_api->error("required a 'cookie' value , Use the `create_auth_cookie` Auth API method to create cookie.");}

		$cookie_value  = $json_api->query->cookie;

		$validate = wp_validate_auth_cookie($cookie_value, 'logged_in') ? true : false;

		return $validate;

	}		
	public function send_mail(){
		global $json_api , $wpdb ;
		
		if(!$json_api->query->email){$json_api->error("Email is required.");}
		$user_email = $json_api->query->email;
		if(!is_email($user_email)){$json_api->error(" Email not valid ");}
		if(!$json_api->query->name){$json_api->error("Name is required.");}
		$name = $json_api->query->name;
		if(!$json_api->query->message){$json_api->error("Message is required.");}
		$message = $json_api->query->message;
		
		$content = $message. "\r\n\r\n";
		$content.="Name :".$name."\r\n\r\n";
		$content.="Email : ".$user_email."\r\n\r\n";
		
		$title	= "Contact Us";
		
		if(get_option( 'ionic_ecommerce_app_settings')) { 
			$all_settings = get_option( 'ionic_ecommerce_app_settings');
		}		
		$to_email = $all_settings['contact_us_email'];
		
		if(!wp_mail($to_email, $title, $content)){
			$json_api->error(" your host may have disabled the mail ");
		}else{
			return "Mail has been sent successfully. ";
		}	
		
	}	
	public function forgot_password(){

		global $json_api , $wpdb , $wp_hasher;

		require_once ABSPATH . 'wp-includes/class-phpass.php';

		

		if(!$json_api->query->email){$json_api->error("Email is required.");}

		$user_email  = $json_api->query->email; 

		if(!is_email($user_email)){$json_api->error(" The Email not Valid exist ");}

		if(!email_exists($user_email)){$json_api->error(" This Email not exist ");}

	    $user_data = get_user_by( 'email', trim( $user_email ) );

		

		$user_login = $user_data->user_login;

		$user_id 	= $user_data->id;	

		$get_key  	= wp_generate_password( 20, false );		

		$wp_hasher  = new PasswordHash(8, TRUE);

		$hashed_id  = $wp_hasher->HashPassword($get_key);

		

		$sql_update = "UPDATE `".$wpdb->prefix."users` SET `user_activation_key` = '".$hashed_id."' WHERE ID =".$user_id;

		$wpdb->query($sql_update);

		

		$title		= "Password Reset";

		

		$content = __('Someone requested that the password be reset for the following account:') . "\r\n\r\n";

		$content .= network_home_url( '/' ) . "\r\n\r\n";

		$content .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";

		$content .= __('If this was a mistake, just ignore this email and nothing will happen.') . "\r\n\r\n";

		$content .= __('To reset your password, visit the following address:') . "\r\n\r\n";

		$content .= '<' . network_site_url("wp-login.php?action=rp&key=$get_key&login=" . rawurlencode($user_login), 'login') . ">\r\n";		

		

		if(!wp_mail($user_email, $title, $content)){

			$json_api->error(" your host may have disabled the mail ");

		}else{

			return "A mail sent to your Email for reset password. ";

		}		 

	}	
	public function fb_connect(){
        global $json_api;
		$app_fields = 'id,name,first_name,last_name,email,picture';
		if ($json_api->query->ssl) {$enable_ssl = $json_api->query->ssl;}else{$enable_ssl = true;}
        if (!$json_api->query->access_token) { $json_api->error(" 'access_token' is required. Need a valid access_token from Facebook API.");
        } else {
			$access_token = $json_api->query->access_token;
            $url_con = 'https://graph.facebook.com/me/?fields='.$app_fields.'&access_token='.$access_token;
            $fb_con = curl_init();
            curl_setopt($fb_con, CURLOPT_URL, $url_con);
            curl_setopt($fb_con, CURLOPT_HEADER, 0);
            curl_setopt($fb_con, CURLOPT_POST, 1);
            curl_setopt($fb_con, CURLOPT_POSTFIELDS, $app_fields);
            curl_setopt($fb_con, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($fb_con, CURLOPT_SSL_VERIFYPEER, 0);
            $get_result = curl_exec($fb_con);
            curl_close($fb_con);
				
            $have_result = json_decode($get_result, true);
				
						
            if (isset($have_result['email']) && $have_result['email'] != "") {			
				
                $have_email = email_exists($have_result['email']);
                if ($have_email){
                    $user_data 		= get_user_by('email',$have_result['email']);
                    $have_user_id 	= $user_data->ID;
                    $have_user_name = $user_data->user_login;
                }
				
                if (!isset($have_user_id) && $have_email == false ) {
                    $user_name = strtolower($have_result['first_name'].'.'.$have_result['last_name']);
                    while (username_exists($user_name)) {
                        $i++;
                        $user_name = strtolower($have_result['first_name'].'.'.$have_result['last_name']).'.'.$i;
                    }
					
                    $gen_password = wp_generate_password($length = 12, $include_standard_special_chars = false);
                    $userdata = array(
                        'user_login' 	=> $user_name,
                        'user_email' 	=> $have_result['email'],
                        'user_pass' 	=> $gen_password,
                        'display_name' 	=> $have_result['name'],
                        'first_name' 	=> $have_result['first_name'],
                        'last_name' 	=> $have_result['last_name']
                    );
                    $have_insert_id = wp_insert_user($userdata);
					$have_user_id   = $have_insert_id;
					
                    if ($have_insert_id) $user_account = 'user registered.';
                } else {
                    if ($have_user_id) $user_account = 'user logged in.';
                }
				
				$timeinsec 	= 1296000; /* 15*24*60*60 */
				$expire_time= time() + apply_filters('auth_cookie_expiration', $timeinsec, $have_user_id, true);
				$cookie	= wp_generate_auth_cookie($have_user_id ,$expire_time , 'logged_in' );
				
                $response['msg'] 		= $user_account;
                $response['id'] 		= $have_user_id;
                $response['cookie'] 	= $cookie;
                $response['user_login'] = $user_name;
                $response['user'] 		= $have_result;
				
				
            } else {
                $response['msg'] = "Your 'access_token' not valid. Get extended permission while joining the Facebook app.";
            }
        }
        return $response;
    }	
	public function update_user_profile(){
		global $json_api , $wpdb;
		
		
		if(!$json_api->query->user_id){$json_api->error("'user_id' var is required.");}
			$user_id = $json_api->query->user_id;		
			$user 	 = get_userdata( $user_id );
		if ( ! $user ) {
			$json_api->error("Invalid User Id."); 
		}

		if ( isset($json_api->query->email) && !email_exists($json_api->query->email) && $json_api->query->email !== $user->user_email) {
			$json_api->error("Email Address is Invalid."); 
		}	
		
		$new_user = array(
				'ID' 	=> $user_id
		);
		$billing  = array();
		$shipping = array();
		
		
		if ( isset( $json_api->query->password) ){
			$new_user['user_pass'] = $json_api->query->password;
		}		
		if ( isset( $json_api->query->email) ){
			$new_user['user_email'] = $json_api->query->email;
		}
		if ( isset( $json_api->query->first_name) ){
			$new_user['first_name'] = $json_api->query->first_name;
		}
		if ( isset( $json_api->query->last_name) ){
			$new_user['last_name'] = $json_api->query->last_name;
		}
		if ( isset( $json_api->query->nickname) ){
			$new_user['nickname'] = $json_api->query->nickname;
		}
		if ( isset( $json_api->query->user_nicename) ){
			$new_user['user_nicename'] = $json_api->query->user_nicename;
		}
		
		if ( isset( $json_api->query->dislay_name) ){
			$new_user['display_name'] = $json_api->query->dislay_name;
		}		
		
		
		if ( isset( $json_api->query->user_url) ){
			$new_user['user_url'] = $json_api->query->user_url;
		}
		if ( isset( $json_api->query->description) ){
			$new_user['description'] = $json_api->query->description;
		}
		
		
		
		
		
		if(isset($json_api->query->billing_first_name)){  
			$billing['billing_first_name'] =  $json_api->query->billing->first_name;
		}
		
		if(isset($json_api->query->billing_last_name)){
			$billing['billing_last_name'] =  $json_api->query->billing->last_name;
		}
		
		if(isset($json_api->query->billing_company)){
			$billing['billing_company'] =  $json_api->query->billing->company;
		}
		
		if(isset($json_api->query->billing_address_1)){
			$billing['billing_address_1'] =  $json_api->query->billing->address_1;
		}
		
		if(isset($json_api->query->billing_address_2)){
			$billing['billing_address_2'] =  $json_api->query->billing->address_2;
		}
		
		if(isset($json_api->query->billing_city)){
			$billing['billing_city'] =  $json_api->query->billing->city;
		}
		
		if(isset($json_api->query->billing_postcode)){
			$billing['billing_postcode'] =  $json_api->query->billing->postcode;
		}
		
		if(isset($json_api->query->billing_country)){
			$billing['billing_country'] =  $json_api->query->billing->country;
		}
		
		if(isset($json_api->query->billing_state)){
			$billing['billing_state'] =  $json_api->query->billing->state;
		}
		
		if(isset($json_api->query->billing_phone)){
			$billing['billing_phone'] =  $json_api->query->billing->phone;
		}
		
		if(isset($json_api->query->billing_email)){
			$billing['billing_email'] =  $json_api->query->billing->email;
		}
		
		
		if(isset($json_api->query->shipping_first_name)){  
			$shipping['shipping_first_name'] =  $json_api->query->shipping->first_name;
		}
		
		if(isset($json_api->query->shipping_last_name)){
			$shipping['shipping_last_name'] =  $json_api->query->shipping->last_name;
		}
		
		if(isset($json_api->query->shipping_company)){
			$shipping['shipping_company'] =  $json_api->query->shipping->company;
		}
		
		if(isset($json_api->query->shipping_address_1)){
			$shipping['shipping_address_1'] =  $json_api->query->shipping->address_1;
		}
		
		if(isset($json_api->query->shipping_address_2)){
			$shipping['shipping_address_2'] =  $json_api->query->shipping->address_2;
		}
		
		if(isset($json_api->query->shipping_city)){
			$shipping['shipping_city'] =  $json_api->query->shipping->city;
		}
		
		if(isset($json_api->query->shipping_postcode)){
			$shipping['shipping_postcode'] =  $json_api->query->shipping->postcode;
		}
		
		if(isset($json_api->query->shipping_country)){
			$shipping['shipping_country'] =  $json_api->query->shipping->country;
		}
		
		if(isset($json_api->query->shipping_state)){
			$shipping['shipping_state'] =  $json_api->query->shipping->state;
		}				
		
		$user_id = wp_update_user( $new_user );		
			
		if ( is_wp_error( $user_id ) ) {
			$json_api->error("There was an error, probably that user doesn't exist."); 
		}
		
		foreach($billing as $key => $value){ 
			update_user_meta( $user_id, $key, $value);
		}
		
		foreach($shipping as $key => $value){ 
			update_user_meta( $user_id, $key, $value);
		}
			
		$user_output 	= get_userdata( $user_id );	
		$user_output	= $user_output->data;
		$user_meta 		= array_map( function( $a ){ return $a[0]; }, get_user_meta( $user_id ) );
		$user_output->billing->first_name   = $user_meta['billing_first_name']; 
		$user_output->billing->last_name  	= $user_meta['billing_last_name']; 
		$user_output->billing->company  	= $user_meta['billing_company']; 
		$user_output->billing->address_1  	= $user_meta['billing_address_1']; 
		$user_output->billing->address_2 	= $user_meta['billing_address_2']; 
		$user_output->billing->city  		= $user_meta['billing_city']; 
		$user_output->billing->postcode  	= $user_meta['billing_postcode']; 
		$user_output->billing->country  	= $user_meta['billing_country']; 
		$user_output->billing->state  		= $user_meta['billing_state']; 
		$user_output->billing->phone 		= $user_meta['billing_phone']; 
		$user_output->billing->email  		= $user_meta['billing_email']; 
		
		$user_output->shipping->first_name     = $user_meta['shipping_first_name']; 
		$user_output->shipping->last_name      = $user_meta['shipping_last_name']; 
		$user_output->shipping->company  		= $user_meta['shipping_company']; 
		$user_output->shipping->address_1  	= $user_meta['shipping_address_1']; 
		$user_output->shipping->address_2 		= $user_meta['shipping_address_2']; 
		$user_output->shipping->city  			= $user_meta['shipping_city']; 
		$user_output->shipping->postcode  		= $user_meta['shipping_postcode']; 
		$user_output->shipping->country  		= $user_meta['shipping_country']; 
		$user_output->shipping->state  		= $user_meta['shipping_state']; 
		//$user_output->shipping = $shipping;
		
		return $user_meta;
		
	}
	public function ionic_reward_points_settings(){

		global $json_api , $wpdb;

		$wc_points_settings = array();

		$earn_data = explode(':' ,get_option( 'wc_points_rewards_earn_points_ratio'));
		$rede_data = explode(':' ,get_option( 'wc_points_rewards_redeem_points_ratio'));

		$wc_points_settings['wc_points_rewards_earn_points_ratio'][earnPoint]    = $earn_data[0];
		$wc_points_settings['wc_points_rewards_earn_points_ratio'][equalTo]      = $earn_data[1];
		$wc_points_settings['wc_points_rewards_redeem_points_ratio'][redeemPoint]  = $rede_data[0];
		$wc_points_settings['wc_points_rewards_redeem_points_ratio'][equalTo]    = $rede_data[1];
		$wc_points_settings['wc_points_rewards_cart_max_discount']    = get_option( 'wc_points_rewards_cart_max_discount');
		$wc_points_settings['wc_points_rewards_max_discount']  		  = get_option( 'wc_points_rewards_max_discount');
		$wc_points_settings['wc_points_rewards_points_expiry']  	  = get_option( 'wc_points_rewards_points_expiry');
		$wc_points_settings['wc_points_rewards_account_signup_points']= get_option( 'wc_points_rewards_account_signup_points');
		$wc_points_settings['wc_points_rewards_write_review_points']  = get_option( 'wc_points_rewards_write_review_points');				

		return  array('data'=>$wc_points_settings);	
	}	
	public function ionic_reward_points(){

		global $json_api , $wpdb;

		if(!$json_api->query->user_id){$json_api->error(" user_id is required. ");}

		$user_id = $json_api->query->user_id;

		$table_points = $wpdb->prefix."wc_points_rewards_user_points_log"; 

		$get_points = "select *  from `".$table_points."` where `user_id`=".$user_id;

		$have_points = $wpdb->get_results($get_points);		

		return  array('data'=>$have_points);	
	}	
	public function ionic_register_device(){

		global $json_api , $wpdb;

		if(!$json_api->query->device_id){$json_api->error(" device_id is required. ");}
		
			$device_id     = $json_api->query->device_id;
			$user_id       = $json_api->query->user_id;
			$update_date   = date("Y-m-d h:i:s");
			$register_date = date("Y-m-d h:i:s");
			
			if($user_id){

				$update_android_devide_user = "UPDATE `".IONIC_NOTIFICATION_DEVICES."` set `user_id`='".$user_id."' , `status`='1' , `update_date`='".$update_date."'  where `device_id`='".$device_id."'";
				 if($wpdb->query($update_android_devide_user)){
					$msg = "User Upated Successfully";
				 }
			}else{
				$check_ae_device_have = "select * from `".IONIC_NOTIFICATION_DEVICES."` where `device_id`='".$device_id."'";
				$have_ae_device = $wpdb->get_results($check_ae_device_have);
				if($have_ae_device == "" || $have_ae_device == 'null'){
					$insert_android_devide = "insert into `".IONIC_NOTIFICATION_DEVICES."` set `device_id`='".$device_id."', `update_date`='".$update_date."' , `register_date`='".$register_date."'";
					if($wpdb->query($insert_android_devide)){
						$msg = "Device registered Successfully";
					 }
				}
			}		

		return $msg;
	}
	public function ionic_coupon_notification(){

		global $json_api , $wpdb;
		if(!$json_api->query->user_id){$json_api->error(" user_id is required. ");}
		$user_id = $json_api->query->user_id;
	
		$get_include_player_idsa	  = "SELECT * FROM `".IONIC_ALL_NOTIFICATION."` where `type`=1 && `user_id`='".$user_id."'";
	
		$show_include_player_idsa  = $wpdb->get_results($get_include_player_idsa);	
		return array('data'=>$show_include_player_idsa);

	}
	public function ionic_notification_update(){

		global $json_api , $wpdb;
		if(!$json_api->query->notification_id){$json_api->error(" notification_id is required. ");}
		$notification_id = $json_api->query->notification_id;
	
		$get_update_notification   = "update `".IONIC_ALL_NOTIFICATION."` set `is_view`=1 where `id`='".$notification_id."'";
		if($wpdb->query($get_update_notification)){	
			$note =  "Notification Updated";	
		}else {
			$note =  "Sorry Something Wrong Here";
		}

		return $note;
	}   
	
} ?>