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

/**
 * 
 * User related functions
 * @author Teamtweaks
 *
 */

class Cart extends MY_Controller { 
	function __construct(){
        parent::__construct();
		$this->load->helper(array('cookie','date','form','email'));
		$this->load->library(array('encrypt','form_validation'));		
		$this->load->model('cart_model');
		$this->load->library('user_agent');
		
		$this->data['loginCheck'] = $this->checkLogin('U');
		//$this->data['MiniCartViewSet'] = $this->cart_model->mini_cart_view($this->data['common_user_id']); 
		
		define("PaypalIDDetails",$this->config->item('payment_0'));
		define("API_LOGINIDDetails",$this->config->item('payment_2'));
    }
    
  
	/**
	 * 
	 * Loading Cart Page
	 */
	
	public function index(){
	 	
		//if ($this->data['loginCheck'] != ''){
			$uid=$this->session->userdata['shopsy_session_user_id'];
			$this->data['user_id'] = $uid;
			$this->data['meta_title'] = $this->data['heading'] = 'Cart'; 
			$this->data['cartViewResults'] = $this->cart_model->mani_cart_view($this->data['common_user_id']);	
			$this->data['relatedPersons'] =$relatedPersons= $this->cart_model->relatedPurchases($this->data['common_user_id']);
			foreach($relatedPersons as $neighbours){
				$relatedPurchasesPrd[$neighbours->neighbourId]=$this->product_model->get_all_details(USER_PAYMENT,array('user_id'=>$neighbours->neighbourId))->result_array();
			}
			foreach($relatedPurchasesPrd as $neighboursprd){
				foreach($neighboursprd as $products){
					$condition = " where p.status='Publish' and p.id=".$products['product_id']." or p.status='Publish' and p.id=".$products['product_id']." and a.pricing IS NOT NULL group by p.id order by p.created desc";
				$relatedPurchases[]=$this->product_model->view_product_details($condition)->row();
				}
			}
			/*Remove the duplication products*/
			$newPrdArr[]=$relatedPurchases[0]->id;
			$newrelatedPurchases[$relatedPurchases[0]->id]=$relatedPurchases[0];
			$j=0;$l=1;
			for($k=1;$k<count($relatedPurchases);$k++){
				if(!in_array($relatedPurchases[$k]->id,$newPrdArr)){
					$j++;$l++;
					$newPrdArr[]=$relatedPurchases[$k]->id;
					$newrelatedPurchases[$relatedPurchases[$k]->id]=$relatedPurchases[$k];
				}
			}
			 
			foreach($relatedPersons as $neighbours){
				unset($newrelatedPurchases[$neighbours->productId]);
			}
			if(!empty($relatedPersons))
			$this->data['relatedPurchases'] = $newrelatedPurchases;
		 	$this->load->view('site/cart/cart.php',$this->data);
		/*}else{
			redirect('login');
		}*/	
	} 
	
	
	/****************** Insert the cart to user********************/
	
	public function insertEditCart(){
	
		$excludeArr = array('addtocart');
		$dataArrVal = array();
		foreach($this->input->post() as $key => $val){
			if(!(in_array($key,$excludeArr))){
				$dataArrVal[$key] = trim(addslashes($val));
			}
		}

		$datestring = "%Y-%m-%d 23:59:59";
		$code = $this->get_rand_str('10');
		$exp_days = $this->config->item('cart_expiry_days');

		$dataArry_data = array('expiry_date' => mdate($datestring,strtotime($exp_days.' days')), 'code' => $code,'user_id' => $this->data['common_user_id']);
		$dataArr = array_merge($dataArrVal,$dataArry_data);
		
		$condition ='';
		
		$this->cart_model->commonInsertUpdate(GIFTCARDS_TEMP,'insert',$excludeArr,$dataArr,$condition);
		
		if ($this->checkLogin('U') != ''){
			$this->setErrorMessage('success','Giftcard Added You Cart successfully');
			redirect('gift-cards');
	 	}else{
			redirect('login');
		}
	}
	
	/*************************** product add to Cart function  *************************************/
	
