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

class Checkout extends CI_Controller {
     
	public function __construct()
	{
		parent::__construct();
		
		if(!isset($_SESSION['userid']))
		{
			redirect(base_url());
	    }  
		 
		$cart = $this->cart->contents();
		if(empty($cart)){
			redirect(base_url());
		}   
	}
	
	public function verify_coupen(){
		$cart = $this->cart->contents();
		if(isset($_POST['coupen_code']) && !empty($cart))
		{
			$coupen_code = $_POST['coupen_code'];
			$offer_query=$this->Data_access_model->select_data('*','hs_offers',array('coupen_code'=>$coupen_code,'offer_status'=>1));
			if($offer_query->num_rows() > 0)
			{  	$alredy_used =0;
				$check_already_used = $this->Data_access_model->select_data('*','hs_user_orders',array('order_uid'=>$_SESSION['userid'], 'used_coupen_code'=>$coupen_code,));
				if($check_already_used->num_rows() > 0){
					$coupen_info = $check_already_used->result_array();
					if($coupen_info[0]['used_coupen_code'] == $coupen_code){
						$alredy_used++;
					} 
				}
				  
				if($alredy_used == 0){
				$offer_info = $offer_query->result_array();
				if($offer_info[0]['coupen_code'] == $coupen_code)
				{
					if($offer_info[0]['coupen_expire_date'] >= date('Y-m-d'))
					{
						if($offer_info[0]['coupen_uses_limt'] >0)
						{
							if($offer_info[0]['apply_discount_to'] =='Total_amount')
							{
								// 1 for precantage and 2 for flat amount 
								if($offer_info[0]['discount_type'] == 1)
								{
									$cart_total = $this->cart->total();
									$disc_amount = $offer_info[0]['discount_amount'];
									$final_amount = ($disc_amount / 100) * $cart_total;
									$final_amount = round($final_amount);
									$session_data = array('discount_amount'=>$final_amount,'copen_code'=>$coupen_code);
									$this->session->set_userdata($session_data);
									$resp = array('status' => 1 , 'final_amount' =>$final_amount, 'currency_symbol'=>$this->hs->getwebsettings('currency_symbol'));
									
								}else if($offer_info[0]['discount_type'] == 2)
								{
									$final_amount = $offer_info[0]['discount_amount'];
									$session_data = array('discount_amount'=>$final_amount, 'copen_code'=>$coupen_code);
									$this->session->set_userdata($session_data);
									$resp = array('status' => 1 , 'final_amount' =>$final_amount, 'currency_symbol'=>$this->hs->getwebsettings('currency_symbol'));
								} 
								
							}else if($offer_info[0]['apply_discount_to'] == 'single_product')
							{
								$cart = $this->cart->contents();
								if(!empty($cart))
								{   $i=0;
									foreach($cart as $cart_item){
										 
										if($cart_item['id'] == $offer_info[0]['discounted_product'])
										{	$i++;
											$prod_price = $cart_item['price']; 
										
											// 1 for precantage and 2 for flate amount
											if($offer_info[0]['discount_type'] == 1)
											{ 
												$cart_total = $this->cart->total();
												$disc_amount = $offer_info[0]['discount_amount'];
												$final_amount = ($disc_amount / 100) * $prod_price;
												$final_amount = round($final_amount);
												 
												$session_data = array('discount_amount'=>$final_amount,
																	  'discount_prodid'=>$cart_item['id'], 'copen_code'=>$coupen_code);
												$this->session->set_userdata($session_data);
												$resp = array('status' => 1 , 'final_amount'=>$final_amount , 'currency_symbol'=>$this->hs->getwebsettings('currency_symbol'));
											}else if($offer_info[0]['discount_type'] == 2)
											{
												$final_amount = $offer_info[0]['discount_amount'];
												$session_data = array('discount_amount'=>$final_amount,
																	  'discount_prodid'=>$cart_item['id'],'copen_code'=>$coupen_code);
												$this->session->set_userdata($session_data);
												$resp = array('status' => 1 , 'final_amount' =>$final_amount, 'currency_symbol'=>$this->hs->getwebsettings('currency_symbol'));
											} 
												
										}else{
											$resp = array('status' => 0 , 'error' =>'This coupen not applied on your selected product');
										}
										if($i >0){
											break;
										}
									}	
								}else{
									$resp = array('status' => 0 , 'error' =>'Something Went wrong. Please Try Again.');
								}
							}	
						}else{
							$resp = array('status' => 0 , 'error' =>'This Coupen Limit is Expired.');
						}
						 
					}else{
						$resp = array('status' => 0 , 'error' =>'This Coupen Code is Expired.');
					}
					 
				}else{
					$resp = array('status' => 0 , 'error' =>'Copen Code Not Exist');
				}					
			
			}else{
				$resp = array('status' => 0 , 'error' =>'You already used this coupen code.');
			}
			
			}else{
				$resp = array('status' => 0 , 'error' =>'Coupen Code Not Exits'); 
			}
			
		}else{
			$resp = array('status' => 0 , 'error' =>'Coupen Code Not Valid');
		}		
		echo  json_encode($resp);
	}
	
