<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Payresponse extends CI_Controller {
     
	public function __construct()
	{
	    parent::__construct();
	   
	} 
	
	/**********************payment by wallet and COD start**********************/
	
	public function wallet_paymentprocess(){
		if(isset($_POST['order_id'])){
			$update_orderid = $_POST['order_id'];
			$update_userid	= $_POST['userid'];
			$order_uniqid   = $_POST['order_uniqid'];
			$order_uname    = $_POST['o_username'];
			$total_amount   = $_POST['final_amount'];
			$cart_amount    = $total_amount;
			$user_wallet = $this->Data_access_model->select_data('wallet_amount','hs_user_wallet',array('wallet_uid' =>$update_userid));
			if($user_wallet->num_rows() > 0)
			{
				$current_wallet = $user_wallet->row();
				if($current_wallet->wallet_amount >= $cart_amount)
				{
					$wallet_debit = $current_wallet->wallet_amount - $cart_amount;
					$this->Data_access_model->update_data('hs_user_wallet',array('wallet_uid' =>$update_userid),array('wallet_amount' =>$wallet_debit));
					if($this->db->affected_rows() > 0)
					{
						$this->payment_bywallet_success($update_orderid,$order_uniqid,$order_uname);
					}
				}else{
					$this->payment_response('failed','',$order_uname ,'Insufficient wallet amount! Please Recharge your wallet. and Try Again !');
				}
			}
			
		}else{
			$this->payment_response('failed','','','something went wroung');
		}		
	}
	
	//WALLET PAYMENT SUCCESS
	public function payment_bywallet_success($order_id='',$odr_uniqid='',$order_user_name){
		if(isset($order_id) && !empty($order_id)){
			$this->cart->destroy();
			$update_orderid = $order_id; 
			 
			$paymentdetails  = array('payment_status' =>1);	
			$success =0;
			$this->Data_access_model->update_data('hs_user_orders',array('order_id'=>$update_orderid),$paymentdetails);
			if($this->db->affected_rows() > 0){
				 
				$order_details = $this->Data_access_model->select_data('*','hs_user_orders',array('order_id' =>$update_orderid));
				if($order_details->num_rows() > 0){
					$ordered_prod = $order_details->row();
					$all_pid = json_decode($ordered_prod->order_pid); 
					foreach($all_pid as $pid){
						 
						$prod_details = $this->Data_access_model->select_data('*','hs_products',array('prod_id' =>$pid->id));
						if($prod_details->num_rows() > 0){
							$check_qty = $prod_details->row();
							if($check_qty->prod_quantity ==''){
								$success++;
							}else if($check_qty->prod_quantity >= $pid->qty){
										
								$new_quantity = $check_qty->prod_quantity - $pid->qty;
										
								$this->Data_access_model->update_data('hs_products',array('prod_id'=>$pid->id),array('prod_quantity'=>$new_quantity));
											
								if($this->db->affected_rows() > 0){
									$success++; 
								}
							}
						} 
					}
				} 
			}
		} 
		if(isset($_SESSION['discount_amount'])){
								 
			$coupen_details = $this->Data_access_model->select_data('*','hs_offers',array('coupen_code'=>$_SESSION['copen_code']));
			if($coupen_details->num_rows() > 0){
				 
				$check_limit = $coupen_details->result_array();
				if($check_limit[0]['coupen_uses_limt'] >0 ){
					$coupen_newlimit = $check_limit[0]['coupen_uses_limt'] - 1;
					$this->Data_access_model->update_data('hs_offers',array('coupen_code'=>$_SESSION['copen_code']),array('coupen_uses_limt'=>$coupen_newlimit));
				}
			}
			unset($_SESSION['discount_amount']);
			unset($_SESSION['copen_code']);
			if(isset($_SESSION['discount_prodid'])){
				unset($_SESSION['discount_prodid']);
			}
		}
		
		if($success >0){
			$this->payment_response('success',$odr_uniqid,$order_user_name,'');
			$this->sending_mail($update_orderid);
		}
	}

	//*****************payment by wallet end******************//	
		
		
	//*****************payment by COD start******************//	
		
	//COD SUCCESS
		
	public function cod_success(){
		
		if(isset($_POST['order_id'])){
			$this->cart->destroy();
			$update_orderid = $_POST['order_id'];
			$update_userid	= $_POST['userid'];
			$order_uniqid   = $_POST['order_uniqid'];
			$order_uname    = $_POST['o_username'];  
			$success =0;
			$order_details = $this->Data_access_model->select_data('*','hs_user_orders',array('order_id' =>$update_orderid));
			if($order_details->num_rows() > 0){
				$ordered_prod = $order_details->row();
				$all_pid = json_decode($ordered_prod->order_pid); 
				foreach($all_pid as $pid)
				{
					$prod_details = $this->Data_access_model->select_data('*','hs_products',array('prod_id' =>$pid->id));
					if($prod_details->num_rows() > 0){
						$check_qty = $prod_details->row();
						if($check_qty->prod_quantity ==''){
							$success++; 
						}else if($check_qty->prod_quantity >= $pid->qty){
							$new_quantity = $check_qty->prod_quantity - $pid->qty;
							$this->Data_access_model->update_data('hs_products',array('prod_id'=>$pid->id),array('prod_quantity'=>$new_quantity));
							if($this->db->affected_rows() > 0){
								$success++; 
							}
						}
					} 
				}
			}
			
			if(isset($_SESSION['discount_amount'])){
								 
				$coupen_details = $this->Data_access_model->select_data('*','hs_offers',array('coupen_code'=>$_SESSION['copen_code']));
				if($coupen_details->num_rows() > 0){
					 
					$check_limit = $coupen_details->result_array();
					if($check_limit[0]['coupen_uses_limt'] >0 ){
						$coupen_newlimit = $check_limit[0]['coupen_uses_limt'] - 1;
						$this->Data_access_model->update_data('hs_offers',array('coupen_code'=>$_SESSION['copen_code']),array('coupen_uses_limt'=>$coupen_newlimit));
					}
				}
				unset($_SESSION['discount_amount']);
				unset($_SESSION['copen_code']);
				if(isset($_SESSION['discount_prodid'])){
					unset($_SESSION['discount_prodid']);
				}
			}
			if($success >0){
				$this->payment_response('success',$order_uniqid ,$order_uname,'');
				$this->sending_mail($update_orderid);
			}
		} 
	}	
	//*****************payment by COD end******************/
	/**********************payment by wallet and COD start*****************/	
		
	
	/***************payment by paypal start*****************/
	//paypal failture	
	public function paypalfailture(){
		$this->payment_response('failed','','','You may try making the payment again');
	}
	
	//paypal success
	public function paypalsuccess(){
		$this->cart->destroy();
		if(isset($_SESSION['discount_amount'])){
								 
				$coupen_details = $this->Data_access_model->select_data('*','hs_offers',array('coupen_code'=>$_SESSION['copen_code']));
				if($coupen_details->num_rows() > 0){
					 
					$check_limit = $coupen_details->result_array();
					if($check_limit[0]['coupen_uses_limt'] >0 ){
						$coupen_newlimit = $check_limit[0]['coupen_uses_limt'] - 1;
						$this->Data_access_model->update_data('hs_offers',array('coupen_code'=>$_SESSION['copen_code']),array('coupen_uses_limt'=>$coupen_newlimit));
					}
				}
				unset($_SESSION['discount_amount']);
				unset($_SESSION['copen_code']);
				if(isset($_SESSION['discount_prodid'])){
					unset($_SESSION['discount_prodid']);
				}
		}
		$this->payment_response('success','','','your order has booked successfully, please check your mail for more detail');
	} 
	
	//paypal notify url
	public function paypalnotify_url(){
		  
		$update_orderid = $_POST['custom'];  
		$payment_txnId = (isset($_POST['txn_id']) ? $_POST['txn_id'] : '');		
		$paymentdetails  = array( 
								'payment_status' 	=>1,
								'payment_txnid'		=>$payment_txnId,  
								);	
			
		$this->Data_access_model->update_data('hs_user_orders',array('order_id'=>$update_orderid),$paymentdetails);
		if($this->db->affected_rows() > 0){
			 
			$order_details = $this->Data_access_model->select_data('*','hs_user_orders',array('order_id' =>$update_orderid));
			if($order_details->num_rows() > 0){
				$ordered_prod = $order_details->row();
				$all_pid = json_decode($ordered_prod->order_pid); 
				foreach($all_pid as $pid){
					$prod_details = $this->Data_access_model->select_data('*','hs_products',array('prod_id' =>$pid->id));
					if($prod_details->num_rows() > 0){
						$check_qty = $prod_details->row();
						if($check_qty->prod_quantity ==''){
							$this->sending_mail($update_orderid);
						}else if($check_qty->prod_quantity >= $pid->qty){
						
							$new_quantity = $check_qty->prod_quantity - $pid->qty;
						
							$this->Data_access_model->update_data('hs_products',array('prod_id'=>$pid->id),array('prod_quantity'=>$new_quantity));
							
							if($this->db->affected_rows() > 0){
								$this->sending_mail($update_orderid);
							}
						}
									
					} 
				}
			} 			
		}	
	}
	//*****************payment by paypal end******************//


	//***************payment by payumoney start**************//	

	//payumoney success
	
	public function payusuccess(){
		if(isset($_POST["status"])){
			$status = $_POST["status"];
			$amount = $_POST["amount"];
			$firstname =$_POST["firstname"];
			$email = $_POST["email"];
			$contact = $_POST['phone'];
			$txnid  = $_POST["txnid"];
			$posted_hash = $_POST["hash"];
			$key = $_POST["key"];
			$productinfo = $_POST["productinfo"];
			$email = $_POST["email"];
			$salt = 'l1hMFGsCMl';
			$udf1 = $_POST['udf1']; //payment_uid
			$udf2 = $_POST['udf2']; //payment_uniqid
			$udf3 = $_POST['udf3']; //payment_pid
			$udf4 = $_POST['udf4']; //address
			$udf5 = $_POST['udf5']; // city+pincode+coupen_code+discount_amount
			$address = explode("|",$udf5);
			$city = $address[0]; //city
			$pincode = $address[1];// pincode
			$coupen_code = $address[2]; // Coupen code 
			$discount_amount = $address[3]; // discount_amount
			If (isset($_POST["additionalCharges"])) {
				$additionalCharges = $_POST["additionalCharges"];
				$retHashSeq = $additionalCharges . '|' . $salt . '|' . $status . '|||||||||||' . $email . '|' . $firstname . '|' . $productinfo . '|' . $amount . '|' . $txnid . '|' . $key;
			} else {

				$retHashSeq = $salt . '|' . $status . '||||||'.$udf5.'|'.$udf4.'|'.$udf3.'|'.$udf2.'|'.$udf1.'|' . $email . '|' . $firstname . '|' . $productinfo . '|' . $amount . '|' . $txnid . '|' . $key;
			}
			$hash = hash("sha512", $retHashSeq);

			if ($hash != $posted_hash) {
				//echo "Invalid Transaction. Please try again";
				$this->payment_response('failed','','$firstname','Invalid Transaction. Please try again');
			}else{
			
				$currency_code = $this->hs->getwebsettings('currency_code');
				if($currency_code !== 'INR'){
					$converted_amount = (int) $this->currencyConverter_new('INR',$currency_code,$amount);
				
					$total_amount = 1 + (int) round($converted_amount,2);  
	
				}else{
		
					$total_amount = $amount;
				}
						
				$paymentdetails  = array( 
			
				'order_uniqid' =>$udf2,
				'order_uid'    =>$udf1,
				'order_pid'    =>$productinfo,  //json_encode($order_info),
				'order_date'   =>date('d M Y h:i:s'),
				'order_contact'=>$contact,
				'order_amount' =>$total_amount, 
				'payment_mode' =>2,
				'order_email'  => $email,
				'delivery_address'=>$udf4,
				'order_city'   => $city ,
				'city_pincode' => $pincode,
				'payment_status' => 1,
				'payment_txnid'	=> $txnid, 
				'used_coupen_code'=>$coupen_code,
				'discount_amount'=>$discount_amount,
				);
				$this->Data_access_model->insert_data('hs_user_orders',$paymentdetails);
				$order_id = $this->db->insert_id(); 
				$proid = json_decode($productinfo);
				foreach($proid as $pid){
						 
					$prod_details = $this->Data_access_model->select_data('*','hs_products',array('prod_id' =>$pid->id));
					if($prod_details->num_rows() > 0){
						$check_qty = $prod_details->row();
						if($check_qty->prod_quantity ==''){
										
						}else if($check_qty->prod_quantity >= $pid->qty){
									
							$new_quantity = $check_qty->prod_quantity - $pid->qty;
							$this->Data_access_model->update_data('hs_products',array('prod_id'=>$pid->id),array('prod_quantity'=>$new_quantity));
						}
					} 
				}
				$this->payment_response('success',$udf2,$firstname,'');
				$this->sending_mail($order_id);
				$this->cart->destroy();
				if(isset($_SESSION['discount_amount'])){
								 
					$coupen_details = $this->Data_access_model->select_data('*','hs_offers',array('coupen_code'=>$_SESSION['copen_code']));
					if($coupen_details->num_rows() > 0){
					 
						$check_limit = $coupen_details->result_array();
						if($check_limit[0]['coupen_uses_limt'] >0 ){
							$coupen_newlimit = $check_limit[0]['coupen_uses_limt'] - 1;
							$this->Data_access_model->update_data('hs_offers',array('coupen_code'=>$_SESSION['copen_code']),array('coupen_uses_limt'=>$coupen_newlimit));
						}
					}
					unset($_SESSION['discount_amount']);
					unset($_SESSION['copen_code']);
					if(isset($_SESSION['discount_prodid'])){
						unset($_SESSION['discount_prodid']);
					}
				} 
			}
		}
	}	
	
	// payumoney failture
	
	public function payufailture(){
		$status = $_POST["status"];
		$firstname= $_POST["firstname"];
		$amount = $_POST["amount"];
		$txnid  = $_POST["txnid"];
		$posted_hash = $_POST["hash"];
		$key = $_POST["key"];
		$productinfo = $_POST["productinfo"];
		$email = $_POST["email"];
		$salt='l1hMFGsCMl';
		$udf1 = $_POST['udf1']; //payment_uid
		$udf2 = $_POST['udf2']; //payment_uniqid
		$udf3 = $_POST['udf3']; //payment_pid
		$udf4 = $_POST['udf4']; //address
		$udf5 = $_POST['udf5']; // city+pincode	
		if (isset($_POST["additionalCharges"])) {
			$additionalCharges=$_POST["additionalCharges"];
			$retHashSeq = $additionalCharges.'|'.$salt.'|'.$status.'|||||||||||'.$email.'|'.$firstname.'|'.$productinfo.'|'.$amount.'|'.$txnid.'|'.$key;        
		} else {      
			$retHashSeq = $salt.'|'.$status.'||||||'.$udf5.'|'.$udf4.'|'.$udf3.'|'.$udf2.'|'.$udf1.'|'.$email.'|'.$firstname.'|'.$productinfo.'|'.$amount.'|'.$txnid.'|'.$key;
		}
		$hash = hash("sha512", $retHashSeq);  
		if ($hash != $posted_hash) {
			 
			$this->payment_response('failed','',$firstname,'Invalid Transaction. Please try again');
		} else {
			$this->payment_response('failed','',$firstname,'You may try making the payment again');
			 
		} 
 
	} 
		
	//payment response for user	
	public function payment_response($type='',$orderid='',$order_uname ='',$msg=''){	
	
		$data['type']		= $type;
		$data['order_id']	= $orderid;
		$data['uname']	    = $order_uname;						 
		$data['message']= $msg;
		$offer_query=$this->Data_access_model->select_data('*','hs_offers',array( 'offer_status' =>1,));
		if($offer_query->num_rows() > 0){
			   
			$offer_data['all_offer'] =$offer_query->result();
			 
		}else{ 
			$offer_data['all_offer'] = "";
			  
		}
		
		$opening_time_query =$this->Data_access_model->select_all('hs_opening_schedule');
		if($opening_time_query->num_rows() > 0){
			$setting_data['opening_time'] =$opening_time_query->result();
			 
		}else{ 
			$setting_data['opening_time'] = "";
		}

		$partner_query=$this->Data_access_model->select_data('*','hs_partners',array( 'partner_status' =>1,));
		if($partner_query->num_rows() > 0){
			   
			$setting_data['all_partners'] =$partner_query->result();
			 
		}else{ 
			$setting_data['all_partners'] = "";
			  
		}
		$offer_data['page_title'] ='Payment Response';
		$this->load->view('theme/common/header',$offer_data);
		$this->load->view('theme/payment_response',$data);
		$this->load->view('theme/common/footer',$setting_data); 
	} 	
		
	//*****************payment by payumoney end****************//		
	
	//*****************send email for order booking start************//	
	public function sending_mail($order_id=''){
		$oid = $order_id;
		$order_details =$this->Data_access_model->select_data('*','hs_user_orders',array('order_id'=>$oid));
		//get order details
		if($order_details->num_rows() > 0){
			$order_info = $order_details->result();
			  
			//get user details
			$user_details = $this->Data_access_model->select_data('*','hs_user',array('user_id'=>$order_info[0]->order_uid ));
			if($user_details->num_rows() > 0 ){
				$uinfo = $user_details->row();
				$uname = $uinfo->user_name; 
				$user_email = $uinfo->user_email;
			}

			$order_date = $order_info[0]->order_date;
			$order_number = $order_info[0]->order_uniqid;
			$order_amount = $this->hs->getwebsettings('currency_symbol').$order_info[0]->order_amount;
			 
			$email_content = $this->hs->getwebsettings('orderbook_template');  
			$email_content = str_replace("[username]",$uname, $email_content);
		    $email_content = str_replace("[order_date]", $order_date,$email_content);
			$email_content = str_replace("[order_number]", $order_number,$email_content);
			$email_content = str_replace("[order_amount]", $order_amount,$email_content);
			$email_content = str_replace("[break]", "<br>", $email_content);
			$data['emcontent'] = $email_content;
		  
			$email_template = $this->load->view('theme/email_template',$data,true);
			$subject = $this->hs->getwebsettings('orderbook_subject');
			// sending mail user
 			$this->hs->send_mail($user_email,$subject,$email_template);
			
			//sending mail admin
			$admin_email = $this->hs->getwebsettings('sender_mailid');
			$admin_emcontent = $this->hs->getwebsettings('adminodr_template'); 
			$admin_emcontent = str_replace("[username]",$uname, $admin_emcontent);
		    $admin_emcontent = str_replace("[order_date]", $order_date,$admin_emcontent);
			$admin_emcontent = str_replace("[order_number]", $order_number,$admin_emcontent);
			$admin_emcontent = str_replace("[break]", "<br>", $admin_emcontent);
			$admin_data['emcontent'] = $admin_emcontent;
			
			$admin_template = $this->load->view('theme/email_template',$admin_data,true);
			$admin_subject = $this->hs->getwebsettings('adminodr_subject');
			// sending mail user
 			$this->hs->send_mail($admin_email,$admin_subject,$admin_template); 
		}	
	} 	
			
	//*****************send email for order booking end************//	

	//***************** currency convetor start******************//
	public function currencyConverter_new($from_Currency,$to_Currency,$amount)
	{
		$from_Currency = urlencode($from_Currency);
		$to_Currency = urlencode($to_Currency);
		//$apikey='692f11c4d93d89416722';
		$apikey = $this->hs->getwebsettings('currency_convert_api');
		$curl = curl_init();
		$url = 	'https://free.currencyconverterapi.com/api/v5/convert?q='.$from_Currency.'_'.$to_Currency.'&compact=y&apiKey='.$apikey.'';
		// OPTIONS:
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
		// EXECUTE:
		$result = curl_exec($curl);
	  
		if(!$result){die("Connection Failure");}
		curl_close($curl);
	    $rate = json_decode($result , true);
	    return $converted_amount = $amount*$rate[$from_Currency.'_'.$to_Currency]['val'];
	}
	
	public function amountUSDTOINR(){
		$protal_currency = $this->hs->getwebsettings('currency_code');
		if($protal_currency == 'USD'){
			$amount = (int) $this->currencyConverter_new('USD','INR',$this->cart->total()) ;
			return (int) round($amount,2);
		}else{
			return $this->cart->total();
		}
	}
	
	public function amountINRTOUSD($subtotal = null){
		$protal_currency = $this->hs->getwebsettings('currency_code');
		if($subtotal == null){
			
			if($protal_currency == 'INR'){
				$amount = $this->currencyConverter_new('INR','USD',$this->cart->total()) ;
				return  round($amount,2);
			}else{
				return $this->cart->total();
			}
		}else{
			if($protal_currency == 'INR'){
				$amount = $this->currencyConverter_new('INR','USD',$subtotal) ;
				return  round($amount,2);
			}else{
				return $subtotal;
			}
		}	
	}
	//***************** currency convetor end******************//


}
	
	
	