	public function cartadd(){
		
		
		
		$excludeArr = array('addtocart','attr_color','mqty','attribute_values');
		$dataArrVal = array();
		$mqty = $this->input->post('mqty');
		foreach($this->input->post() as $key => $val){
			if(!(in_array($key,$excludeArr))){
				$dataArrVal[$key] = trim(addslashes($val));
			}
		}

		$datestring = date('Y-m-d H:i:s',now());
		$indTotal = ( $this->input->post('price') + $this->input->post('product_shipping_cost') + ($this->input->post('price') * 0.01 * $this->input->post('product_tax_cost')) ) * $this->input->post('quantity');
		if($this->input->post('attribute_values') != ''){
			$attVals = @implode('|-|',$this->input->post('attribute_values'));
		}else{
			$attVals = '';
		}
		$dataArry_data = array('created' => $datestring, 'user_id' => $this->data['common_user_id'], 'indtotal' => $indTotal, 'total' => $indTotal, 'attribute_values' => $attVals);
		$dataArr = array_merge($dataArrVal,$dataArry_data);
		
		$condition ='';
		
		
		$this->data['productVal'] = $this->cart_model->get_all_details(SHOPPING_CART,array( 'user_id' => $this->data['common_user_id'],'product_id' => $this->input->post('product_id'),'attribute_values' => $attVals));	
		
		//echo '<pre>'; print_r($this->data['productVal']); die;
		
		if($this->data['productVal']->num_rows > 0){
			$newQty = $this->data['productVal']->row()->quantity + $this->input->post('quantity');
			if ($newQty <= $mqty){
				$indTotal = ( $this->input->post('price') + $this->input->post('product_shipping_cost') + ($this->input->post('price') * 0.01 * $this->input->post('product_tax_cost')) ) * $newQty ; 
				$dataArr = array('quantity' => $newQty, 'indtotal' => $indTotal, 'total' => $indTotal);
				$condition =array('id' => $this->data['productVal']->row()->id);
				$this->cart_model->commonInsertUpdate(SHOPPING_CART,'update',$excludeArr,$dataArr,$condition); 
			}else{
				echo 'Error|'.$this->data['productVal']->row()->quantity; die;
			}
		}else{
			$this->cart_model->commonInsertUpdate(SHOPPING_CART,'insert',$excludeArr,$dataArr,$condition);
		}
		
		
		echo 'Success|'.$this->cart_model->mini_cart_view($this->data['common_user_id']); 
		
			
	}
	
	
	/*************************** User product add to Cart function  *************************************/
	public function usercartadd(){
	//echo "<pre>"; print_r($_POST); die;
	
	//[mqty] => 13
//    [quantity] => 1
//    [product_id] => 155
//    [sell_id] => 61
//    [price] => 12.00
//    [attribute_values] => color:red ,size:L
		
		//error_reporting(-1);
		$digital_files = $this->input->post('digital_files');
		$excludeArr = array('mqty');
		$dataArrVal = array();
		$mqty = $this->input->post('mqty');
		foreach($this->input->post() as $key => $val){
			if(!(in_array($key,$excludeArr))){
				$dataArrVal[$key] = trim(addslashes($val));
			}
		}

		$datestring = date('Y-m-d H:i:s',now());
		$indTotal = ( $this->input->post('price') * $this->input->post('quantity') );
		
		$dataArry_data = array('created' => $datestring, 'user_id' => $this->data['common_user_id'], 'indtotal' => $indTotal, 'total' => $indTotal);
		$dataArr = array_merge($dataArrVal,$dataArry_data);
		
		$condition ='';
		
		
		
		$this->data['productVal'] = $this->cart_model->get_all_details(USER_SHOPPING_CART,array( 'user_id' => $this->data['common_user_id'],'product_id' => $this->input->post('product_id'),'attribute_values' => $this->input->post('attribute_values')));	
		
		if($this->data['productVal']->num_rows > 0){
			$newQty = $this->data['productVal']->row()->quantity + $this->input->post('quantity');
			
			if ($newQty <= $mqty){
				$indTotal = $this->input->post('price') * $newQty ; 
				$dataArr = array('quantity' => $newQty, 'indtotal' => $indTotal, 'total' => $indTotal);
				$condition =array('id' => $this->data['productVal']->row()->id);
				$this->cart_model->update_details(USER_SHOPPING_CART,$dataArr,$condition); 
			}else{
				echo 'Error|'.$this->data['productVal']->row()->quantity; die;
			} 	
			
		}else{
			$this->cart_model->simple_insert(USER_SHOPPING_CART,$dataArr);
		}
		
		
		//if ( $this->checkLogin('U')!= ''){
			echo 'Success|'.$this->cart_model->mini_cart_view($this->data['common_user_id']); 
		//}else{
		//	echo 'login|lgoin';
		//}	
	}
	