	public function index(){
		$offer_query=$this->Data_access_model->select_data('*','hs_offers',array( 'offer_status' =>1,));
		if($offer_query->num_rows() > 0){
			$data['all_offer'] =$offer_query->result();
		}else{ 
			$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'] = "";
		}
		$user_wallet = $this->Data_access_model->select_data('*','hs_user_wallet',array('wallet_uid' =>$_SESSION['userid']));
	    if($user_wallet->num_rows() > 0){
			$data['current_wallet'] = $user_wallet->result();
		}else{ 
			 $data['current_wallet'] = '';
		}
		$data['cart'] = $this->cart->contents();
		$data['cart_total'] = $this->cart->total();
		$data['page_title'] = 'Checkout';
		$data['page_descri'] ='Checkout';
		$this->load->view('theme/common/header',$data);
		$this->load->view('theme/checkout.php',$data);
		$this->load->view('theme/common/footer',$setting_data);
	}
	
//*****************chck out process start***********************//
	
	public function checkout_payment(){
		
		$cart = $this->cart->contents();
		if(!empty($cart)){
			$this->form_validation->set_rules('ufname','First Name','trim|required');	
			$this->form_validation->set_rules('ulname','Last Name','trim|required');
			$this->form_validation->set_rules('ucheck_email','Email','trim|required');
			$this->form_validation->set_rules('ucontact','Contact','trim|required');
			$this->form_validation->set_rules('uaddress','Address','trim|required');	
			$this->form_validation->set_rules('ucity','City', 'trim|required');
			$this->form_validation->set_rules('upincode','Pin Code','trim|required');
			$this->form_validation->set_rules('payment_group','Payment Option','trim|required');
			if ($this->form_validation->run() == FALSE)
			{
				echo 0; 
				
			}else{

				$order_details = array();
				
				$order_details['uid'] = $this->input->post('check_uid');  
				$payment_mode = $this->input->post('payment_group');
				$cart_amount =  $this->input->post('cart_total');
				$order_details['fname'] 		= $this->input->post('ufname');
				$order_details['lname']         = $this->input->post('ulname');
				$order_details['contact'] 		= $this->input->post('ucontact');
				$order_details['email'] 		= $this->input->post('ucheck_email');
				$order_details['cart_amount']	= $cart_amount;
				$order_details['payment_mode'] 	= $payment_mode; //1 for paypal, 2 for payumoney, 3 for wallet,4 for Cod
				$order_details['delivery_add'] 	= $this->input->post('uaddress');
				$order_details['city'] 			= $this->input->post('ucity');
				$order_details['pin_code'] 		= $this->input->post('upincode');
				$order_details['contact'] 		= $this->input->post('ucontact');
				$order_details['coupen_code']   = ''; 
				$order_details['discount_amount']  = 'None';
				if(isset($_SESSION['discount_amount'])){
					$order_details['coupen_code'] = $_SESSION['copen_code'];
					$order_details['discount_amount'] = $_SESSION['discount_amount'];
					$cart_total =$this->cart->total() - $_SESSION['discount_amount'];
					 
				}else{
					$cart_total = $this->cart->total();
				}
				if($cart_total == $cart_amount){
					if($payment_mode == 1){
				
						$this->paymentby_paypal($order_details);
				
					}else if($payment_mode == 2){
				
						$this->paymentby_payumoney($order_details);
				
					}else if($payment_mode == 3){
				
						$user_wallet = $this->Data_access_model->select_data('wallet_amount','hs_user_wallet',array('wallet_uid' =>$order_details['uid']));
						if($user_wallet->num_rows() > 0){
							$current_wallet = $user_wallet->row();
							if($current_wallet->wallet_amount < $cart_amount){
						  
								echo 3; // 3 for low balance 
						  
							}else{
								$this->payment_by_wallet($order_details); 
							}
						}else{
							echo 4; //4 for low balance  
						}
					}else if($payment_mode == 4){
				
						$this->payment_by_wallet($order_details); 
					}	
				}else{
					echo 0; //something went wroung
				}
			}
		}else{
			echo 5; // 5 for cart empty
		}
	}