	/*************************** Cart Ajax Update function  *************************************/
	
	public function ajaxUpdate(){
		$excludeArr = array('id','qty','updval');
	
		$productVal = $this->cart_model->get_all_details(SHOPPING_CART,array( 'user_id' => $this->data['common_user_id'],'id' => $this->input->post('updval')));	
		
		$newQty = $this->input->post('qty');
		$indTotal = ( $productVal->row()->price + $productVal->row()->product_shipping_cost + ($productVal->row()->price * 0.01 * $productVal->row()->product_tax_cost) ) * $newQty ;
			
		$dataArr = array('quantity' => $newQty, 'indtotal' => $indTotal, 'total' => $indTotal);
		$condition =array('id' => $productVal->row()->id);
		$this->cart_model->commonInsertUpdate(SHOPPING_CART,'update',$excludeArr,$dataArr,$condition);
		
		echo number_format($indTotal,2,'.','').'|'.$this->data['CartVal'] = $this->cart_model->mani_cart_total($this->data['common_user_id']); 
		
		return;
	}
	
	/*************************** USer Cart Ajax Update function  *************************************/
	public function ajaxUserUpdate(){
		$excludeArr = array('id','qty','updval','selid');
		
		$productVal = $this->cart_model->get_all_details(USER_SHOPPING_CART,array( 'user_id' => $this->data['common_user_id'],'id' => $this->input->post('updval')));	
		
		$newQty = $this->input->post('qty');
		$indTotal = $productVal->row()->price * $newQty ;
		$shipcost = $productVal->row()->product_shipping_cost * $newQty ;
			
		$dataArr = array('quantity' => $newQty, 'indtotal' => $indTotal, 'shipping_cost' => $shipcost, 'total' => $indTotal);
		$condition =array('id' => $productVal->row()->id);
		$this->cart_model->update_details(USER_SHOPPING_CART,$dataArr,$condition);
		
		echo number_format($indTotal,2,'.','').'|'.$this->data['CartVal'] = $this->cart_model->mani_user_cart_total($this->data['common_user_id'],$this->input->post('selid')); 
		
		return;
	}
	
	/*************************** Cart Ajax Delete function  *************************************/
	public function ajaxDelete(){
	
		$delt_id = $this->input->post('curval'); 
		$CondID = $this->input->post('cart'); 
		if($CondID =='gift'){		
			$this->db->delete(GIFTCARDS_TEMP, array('id' => $delt_id)); 
			echo $this->data['GiftVal'] = $this->cart_model->mani_gift_total($this->data['common_user_id']);
		}elseif($CondID =='subscribe'){		
			$this->db->delete(FANCYYBOX_TEMP, array('id' => $delt_id)); 
			echo $this->data['SubscribeVal'] = $this->cart_model->mani_subcribe_total($this->data['common_user_id']);			
		}elseif($CondID == 'cart'){
			$this->db->delete(SHOPPING_CART, array('id' => $delt_id)); 
			echo $this->data['CartVal'] = $this->cart_model->mani_cart_total($this->data['common_user_id']);
		}elseif($CondID == 'usercart'){
			$seller_id = $this->input->post('sellId');
			$this->db->delete(USER_SHOPPING_CART, array('id' => $delt_id)); 
			
			$shopId = 'shopId-'.$seller_id;
			$this->session->unset_userdata($shopId, '');
			$shopCounty = 'ShopCountry-'.$seller_id;
			$this->session->unset_userdata($shopCounty, '');
			$this->cart_model->Check_Code_Val_Remove($this->data['common_user_id'],$seller_id);
		
			$this->setErrorMessage('success','Product Removed From Your Cart successfully');	
			
			echo $this->data['UserCartVal'] = $this->cart_model->mani_user_cart_total($this->data['common_user_id'],$seller_id);
		}

		return;
	}
	
	/*************************** Coupon code Check function  *************************************/
	
	public function checkCode(){
	
		$Code = $this->input->post('code');
		$amount = $this->input->post('amount'); 
		$shipamount = $this->input->post('shipamount'); 
		$sellerId = $this->input->post('seller_id'); 
		
		echo $this->cart_model->Check_Code_Val($Code,$amount,$shipamount,$sellerId,$this->data['common_user_id']);
		$this->setErrorMessage('success','Coupon Code Applied Successfully');

		return;
	
	}
	
	/*************************** Contact Shop Owner Check product popup function  *************************************/
	
	public function contactshopowner(){
	
		$productid = $this->input->post('product_id'); 
		$sellerId = $this->input->post('seller_id'); 
		
		$productVal = $this->cart_model->get_all_details(PRODUCT,array( 'id' => $productid));	
		$sellerVal = $this->cart_model->get_all_details(USERS,array( 'id' => $sellerId));
		$sellerBusinessVal = $this->cart_model->get_all_details(SELLER,array( 'seller_id' => $sellerId));	
		$UserVal = $this->cart_model->get_all_details(USERS,array( 'id' => $this->data['common_user_id']));	
		
		
		if($UserVal->row()->thumbnail !=''){
			$srcVal = 'images/users/'.$UserVal->row()->thumbnail;
		}else{
			$srcVal = 'images/default_avat.png';
		}
		
		
		$popupVal = '<div class="conversation"><div class="conversation_container">
			    <h2 class="conversation_headline">New conversation with '.ucfirst($sellerVal->row()->full_name).' from '.ucfirst($sellerBusinessVal->row()->seller_businessname).'</h2>
    			<div class="conversation_thumb"><img width="75" height="75" src="'.$srcVal.'"></div>
				<div class="conversation_right">
				<form name="contactshopowener" id="contactshopowener" method="post" action="site/cart/cartcontactshopowner">
					<input class="conversation-subject" type="text" name="subject" placeholder="Subject" value="'.$productVal->row()->product_name.'">
	    			<textarea class="conversation-textarea" rows="11" name="message_text" placeholder="Message text">Listing: '.base_url().'products/'.$productVal->row()->seourl.'</textarea>
					<input type="hidden" name="productid" id="productid" value="'.$productVal->row()->id.'" >
					<input type="hidden" name="productname" id="productname" value="'.$productVal->row()->product_name.'" >
					<input type="hidden" name="username" id="username" value="'.$UserVal->row()->full_name.'" >
					<input type="hidden" name="useremail" id="useremail" value="'.$UserVal->row()->email.'" >
					<input type="hidden" name="userid" id="userid" value="'.$UserVal->row()->id.'" >
					<input type="hidden" name="selleremail" id="selleremail" value="'.$sellerVal->row()->email.'" >
					<input type="hidden" name="sellerid" id="sellerid" value="'.$sellerVal->row()->id.'" >
					<input type="hidden" name="subject_name" id="subject_name" value="New conversation with '.ucfirst($sellerVal->row()->full_name).' from '.ucfirst($sellerBusinessVal->row()->seller_businessname).'">
					
    				<input class="subscribe_btn" type="submit" value="send" style="height: auto; padding: 7px 10px; margin: 10px 0 7px 20px; font-weight: bold;">
		</form>			
  				</div> 
    			</div>
			    </div>';
		echo $popupVal;		
		
		return;
	
	}
	
	public function cartcontactshopowner(){
		
		$dataArr = array('username'=>$this->input->post('username'),'useremail'=>$this->input->post('useremail'),'user_id'=>$this->input->post('userid'),'selleremail'=>$this->input->post('selleremail'),'sellerid'=>$this->input->post('sellerid'),'product_id'=>$this->input->post('productid'),'product_name'=>$this->input->post('productname'),'description'=>$this->input->post('message_text'));
		$this->cart_model->simple_insert(CONTACTSELLER,$dataArr);
		$dataArry = array('sender_email'=>$this->input->post('useremail'),'sender_id'=>$this->input->post('userid'),'receiver_email'=>$this->input->post('selleremail'),'receiver_id'=>$this->input->post('sellerid'),'subject'=>$this->input->post('subject'),'message'=>$this->input->post('message_text'),'dataAdded'=>date('Y-m-d H:i:s'));
		$this->user_model->simple_insert(CONTACTPEOPLE,$dataArry);
		
		$productName = $this->input->post('productname');
		$userrname = $this->input->post('username');
		$description = $this->input->post('message_text');
		$email = $this->input->post('selleremail');
		
		$newsid='15';
		$template_values=$this->cart_model->get_newsletter_template_details($newsid);
		
		$subject = 'From: '.$this->config->item('email_title').' - '.$template_values['news_subject'];
		$adminnewstemplateArr=array('email_title'=> $this->config->item('email_title'),'logo'=> $this->data['logo']);
		extract($adminnewstemplateArr);
		//$ddd =htmlentities($template_values['news_descrip'],null,'UTF-8');
		$header .="Content-Type: text/plain; charset=ISO-8859-1\r\n";
		
		$message .= '<!DOCTYPE HTML>
			<html>
			<head>
			<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
			<meta name="viewport" content="width=device-width"/><body>';
		include('./newsletter/registeration'.$newsid.'.php');	
		
		$message .= '</body>
			</html>';
		
		if($template_values['sender_name']=='' && $template_values['sender_email']==''){
			$sender_email=$this->data['siteContactMail'];
			$sender_name=$this->data['siteTitle'];
		}else{
			$sender_name=$template_values['sender_name'];
			$sender_email=$template_values['sender_email'];
		}

		$email_values = array('mail_type'=>'html',
							'from_mail_id'=>$sender_email,
							'mail_name'=>$sender_name,
							'to_mail_id'=>$email,
							'subject_message'=>$template_values['news_subject'],
							'body_messages'=>$message
							);
		//echo '<pre>'; print_r($email_values); die;
		$email_send_to_common = $this->cart_model->common_email_send($email_values);
		
		
		
		$this->setErrorMessage('success','Contact Shop Owner Mail Sent Successfully.');
		redirect('cart');
			
	}
	