	//*****************payment by wallet and COD start******************//	
	public function payment_by_wallet($order_details=''){
		$cart = $this->cart->contents();
		$item =array();
		$response = 0;
		foreach($cart as $cart_item){
				
			$item[] = array(
			'id' => $cart_item['id'],
			'name'=>$cart_item['name'],
			'qty' =>$cart_item['qty'], 
			'subtotal'=>$cart_item['subtotal']
			);
		}
				
		$ouniqid = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 8);
		$order_data =array(	'order_uniqid' =>$ouniqid,					
		'order_uid' =>$order_details['uid'],
		'order_pid' =>json_encode($item),
		'order_date' =>date('d M Y h:i:s'),
		'order_contact' =>$order_details['contact'],
		'order_amount' =>$order_details['cart_amount'], 
		'payment_mode' =>$order_details['payment_mode'],
		'order_email' =>$order_details['email'],
		'delivery_address'=>$order_details['delivery_add'],
		'order_city' =>$order_details['city'],
		'city_pincode' =>$order_details['pin_code'],
		'payment_status' => 0,
		'used_coupen_code'=>$order_details['coupen_code'],
		'discount_amount'=>$order_details['discount_amount'],
		);
		$this->Data_access_model->insert_data('hs_user_orders',$order_data); 
		$order_id = $this->db->insert_id();
		if($this->db->affected_rows() > 0){

			$dataform =  array(
			'userid' => $order_details['uid'],
			'order_id' =>$order_id,
			'order_uniqid' =>$ouniqid,
			'o_username' => $order_details['fname'].' '.$order_details['lname'],
			'final_amount' =>$order_details['cart_amount'],
			);


			if($order_details['payment_mode'] == 3){

				$form_action = base_url().'payresponse/wallet_paymentprocess';

			}else if($order_details['payment_mode'] == 4){

				$form_action = base_url().'payresponse/cod_success';

			}

			$form_data = '';
			$form_data .='<form action="'.$form_action.'" method="post" id="payaple_form">';
			foreach($dataform as $key=>$value ){
				$form_data .= '<input type="hidden" name="'.$key.'" value="'.$value.'"> ';
			}

			$form_data .='</form> ';

			echo $form_data;
		}
	}

	//*****************payment by wallet and COD end******************//	
				
	//*****************payment by paypal start******************//	
	public function paymentby_paypal($order_details=''){
		
		$cart = $this->cart->contents();
		$currency_code = $this->hs->getwebsettings('currency_code');
		if($currency_code == 'INR'){ 
		 	$curre_code = 'USD';		 
		}else{
			$curre_code = $currency_code;
		}
		
		if($currency_code == 'INR'){ 
				$total_amount = $this->currencyConverter_new('INR','USD',$order_details['cart_amount']);
				$final_amount = round($total_amount,2);
			}else{
				$final_amount = $order_details['cart_amount'];
			} 
		$paypal_info =[];
		$item_info =[];
		$order_info =array();
		foreach($cart as $cart_item){
			$order_info[] = array(
			'id' => $cart_item['id'],
			'name'=>$cart_item['name'],
			'qty' =>$cart_item['qty'],
			'subtotal'=>$cart_item['subtotal'],
			);
		} 
		$item_info['item_name'] ="Shoping Cart Total";
		$item_info['amount'] =$final_amount; 
		$item_details = json_encode($item_info);
		$order_data  =array(            
		'order_uniqid' =>substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 8),
		'order_uid' =>$order_details['uid'],
		'order_pid' =>json_encode($order_info),
		'order_date' =>date('d M Y h:i:s'),
		'order_contact' =>$order_details['contact'],
		'order_amount' =>$order_details['cart_amount'], 
		'payment_mode' =>$order_details['payment_mode'],
		'order_email' =>$order_details['email'],
		'delivery_address'=>$order_details['delivery_add'],
		'order_city' =>$order_details['city'],
		'city_pincode' =>$order_details['pin_code'],
		'payment_status' => 0,
		'used_coupen_code'=>$order_details['coupen_code'],
		'discount_amount'=>$order_details['discount_amount'],
		);
		$this->Data_access_model->insert_data('hs_user_orders',$order_data);
		$order_id = $this->db->insert_id();	
						
						 
		$paypal_info = array(
		'cmd'			=>  '_xclick',
		'upload'		=>	'1',
		'business'		=>	$this->hs->getwebsettings('paypal_email'), 
		'currency_code' =>	$curre_code,
		'return'		=>	base_url('payresponse/paypalsuccess'),
		'cancel_return'	=>	base_url('payresponse/paypalfailture'),
		'notify_url'	=>	base_url('payresponse/paypalnotify_url'),
		'custom'        =>  $order_id,
		); 
					
		$dataform = array_merge($paypal_info,$item_info);
		$data['cartitem_info'] = $order_info;
		$data['form_action'] = 'https://api.paypal.com'; 
					
		//test url :- https://www.sandbox.paypal.com/cgi-bin/webscr
		// live url :- https://api.paypal.com
		 
		$form_data = '';
		$form_data .='<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" id="payaple_form">';
		foreach($dataform as $key=>$value ){
			$form_data .= '<input type="hidden" name="'.$key.'" value="'.$value.'"> ';
		}

		$form_data .='</form>';
		echo $form_data;
	}
	
	//*****************payment by paypal end******************//


	//*****************payment by payumoney start***************//			
	 public function paymentby_payumoney($order_details){
		
		$MERCHANT_KEY = $this->hs->getwebsettings('payumoney_key');  
		$SALT = $this->hs->getwebsettings('payumoney_salt');   
		$txnid = substr(hash('sha256', mt_rand() . microtime()), 0, 20);
		$cuurency_code = $this->hs->getwebsettings('currency_code');
		
		if($cuurency_code != 'INR'){
			$converted_amount = (int) $this->currencyConverter_new($cuurency_code,'INR',$order_details['cart_amount']);
			$totalcost = (int) round($converted_amount,2);  
		}else{
			$totalcost = $order_details['cart_amount'];
		}
		
		$hash ='';
		$firstname = $order_details['fname'].' '.$order_details['lname'];
		$email = $order_details['email'];
		$contact = $order_details['contact'];
		$userid = $order_details['uid'];
		$dilevery_address = $order_details['delivery_add'];
		$city = $order_details['city'];
		$payment_mode = $order_details['payment_mode'];
		$udf1	=   $userid; //payment_uid
		$udf2	=	substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 8); //payment_uniqid
		$udf3	=	'1';//payment_pid
		$udf4  = $order_details['delivery_add']; //address
		$udf5  = $order_details['city'].'|'.$order_details['pin_code'].'|'.$order_details['coupen_code'].'|'.$order_details['discount_amount']; // city+pincode+coupencode+discoun_amount
		$carts = $this->cart->contents();
		foreach($carts as $cart_item){
				
			$product_details[] = array(
			'id' => $cart_item['id'],
			'name'=>$cart_item['name'],
			'qty' =>$cart_item['qty'],
			'subtotal'=>$cart_item['subtotal']
			);
		}
		$productinfo =json_encode($product_details);
		//$hashSequence = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10";
		
		$hash_string = $MERCHANT_KEY."|".$txnid."|".$totalcost."|".$productinfo."|".$firstname."|".$email."|".$udf1."|".$udf2."|".$udf3."|".$udf4."|".$udf5."||||||".$SALT;
		
		$hash = strtolower(hash('sha512', $hash_string));
		
		$posted  = array(
						'key' 				=>  $MERCHANT_KEY,
						'hash'				=>  $hash,
						'txnid' 			=>  $txnid, 
						'amount'			=>  $totalcost,
						'productinfo' 		=>  $productinfo,
						'firstname' 		=>  $firstname,
						'email' 			=>  $email,
						'phone' 			=>  $contact,
						'surl' 				=>  base_url('payresponse/payusuccess'),
						'furl' 				=>  base_url('payresponse/payufailture'),
						'service_provider' 	=>  'payu_paisa',
						'udf1'				=>  $udf1, //payment_uid
						'udf2'				=>	$udf2, //payment_uniqid
						'udf3'				=>	$udf3, //payment_pid
						'udf4' 				=>  $udf4, //address
						'udf5'				=>  $udf5, //city
						);	 
		 		 
		$form_action ='https://secure.payu.in/_payment';	
		
		//live mode url 'https://secure.payu.in/_payment'
		//'https://sandboxsecure.payu.in/_payment'	 for test mode url
		
		$dataform = $posted;	
		$form_data = '';
		$form_data .='<form action="'.$form_action.'" method="post" id="payaple_form">';
		foreach($dataform as $key=>$value ){
			if($key == 'productinfo'){
				
				$form_data .= '<textarea name="'.$key.'" style="display:none">'.$value.'</textarea>'; 
				
			}else{
				$form_data .= '<input type="hidden" name="'.$key.'" value="'.$value.'">';
			}
		}
		 
		$form_data .='</form>';
		echo $form_data;
	} 
	//*****************payment by payumoney 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******************//
}