	/*************************** Coupon Code Remove function  *************************************/
	
	public function checkCodeRemove(){
		$sellerId = $this->input->post('seller_id');
		$this->cart_model->Check_Code_Val_Remove($this->data['common_user_id'],$sellerId);
		echo $this->data['CartVal'] = $this->cart_model->mani_cart_coupon_sucess($this->data['common_user_id']); 
		$this->setErrorMessage('success','Coupon Code Removed Successfully');
		return;
	
	}
	
	/*************************** Sellect Cart Remove function  *************************************/
	
	public function SellerCartRemove(){
		$sellerId = $this->input->post('seller_id');
		
		$this->db->delete(USER_SHOPPING_CART, array('sell_id' => $sellerId)); 
		$this->setErrorMessage('success','Shop Product Removed Your Cart Successfully');
		return;	
	}
	
	/*************************** Sellect Cart Remove function  *************************************/
	
	public function giftcardCartRemove(){
		$sellerId = $this->input->post('user_id');
		
		$this->db->delete(GIFTCARDS_TEMP, array('user_id' => $sellerId)); 
		$this->setErrorMessage('success','GiftCard Removed Your Cart Successfully');
		return;
	
	}
	
	/*************************** Coupon Code Success function  *************************************/
	
	public function checkCodeSuccess(){
		echo $this->data['CartVal'] = $this->cart_model->mani_cart_coupon_sucess($this->data['common_user_id']); 
	}
	
	/*************************** Ajax Change address for cart page function  *************************************/	
	public function ajaxChangeAddress(){

		if($this->input->post('add_id') != ''){
			$ChangeAdds =  $this->cart_model->get_all_details(SHIPPING_ADDRESS,array( 'user_id' => $this->data['common_user_id'],'id' => $this->input->post('add_id')));
			
			$ShipCostVal = $this->cart_model->get_all_details(COUNTRY_LIST,array( 'country_code' => $ChangeAdds->row()->country));	
			$MainShipCost = number_format($ShipCostVal->row()->shipping_cost,2,'.','');
			$MainTaxCost = number_format(($this->input->post('amt') * 0.01 * $ShipCostVal->row()->shipping_tax),2,'.','');
			$TotalAmts = number_format(( ($this->input->post('amt') + $MainShipCost + $MainTaxCost) - $this->input->post('disamt')),2,'.','');
			
			$condition = array('user_id' => $this->data['common_user_id']);
			$dataArr2 = array('shipping_cost' => $MainShipCost, 'tax' => $ShipCostVal->row()->shipping_tax);
			$this->cart_model->update_details(SHOPPING_CART,$dataArr2,$condition); 
			
			echo $Chg_Adds = $MainShipCost.'|'.$MainTaxCost.'|'.$ShipCostVal->row()->shipping_tax.'|'.$TotalAmts.'|'.$ChangeAdds -> row() -> full_name.'<br>'.$ChangeAdds -> row() -> address1.'<br>'.$ChangeAdds -> row() -> city.' '.$ChangeAdds -> row() -> state.' '.$ChangeAdds -> row() -> postal_code.'<br>'.$ChangeAdds -> row() -> country.'<br>'.$ChangeAdds -> row() -> phone;		
			
		}else{
			echo '0';
		}
	}

	/*************************** User Ajax Change address for cart page function  *************************************/		
	public function ajaxUserChangeAddress(){
		
		//echo '<pre>'; print_r($_POST); die;

		if($this->input->post('add_id') != ''){
			$shopId = 'shopId-'.$this->input->post('seller_id');
			$this->session->unset_userdata($shopId, '');
			$this->session->set_userdata($shopId,$this->input->post('add_id'));
			
			$ChangeAdds =  $this->cart_model->get_all_details(SHIPPING_ADDRESS,array( 'user_id' => $this->data['common_user_id'],'id' => $this->input->post('add_id')));
			$shopCounty = 'ShopCountry-'.$this->input->post('seller_id');
			$this->session->unset_userdata($shopCounty, '');
			$this->session->set_userdata($shopCounty,$ChangeAdds->row()->country);
			
		$ProductVal = $this->cart_model->get_all_details(USER_SHOPPING_CART,array( 'sell_id' => $this->input->post('seller_id'), 'user_id' => $this->data['common_user_id']),array(array('field'=>'id','type'=>'Asc')));	
		
		$s=0;
		
		foreach($ProductVal->result_array() as $prodtVal){	$shipCost = $shipCost1 = 0;
			$SubShipVal = $this->cart_model->get_all_details(SUB_SHIPPING,array( 'product_id' => $prodtVal['product_id'],'ship_name' => $ChangeAdds->row()->country), array(array('field'=>'ship_id','type'=>'Desc')));
			
			if($SubShipVal->num_rows() > 0){
				if($s==0){
					$shipCost = $SubShipVal->row()->ship_cost;
				}else{
					$shipCost = $SubShipVal->row()->ship_other_cost;
				}

				$newshipCost = number_format( ($prodtVal['quantity'] * $shipCost),2,'.','');
				$conditionShip = array('id' => $prodtVal['id']);
				$dataArrShip = array('product_shipping_cost' => $shipCost,'shipping_cost' => $newshipCost,'shipping'=>'Yes');
				//echo '<pre>Ord'; print_r($dataArrShip);
				$this->cart_model->update_details(USER_SHOPPING_CART,$dataArrShip,$conditionShip); 
				//echo $this->db->last_query();
				$s++;	
			}else{
				$SubShipValNew = $this->cart_model->get_all_details(SUB_SHIPPING,array( 'product_id' => $prodtVal['product_id'],'ship_name' => 'Everywhere Else'), array(array('field'=>'ship_id','type'=>'Desc')));
				//echo '<pre>'; print_r($SubShipValNew->result_array()); 
				if($SubShipValNew->num_rows() > 0){
					if($s==0){
						$shipCost1 = $SubShipValNew->row()->ship_cost;
					}else{
						$shipCost1 = $SubShipValNew->row()->ship_other_cost;
					}
					$newshipCost1 = number_format( ($prodtVal['quantity'] * $shipCost1),2,'.','');
					$conditionShip1 = array('id' => $prodtVal['id']);
					$dataArrShip1 = array('product_shipping_cost' => $shipCost1,'shipping_cost' => $newshipCost1,'shipping'=>'Yes');	
					//echo '<pre>Every'; print_r($dataArrShip1);
					$this->cart_model->update_details(USER_SHOPPING_CART,$dataArrShip1,$conditionShip1); 
					//echo $this->db->last_query();
					$s++;	
				}
				
			}
					
		}
			//echo '<pre>'; print_r($ProductVal->result_array()); die;
				//foreach($ProductVal->result_array() as $prodtVal){
		/*$SubShipVal = $this->cart_model->get_all_details(SUB_SHIPPING,array( 'product_id' => $ProductVal->row()->product_id), array(array('field'=>'ship_id','type'=>'Desc')));
			//echo '<pre>'; print_r($SubShipVal->result_array()); die;
				
				$shipCost = $shipOtherCost = 0;
				if($SubShipVal->num_rows() > 0){
					if($SubShipVal->row()->ship_id == '232'){
						$shipCost = $SubShipVal->row()->ship_cost;
						$shipOtherCost = $SubShipVal->row()->ship_other_cost;
					}else{
						$shipCost = $shipOtherCost = 'No-Shipping';
					}
					foreach($SubShipVal->result_array() as $shipSubVal){
						if($ChangeAdds->row()->country == $shipSubVal['ship_name']){
							$shipCost = $SubShipVal->row()->ship_cost;
							$shipOtherCost = $SubShipVal->row()->ship_other_cost;
						}
					}
				}
			//}
			
			if($shipCost > 0){
				//echo '<pre>'; print_r($ProductVal->result_array());
				foreach($ProductVal->result_array() as $prodtVal){
					if($ProductVal->row()->id == $prodtVal['id']){
						$newshipCost = number_format($prodtVal['quantity'] * $shipCost,2,'.','');
						$conditionShip = array('id' => $prodtVal['id']);
						$dataArrShip = array('product_shipping_cost' => $shipCost,'shipping_cost' => $newshipCost,'shipping'=>'Yes');
						$this->cart_model->update_details(USER_SHOPPING_CART,$dataArrShip,$conditionShip); 
						//echo $this->db->last_query();
					}else{
						$newshipCost = number_format($prodtVal['quantity'] * $shipOtherCost,2,'.','');
						$conditionShip = array('id' => $prodtVal['id']);
						$dataArrShip = array('product_shipping_cost' => $shipOtherCost,'shipping_cost' => $newshipCost,'shipping'=>'Yes' );
						$this->cart_model->update_details(USER_SHOPPING_CART,$dataArrShip,$conditionShip); 
						//echo $this->db->last_query();					
					}
				}
			}*/
			
			/*$ShipCostVal = $this->cart_model->get_all_details(COUNTRY_LIST,array( 'country_code' => $ChangeAdds->row()->country));	
			$MainShipCost = number_format($ShipCostVal->row()->shipping_cost,2,'.','');
			$MainTaxCost = number_format(($this->input->post('amt') * 0.01 * $ShipCostVal->row()->shipping_tax),2,'.','');
			$TotalAmts = number_format(($this->input->post('amt') + $MainShipCost + $MainTaxCost),2,'.','');
			
			$condition = array('user_id' => $this->data['common_user_id']);
			$dataArr2 = array('shipping_cost' => $MainShipCost, 'tax' => $ShipCostVal->row()->shipping_tax);
			$this->cart_model->update_details(USER_SHOPPING_CART,$dataArr2,$condition); */
			
			//echo $Chg_Adds = $MainShipCost.'|'.$MainTaxCost.'|'.$ShipCostVal->row()->shipping_tax.'|'.$TotalAmts.'|'.$ChangeAdds -> row() -> full_name.'<br>'.$ChangeAdds -> row() -> address1.'<br>'.$ChangeAdds -> row() -> city.' '.$ChangeAdds -> row() -> state.' '.$ChangeAdds -> row() -> postal_code.'<br>'.$ChangeAdds -> row() -> country.'<br>'.$ChangeAdds -> row() -> phone;		
			echo '1';
		}else{
			echo '0';
		}
	}
	
	
	/*************************** Ajax Subscribe address for cart page function  *************************************/	
	public function ajaxSubscribeAddress(){

		if($this->input->post('add_id') != ''){
			$ChangeAdds =  $this->cart_model->get_all_details(SHIPPING_ADDRESS,array( 'user_id' => $this->data['common_user_id'],'id' => $this->input->post('add_id')));
			
			$ShipCostVal = $this->cart_model->get_all_details(COUNTRY_LIST,array( 'country_code' => $ChangeAdds->row()->country));	
			$MainShipCost = number_format($ShipCostVal->row()->shipping_cost,2,'.','');
			$MainTaxCost = number_format(($this->input->post('amt') * 0.01 * $ShipCostVal->row()->shipping_tax),2,'.','');
			$TotalAmts = number_format(($this->input->post('amt') + $MainShipCost + $MainTaxCost),2,'.','');
			
			
			echo $Chg_Adds = $MainShipCost.'|'.$MainTaxCost.'|'.$ShipCostVal->row()->shipping_tax.'|'.$TotalAmts.'|'.$ChangeAdds -> row() -> full_name.'<br>'.$ChangeAdds -> row() -> address1.'<br>'.$ChangeAdds -> row() -> city.' '.$ChangeAdds -> row() -> state.' '.$ChangeAdds -> row() -> postal_code.'<br>'.$ChangeAdds -> row() -> country.'<br>'.$ChangeAdds -> row() -> phone;		
			
			
		}else{
			echo '0';
		}
	}
	
	/*************************** Ajax Delete address for cart page function  *************************************/	
	public function ajaxDeleteAddress(){
    	if ($this->checkLogin('U')==''){
    		redirect('login');
    	}else {
    		$delID = $this->input->post('del_ID'); 
    		$checkAddrCount = $this->cart_model->get_all_details(SHIPPING_ADDRESS,array('id' => $delID ,'primary'=>'Yes' ));
			
    		if ($checkAddrCount->num_rows == 0){
    			$this->cart_model->commonDelete(SHIPPING_ADDRESS,array('id' => $delID));
				echo '0';
    		}else{
				echo '1';
			}
    	}
    }
		public function ajaxDeleteAddress_account(){
		$delID = $this->uri->segment(4);

		
    	if ($this->checkLogin('U')==''){
    		redirect('login');
    	}else {
    		$checkAddrCount = $this->cart_model->get_all_details(SHIPPING_ADDRESS,array('id' => $delID ,'primary'=>'Yes' ));
			
    		if ($checkAddrCount->num_rows == 0){
    			$this->cart_model->commonDelete(SHIPPING_ADDRESS,array('id' => $delID));
				//$str = $this->db->last_query();
				//echo '0';
				$this->setErrorMessage('success','Shipping address deleted successfully');	
				  redirect('settings/shipping');
    		}else{
						//echo '1';
					$this->setErrorMessage('error','Default address don`t be deleted.');	
				  redirect('settings/shipping');
				
			}
    	}
    }
	
	/*************************** Shipping address Insert for cart page function  *************************************/	
	public function insert_shipping_address(){
    	if ($this->checkLogin('U')==''){
    		redirect('login');
    	}else {
    		$is_default = $this->input->post('set_default');
    		if ($is_default == ''){
    			$primary = 'No';
    		}else{
    			$primary = 'Yes';
    		}
    		$checkAddrCount = $this->cart_model->get_all_details(SHIPPING_ADDRESS,array('user_id'=>$this->checkLogin('U')));
    		if ($checkAddrCount->num_rows == 0){
    			$primary = 'Yes';
    		}
    		$excludeArr = array('ship_id','set_default');
    		$dataArr = array('primary'=>$primary);
    		
    		
    			$this->cart_model->commonInsertUpdate(SHIPPING_ADDRESS,'insert',$excludeArr,$dataArr,$condition);
    			$shipID = $this->cart_model->get_last_insert_id();
    			$this->setErrorMessage('success','Shipping address added successfully');
    		
    		if ($primary == 'Yes'){
	    		$condition = array('id !='=>$shipID,'user_id'=>$this->checkLogin('U'));
    			$dataArr = array('primary'=>'No');
    			$this->cart_model->update_details(SHIPPING_ADDRESS,$dataArr,$condition);
    		}
    		redirect('cart');
    	}
    }
	
	/*************************** Cart Checkout function  *************************************/	
	public function cartcheckout(){
		if($this->input->post('Ship_address_val') !=''){
		
			$userid = $this->checkLogin('U');
			$this->cart_model->addPaymentCart($userid);
			redirect("checkout/cart");
		}else{
			$this->setErrorMessage('error','Please Add the Shipping address');		
			redirect("cart");
		}	
	}
	
	/*************************** User Cart Checkout function  *************************************/	
	public function usercartcheckout(){
		//echo '<pre>';print_r($_POST); die;
		if($this->input->post('Ship_address_val') !=''){
			if($this->input->post('payment_value')!=''){
				$userid = $this->checkLogin('U');
				$this->cart_model->addPaymentUserCart($userid);
				redirect("checkout/sellercart");
			}else{
				$this->setErrorMessage('error','Please Select the Payment Method');		
				redirect("cart");
			}
		}else{
			$this->setErrorMessage('error','Please Add the Shipping address');		
			redirect("cart");
		}	
	}
	
	/*************************** Subscribe Checkout function  *************************************/	
	public function Subscribecheckout(){
		if($this->input->post('SubShip_address_val') !=''){
			$userid = $this->checkLogin('U');
			$this->cart_model->addPaymentSubscribe($userid);
			redirect("checkout/subscribe");
		}else{
			$this->setErrorMessage('error','Please Add the Shipping address');		
			redirect("cart");
		}	
	}
	
	
}

/* End of file user.php */
/* Location: ./application/controllers/site/user.php */