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

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

class Product extends MY_Controller {
	function __construct(){
        parent::__construct();
		$this->load->helper(array('cookie','date','form','email','text'));
		$this->load->library(array('encrypt','form_validation'));		
		$this->load->model(array('product_model','user_model','seller_model','product_attribute_model','currency_model'));
		
		$this->data['loginCheck'] = $this->checkLogin('U');
		$this->data['AdminloginCheck'] = $this->checkLogin('A');
		$this->data['likedProducts'] = array();
	 	if ($this->data['loginCheck'] != ''){
	 		$this->data['likedProducts'] = $this->product_model->get_all_details(PRODUCT_LIKES,array('user_id'=>$this->checkLogin('U')));
	 	}
		#include('./geoplugin.php');
    }
   
	public function add_shop_product(){		
		if($this->checkLogin('U') != '' || $this->checkLogin('A') == 1){
			if($this->checkLogin('A') == 1){
				$status="Publish";
				$pay_status='Paid';
			}else if($this->checkLogin('U') == 1){
				$status="Publish";
				$pay_status='Paid';	
			} else {
				$status="UnPublish";
				$pay_status='Pending';
			} 
			if($this->checkLogin('U') != ''){
				$userID=$this->checkLogin('U');
			} else {
				$userID=1;
			}
			
			
			if($this->input->post('edit_product_id')==''){
				if($this->input->post('image_upload') == ''){ redirect($_SERVER['HTTP_REFERER']);}
			}
				$dir = getcwd()."/images/product/temp_img/";//dir absolute path
				$interval = strtotime('-24 hours');//files older than 24hours
				foreach (glob($dir."*.*") as $file) 
    			{
    			if (filemtime($file) <= $interval ) {unlink($file);}
				}
				
		$dir = getcwd()."/temp_digital_files/";//dir absolute path
				$interval = strtotime('-24 hours');//files older than 24hours
				foreach (glob($dir."*.*") as $file) 
    			{
    			if (filemtime($file) <= $interval ) {unlink($file);}
				}
		
		$UPDATE_product_Seourl =  $this->input->post('edit_product_id');
		$made_by =  $this->input->post('about_item');
		$product_condition = $this->input->post('what_item');
		$maked_on = $this->input->post('when_made');
		$category1 =  $this->input->post('main_cat_id');
		$category_id = $category1;
		if($this->input->post('level1_sub_cat') != ''){
		$category2 =  $this->input->post('level1_sub_cat');
		$category_id.= ','.$category2;
		}
		if($this->input->post('level2_sub_cat') != ''){
		$category3 =  $this->input->post('level2_sub_cat');
		$category_id.= ','.$category3;
		}
		
		//$category_id = $category1.",".$category2.",".$category3;
		$product_name =  $this->input->post('product_name');
		
		if($this->input->post('image_upload')!=''){
			$imgRnew0 = @explode('.',$this->input->post('image_upload'));
			$NewImg0 = url_title($imgRnew0[0], '-', TRUE);
			$image_upload0 = $NewImg0.'.'.$imgRnew0[1];
		}
		
		if($this->input->post('image_upload1')!=''){
			$imgRnew1 = @explode('.',$this->input->post('image_upload1'));
			$NewImg1 = url_title($imgRnew1[0], '-', TRUE);
			$image_upload1 = $NewImg1.'.'.$imgRnew1[1];
		}
		
		if($this->input->post('image_upload2')!=''){
			$imgRnew2 = @explode('.',$this->input->post('image_upload2'));
			$NewImg2 = url_title($imgRnew2[0], '-', TRUE);
			$image_upload2 = $NewImg2.'.'.$imgRnew2[1];
		}
		
		if($this->input->post('image_upload3')!=''){
			$imgRnew3 = @explode('.',$this->input->post('image_upload3'));
			$NewImg3 = url_title($imgRnew3[0], '-', TRUE);
			$image_upload3 = $NewImg3.'.'.$imgRnew3[1];
		}
		
		
		if($this->input->post('image_upload4')!=''){
			$imgRnew4 = @explode('.',$this->input->post('image_upload4'));
			$NewImg4 = url_title($imgRnew4[0], '-', TRUE);
			$image_upload4 = $NewImg4.'.'.$imgRnew4[1];
		}
		
		
		$timeImg=time();
			if($image_upload0 != '' || $this->input->post('existImage0') != ''){
				if($image_upload0 != ''){
					@copy('./images/product/temp_img/'.$image_upload0, './images/product/org-image/'.$timeImg.'-'.$image_upload0);
					@copy('./images/product/temp_img/'.$image_upload0, './images/product/'.$timeImg.'-'.$image_upload0);
					$this->ImageResizeWithCrop(550, 350, $timeImg.'-'.$image_upload0, './images/product/');
					@copy('./images/product/'.$timeImg.'-'.$image_upload0, './images/product/thumb/'.$timeImg.'-'.$image_upload0);
					$this->ImageResizeWithCrop(175, 150, $timeImg.'-'.$image_upload0, './images/product/thumb/');
					@copy('./images/product/temp_img/'.$image_upload0, './images/product/list-image/'.$timeImg.'-'.$image_upload0);
					$this->ImageResizeWithCrop(75, 75, $timeImg.'-'.$image_upload0, './images/product/list-image/');
					$imagesVal=$timeImg.'-'.$image_upload0;
				}else if($this->input->post('existImage0') != ''){
					$imagesVal=$this->input->post('existImage0');	
				}
			}
			  
			if($image_upload1 != '' || $this->input->post('existImage1') != ''){
				if($image_upload1 != ''){
					@copy('./images/product/temp_img/'.$image_upload1, './images/product/org-image/'.$timeImg.'-'.$image_upload1);
					@copy('./images/product/temp_img/'.$image_upload1, './images/product/'.$timeImg.'-'.$image_upload1);
					$this->ImageResizeWithCrop(550, 350, $timeImg.'-'.$image_upload1, './images/product/');
					@copy('./images/product/'.$timeImg.'-'.$image_upload1, './images/product/thumb/'.$timeImg.'-'.$image_upload1);
					$this->ImageResizeWithCrop(175, 150, $timeImg.'-'.$image_upload1, './images/product/thumb/');
					@copy('./images/product/temp_img/'.$image_upload1, './images/product/list-image/'.$timeImg.'-'.$image_upload1);
					$this->ImageResizeWithCrop(75, 75, $timeImg.'-'.$image_upload1, './images/product/list-image/');
					$imagesVal .=','.$timeImg.'-'.$image_upload1;
				}else if($this->input->post('existImage1') != ''){
					$imagesVal .=','.$this->input->post('existImage1');	
				}
			  }
			  
			  if($image_upload2 != '' || $this->input->post('existImage2')){
                  if($image_upload2 != ''){
						@copy('./images/product/temp_img/'.$image_upload2, './images/product/org-image/'.$timeImg.'-'.$image_upload2);
						@copy('./images/product/temp_img/'.$image_upload2, './images/product/'.$timeImg.'-'.$image_upload2);
						$this->ImageResizeWithCrop(550, 350, $timeImg.'-'.$image_upload2, './images/product/');
						@copy('./images/product/'.$timeImg.'-'.$image_upload2, './images/product/thumb/'.$timeImg.'-'.$image_upload2);
						$this->ImageResizeWithCrop(175, 150, $timeImg.'-'.$image_upload2, './images/product/thumb/');
						@copy('./images/product/temp_img/'.$image_upload2, './images/product/list-image/'.$timeImg.'-'.$image_upload2);
						$this->ImageResizeWithCrop(75, 75, $timeImg.'-'.$image_upload2, './images/product/list-image/');
						$imagesVal.=','.$timeImg.'-'.$image_upload2;
					} 
					else if($this->input->post('existImage2') != '')
					{
						$imagesVal .=','.$this->input->post('existImage2');	
					}
			  }
			  
			  if($image_upload3 != '' || $this->input->post('existImage3')){
				   	if($image_upload3 != ''){
						@copy('./images/product/temp_img/'.$image_upload3, './images/product/org-image/'.$timeImg.'-'.$image_upload3);
						@copy('./images/product/temp_img/'.$image_upload3, './images/product/'.$timeImg.'-'.$image_upload3);
						$this->ImageResizeWithCrop(550, 350, $timeImg.'-'.$image_upload3, './images/product/');
						@copy('./images/product/'.$timeImg.'-'.$image_upload3, './images/product/thumb/'.$timeImg.'-'.$image_upload3);
						$this->ImageResizeWithCrop(175, 150, $timeImg.'-'.$image_upload3, './images/product/thumb/');
						@copy('./images/product/temp_img/'.$image_upload3, './images/product/list-image/'.$timeImg.'-'.$image_upload3);
						$this->ImageResizeWithCrop(75, 75, $timeImg.'-'.$image_upload3, './images/product/list-image/');
						$imagesVal.=','.$timeImg.'-'.$image_upload3;
					}else if($this->input->post('existImage3') != ''){
						$imagesVal .=','.$this->input->post('existImage3');	
					}
			  }                        
			  
			  if($image_upload4 != '' || $this->input->post('existImage4')){
					if($image_upload4 != ''){ 
						@copy('./images/product/temp_img/'.$image_upload4, './images/product/org-image/'.$timeImg.'-'.$image_upload4);
						@copy('./images/product/temp_img/'.$image_upload4, './images/product/'.$timeImg.'-'.$image_upload4);
						$this->ImageResizeWithCrop(550, 350, $timeImg.'-'.$image_upload4, './images/product/');
						@copy('./images/product/'.$timeImg.'-'.$image_upload4, './images/product/thumb/'.$timeImg.'-'.$image_upload4);
						$this->ImageResizeWithCrop(175, 150, $timeImg.'-'.$image_upload4, './images/product/thumb/');
						@copy('./images/product/temp_img/'.$image_upload4, './images/product/list-image/'.$timeImg.'-'.$image_upload4);
						$this->ImageResizeWithCrop(75, 75, $timeImg.'-'.$image_upload4, './images/product/list-image/');
						$imagesVal.=','.$timeImg.'-'.$image_upload4;
					}else if($this->input->post('existImage4') != ''){
						$imagesVal .=','.$this->input->post('existImage4');	
					}
			  }
		//$imagesVal=$timeImg.'-'.$image_upload0.','.$Imgname1.','.$timeImg.'-'.$image_upload2.','.$timeImg.'-'.$image_upload3.','.$timeImg.'-'.$image_upload4;
		//echo $imagesVal; die;
		$description = $this->input->post('description');
		$tags = $this->input->post('jquery-tagbox-tags');
		$materials = $this->input->post('jquery-tagbox-materials'); 
		if($this->input->post('price_status') == 1)
		{
		$price = $this->input->post('price');	
		}else{
		$price = '';
		}
		$quantity = $this->input->post('quantity');	
		$giftcard='false';
		if($this->input->post('giftcard') == 'on'){
		$giftcard='true';
		} 
		
		$ship_duration = $this->input->post('ship_duration'); 
		if($ship_duration == 'custom')
		{
			$ship_duration=$this->input->post('processing_min').'-'.$this->input->post('processing_max').' '.$this->input->post('processing_time_units');
		}
		
		$ship_from=explode('|',$this->input->post('shipping_from'));
			$seourlBase = $seourl = url_title($product_name, '-', TRUE);
			$seourl_check = '0';
			$duplicate_url = $this->product_model->get_all_details(PRODUCT,array('seourl'=>$seourl));
			if ($duplicate_url->num_rows()>0){
				$seourl = $seourlBase.'-'.$duplicate_url->num_rows();
			}else {
				$seourl_check = '1';
			}
			$urlCount = $duplicate_url->num_rows();
			while ($seourl_check == '0'){
				$urlCount++;
				$duplicate_url = $this->product_model->get_all_details(PRODUCT,array('seourl'=>$seourl));
				if ($duplicate_url->num_rows()>0){
					$seourl = $seourlBase.'-'.$urlCount;
				}else {
					$seourl_check = '1';
				}
			}
			$productsEo=$seourl;
			$product_seller_id = rand(1111, 999999);
			if($UPDATE_product_Seourl != ''){
				$modifyDate=date('Y-m-d h:m:s');	
			} else {
				$modifyDate='';
			}
			$dataArr = array(
			            'made_by' => $made_by,
						'product_condition' => $product_condition,
						'modified' => $modifyDate,
						'maked_on' => $maked_on,
			            'product_name' => $product_name,
						'description' => $description,
						'price' => $price,
						'quantity' => $quantity,
						'image' => $imagesVal,
						'category_id' => $category_id,
						'tag' => $tags,
						'materials' => $materials,
						'status' => $status, 
						'pay_status' => $pay_status, 
						'seourl' => $seourl,
						'gift_card' => $giftcard,
						'user_id' => $userID,
						'seller_product_id' => $product_seller_id,
						'ship_duration' => $ship_duration,
						'ship_from' => $ship_from[1],
						//'ship_details' => $shippingVal
						);
						#echo "<pre>"; print_r($dataArr);  die;
			if($UPDATE_product_Seourl != ''){
				unset($dataArr['seourl']);unset($dataArr['user_id']);	
				unset($dataArr['status']);	
				unset($dataArr['pay_status']);				
				$this->product_model->edit_product($dataArr,array('seourl' => $UPDATE_product_Seourl));
				$productsEo=$UPDATE_product_Seourl;
			} else {
			   $this->product_model->add_product($dataArr);
			}	
			$product_id = $this->db->insert_id();
			
		if($this->input->post('item_name')=='physical'){
			if($this->input->post('shipping_to') != ''){	
				   if($UPDATE_product_Seourl != ''){
							$product_id=$this->input->post('edit_id');
							$this->product_model->commonDelete(SUB_SHIPPING,array('product_id' => $this->input->post('edit_id')));
								
				   }
				   
					$ship_to = $this->input->post('shipping_to');  
					$ship_to_id = $this->input->post('ship_to_id');   //print_r($ship_to_id); die;
					$cost_individual = $this->input->post('shipping_cost');	
					$cost_with_another = $this->input->post('shipping_with_another');
					for($i=0; $i < sizeof($ship_to); $i++)
					{
						
						$ship_name=@explode('|', $ship_to[$i]);
						if($ship_to[$i] == 'Everywhere Else'){
							$shipName='Everywhere Else';
							$shipId=232; 
							
						} else {
						$shipName=$ship_name[1];
						$shipId=$ship_to_id[$i];
						}
						$seourlBase = $seourl = url_title($shipName, '-', TRUE);
						$seourl_check = '0';
						$duplicate_url = $this->product_model->get_all_details(SUB_SHIPPING,array('ship_seourl'=>$seourl));
						if ($duplicate_url->num_rows()>0){
							$seourl = $seourlBase.'-'.$duplicate_url->num_rows();
						}else {
							$seourl_check = '1';
						}
						$urlCount = $duplicate_url->num_rows();
						while ($seourl_check == '0'){
							$urlCount++;
							$duplicate_url = $this->product_model->get_all_details(SUB_SHIPPING,array('ship_seourl'=>$seourl));
							if ($duplicate_url->num_rows()>0){
								$seourl = $seourlBase.'-'.$urlCount;
							}else {
								$seourl_check = '1';
							}
						}
					
						 $dataArrShip=array('product_id' => $product_id,'ship_id' => $shipId,'ship_name' => $shipName,'ship_cost' => $cost_individual[$i],'ship_seourl' => $seourl,'ship_other_cost' => $cost_with_another[$i]);
						//print_r( $dataArrShip); die;
						 $this->product_model->simple_insert(SUB_SHIPPING,$dataArrShip);
						
					}
			}
		}else if($this->input->post('item_name')=='digital'){
			if($UPDATE_product_Seourl != ''){
				$product_id=$this->input->post('edit_id');
				$this->product_model->commonDelete(SUB_SHIPPING,array('product_id' => $this->input->post('edit_id')));								
		   	}
			$shipName='Everywhere Else';
			$seourlBase = $seourl = url_title($shipName, '-', TRUE);
			$seourl_check = '0';
			$duplicate_url = $this->product_model->get_all_details(SUB_SHIPPING,array('ship_seourl'=>$seourl));
			if ($duplicate_url->num_rows()>0){
				$seourl = $seourlBase.'-'.$duplicate_url->num_rows();
			}else {
				$seourl_check = '1';
			}
			$urlCount = $duplicate_url->num_rows();
			while ($seourl_check == '0'){
				$urlCount++;
				$duplicate_url = $this->product_model->get_all_details(SUB_SHIPPING,array('ship_seourl'=>$seourl));
				if ($duplicate_url->num_rows()>0){
					$seourl = $seourlBase.'-'.$urlCount;
				}else {
					$seourl_check = '1';
				}
			}
			$dataArrShip=array('product_id'=> $product_id,'ship_id' => '232','ship_name' => 'Everywhere Else','ship_cost' => '0','ship_seourl' => $seourl,'ship_other_cost' => '0');
			$this->product_model->simple_insert(SUB_SHIPPING,$dataArrShip);
		}
	  	
		$item_name = $this->input->post('item_name');  //physical or digital
		if($UPDATE_product_Seourl != ''){ 
			$product_id=$this->input->post('edit_id');
		    $this->product_model->delete_subproduct_all(array('product_id' => $this->input->post('edit_id')));
		}
		if($item_name == 'physical'){  //if is it physical item we shoud add the attributes to the subproducts table else add digital file/ 
			if($UPDATE_product_Seourl != ''){
				if($this->input->post('exist_property_level')!=""){
					if($this->input->post('property_level')==''){
					$variation_name1 = $this->input->post('exist_property_level');
					}
					else{
						$variation_name1 = $this->input->post('property_level');
					}
				}
				else{
					$variation_name1 = $this->input->post('property_level');
				}
				
				/*If variation two existing*/
				if($this->input->post('exist_property_level1')!=""){
					if($this->input->post('property_level1')==''){
					$variation_name2 = $this->input->post('exist_property_level1');
					}
					else{
						$variation_name2 = $this->input->post('property_level1');
					}
				}
				else{
					$variation_name2 = $this->input->post('property_level1');
				}
								
			}
			else{
			$variation_name1 = $this->input->post('property_level');
			$variation_name2 = $this->input->post('property_level1');
			}			
			$variation_value1 = $this->input->post('variation_value');
			if($this->input->post('variation_scale1') != ''){
			    $variation_scale1 = $this->input->post('variation_scale1');
			}
			else{
				$variation_scale1='';
			}
			if($this->input->post('variation_scale2') != ''){
			    $variation_scale2 = $this->input->post('variation_scale2');
			}
			else{
				$variation_scale2='';
			}
				
			$variation_value2 =  $this->input->post('variation_value1');
				if($this->input->post('price_status') == 0 || $this->input->post('pricing') != 0){
				$pricing1 = $this->input->post('pricing');	
				}else{
				$pricing1 = array();
				}
			//print_r($pricing1); die;
			$stock1 = $this->input->post('listing_variation');						
			$stock2 = $this->input->post('listing_variation1');			
					if($variation_name1 != '' && count($this->input->post('DigiFiles')) == 1 && $variation_value1 != ''){
							for($i=0; $i< sizeof($variation_value1); $i++){
								if($pricing1[$i] == 0) { $prcg=NULL; } else { $prcg=$pricing1[$i]; }					
								  $attr_array1 = array('attr_name' => $variation_name1,
													'attr_value' => $variation_value1[$i],
													//'attr_seourl' => $seourl,
													'pricing' => $prcg,
													'stock_status' => $stock1[$i],
													'product_id' => $product_id,
													'attr_scale' => $variation_scale1);
													
								  $this->product_model->add_subproduct_insert($attr_array1);
							//echo $this->db->last_query();
								  }
							 
					}
					if($variation_name2 != '' && count($this->input->post('DigiFiles')) == 1 && $variation_value2 != ''){
						    
							for($i=0; $i< sizeof($variation_value2); $i++){
								$attr_array2 = array('attr_name' => $variation_name2,
													'attr_value' => $variation_value2[$i],
													//'attr_seourl' => $seourl,
													//'pricing' => $pricing2[$i],
													'stock_status' => $stock2[$i],
													'product_id' => $product_id,
													'attr_scale' => $variation_scale2);
												//echo "<pre>";  print_r($attr_array2); die;
													//echo $this->db->last_query();
							$this->product_model->add_subproduct_insert($attr_array2);
							}
					} 
		}
		else if(count($this->input->post('DigiFiles')) > 1){  // if is it digital item  
					
			$digitalfile =  $this->input->post('DigiFiles');
			//echo "<pre>"; print_r($digitalfile); die;
			$timeFile=time();
			for($i=1; $i < sizeof($digitalfile); $i++){
			@copy('./temp_digital_files/'.$digitalfile[$i], './digital_files/'.$timeFile.$digitalfile[$i]);
			$digitalValues .=$timeFile.$digitalfile[$i].',';
			}
			$attr_digital = array('digital_item' => $digitalValues,'product_id' => $product_id); 
			$this->product_model->add_subproduct_insert($attr_digital);
		}
			//$this->setErrorMessage('success','Product Added Successfully');
			if($this->input->post('AdminEditProduct')=='admin-edit-product'){
				redirect('admin-preview/'.$productsEo);	
			}else{
				redirect('preview/'.$productsEo);
			}
			//$this->load->view('site/shop/listitem_preview',$this->data);
		} else {
		$this->setErrorMessage('error','You Must Login First');
		redirect('');
		}
	}

			
   public function edit_shop_items($seourl){
	   if($this->checkLogin('U') != '' || $this->checkLogin('A') == 1){
	   
	   
	$this->data['edit_item_detail']=$this->product_model->get_all_details(PRODUCT,array('seourl'=>$seourl)); 
	$catId=explode(',',$this->data['edit_item_detail']->row()->category_id);
	$this->data['SubCatId1']=$this->product_model->get_all_details(CATEGORY,array('rootID'=> $catId[0],'status' =>'Active'))->result();
	$this->data['SubCatId2']=$this->product_model->get_all_details(CATEGORY,array('rootID'=> $catId[1],'status' =>'Active'))->result();
	//echo sizeof($this->data['SubCatId1']); die;
	$this->data['edit_attr_details']=$this->product_model->view_subproduct_details_join($this->data['edit_item_detail']->row()->id);
	//echo "<pre>"; print_r($this->data['edit_attr_details']->result_array()); 
	
	$this->data['edit_attr_check']=$this->product_model->get_subproductdetail_GroupEditpage(SUBPRODUCT,$this->data['edit_item_detail']->row()->id,'attr_name')->result_array();
	//echo '<pre>';print_r($this->data['edit_attr_check']->result_array()); die;
	//echo $this->db->last_query(); die;
	$this->data['edit_digital_check']=$this->product_model->get_all_details(SUBPRODUCT,array('product_id'=> $this->data['edit_item_detail']->row()->id))->result_array();
	$this->data['variations_result']= $this->product_model->get_all_details(PRODUCT_ATTRIBUTE,array())->result();
    $this->data['shiptoDetail'] = $this->product_model->get_all_details(SUB_SHIPPING,array('product_id' => $this->data['edit_item_detail']->row()->id))->result(); 
	$this->data['seller_info']=$this->seller_model->get_sellers_data(SELLER,$condition);
		$this->load->view('site/shop/edit_shop_listitems',$this->data);
	   } else {
		$this->setErrorMessage('error','You Must Login First');
		redirect('');
		}
   }
	
	
	public function load_category_Listpage(){ 
		$rootCat=explode('-',$this->uri->segment(2)); 
		$sortArr2 = array('field'=>'cat_position','type'=>'asc');
		$sortArr1 = array($sortArr2);
		$this->data['subCategories']=$this->product_model->get_all_details(CATEGORY,array('rootID'=>$rootCat[0],'status'=>'Active'),$sortArr1);
		$this->data['currentMainCategory']=$this->product_model->get_all_details(CATEGORY,array('id' => $rootCat[0],'status'=>'Active'))->row();
		
		if($this->data['currentMainCategory']->rootID == 0){
		$condition = " where p.status='Publish' and p.category_id LIKE '%".$rootCat[0]."' and u.group='Seller' and u.status='Active' or p.status='Publish' and p.user_id=0 and a.pricing IS NOT NULL group by p.id order by p.created desc";
		$this->data['Main_cat_product_list']=$this->product_model->view_product_details($condition);
		
		$this->data['meta_title'] =$this->data['currentMainCategory']->seo_title;
		$this->data['title'] =$this->data['currentMainCategory']->seo_title;
		$this->data['meta_keyword'] =$this->data['currentMainCategory']->seo_keyword; 
		$this->data['meta_description'] =$this->data['currentMainCategory']->seo_description;   
		//echo $this->db->last_query(); 
		//echo "<pre>"; print_r($this->data['Main_cat_product_list']->result_array()); die; 
		
		}
		$this->load->view('site/list/category_listpage',$this->data);
	}	
	
	
	
	public function load_product_Listpage(){
		
		
		if(isset($_SERVER['HTTPS'])){
        	$protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https://" : "http://";
	    }else{
			$protocol = 'http://';
	    }	
		
		$CUrurl = $protocol.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		$curUrl = @explode('?pg=',$CUrurl);
		
		if($this->input->get('pg') != ''){
			$paginationVal = $this->input->get('pg') * 8;
			$limitPaging = $paginationVal.',8 ';
		} else {
			$limitPaging = ' 8';
		}
		$newPage = $this->input->get('pg')+1;
		$qry_str = $curUrl[0].'?pg='.$newPage;



		$segmentArr=$this->uri->segment_array();
		$Catid=explode('-',$this->uri->segment(count($segmentArr))); 
		$sortArr2 = array('field'=>'cat_position','type'=>'asc');
		$sortArr1 = array($sortArr2);
		$currentcatDetails=$this->product_model->get_all_details(CATEGORY,array('id' => $Catid[0],'status'=>'Active'))->row();
		if($currentcatDetails->rootID == 0){
			if(!isset($_GET['ref'])){
				redirect('category-list/'.$this->uri->segment(count($segmentArr)));
			}
		}
		$this->data['currentsubCategory']=$currentcatDetails;
		$this->data['subCats']=$this->product_model->get_all_details(CATEGORY,array('rootID'=>$Catid[0],'status'=>'Active'),$sortArr1);
		$this->data['super_sub_catStatus']='Yes';
		$this->data['super_sub_catID']=$Catid[0];
		if($this->data['subCats']->num_rows() == 0){
			$this->data['super_sub_catStatus']='No';
			$this->data['subCats']=$this->product_model->get_all_details(CATEGORY,array('rootID'=>$currentcatDetails->rootID,'status'=>'Active'),$sortArr1);   
		   }
		$Catid1=explode('-',$this->uri->segment(2)); 
		$this->data['footerSubcatList']=$this->product_model->get_all_details(CATEGORY,array('rootID'=>$Catid1[0],'status'=>'Active'),$sortArr1);
		
		
		$made_by='';
		if($this->input->get('marketplace') == 'handmade'){
		$filterid=1;
		$made_by="and p.made_by='".$filterid."'";
		} else if($this->input->get('marketplace') == 'vintage'){
		$filterid=2;
		$made_by="and p.made_by='".$filterid."'";
		}
		$minprice='';
		$maxprice='';
		if($this->input->get('max_price') != '' || $this->input->get('min_price') != ''){
		$minVal = $this->input->get('min_price')/$this->data['currencyValue']; $maxVal = $this->input->get('max_price')/$this->data['currencyValue'];  
			if($maxVal == ''){
			$price="and ((p.price >'".$minVal."')"; 
			$prcing="or (a.pricing >'".$minVal."'))";
			}else { 
			$price="and ((p.price >'".$minVal."' and p.price <'".$maxVal."')";
			$prcing="or (a.pricing >'".$minVal."' and a.pricing <'".$maxVal."'))"; 
			}
		}
		$shipto='';  
		if($this->input->get('shipto') != ''){
		$shipto="and (ss.ship_id ='".$this->input->get('shipto')."' or ss.ship_id ='232')";
		}
		$shipfrom='';
		$location=mysql_real_escape_string($this->input->get('location'));
		if($location != ''){
		$shipfrom="and (u.city LIKE '%".$location."%' or u.district LIKE '%".$location."%' or u.state LIKE '%".$location."%' or u.country LIKE '%".$location."%')";
		}
		
		$gift_cards=''; 
		if($this->input->get('gift_cards') != ''){
		$gift_cards="and s.gift_card ='Yes'";
		} 
		//p.category_id LIKE '%,".$Catid[0]."'
		$condition = " where p.status='Publish' and FIND_IN_SET('".$Catid[0]."',p.category_id) ".$made_by." ".$gift_cards." ".$price." ".$prcing." ".$shipto." ".$shipfrom." and u.group='Seller' and u.status='Active' or p.status='Publish' and p.user_id=0 and a.pricing IS NOT NULL group by p.id order by p.created desc limit ".$limitPaging;
		$this->data['product_list']=$this->product_model->view_product_details($condition);
		
		
		
		if($this->data['product_list']->num_rows() > 0){
			$paginationDisplay  = '<a title="'.$newPage.'" class="landing-btn-more" href="'.$qry_str.'" style="display: none;">See More Products</a>';
		}else{
			$paginationDisplay  = '<a title="'.$newPage.'" class="landing-btn-more" style="display: none;">No More Products</a>';
		}	
		$this->data['paginationDisplay'] = $paginationDisplay;
		
		//$this->data['product_list']=$this->product_model->get_limited_details_FIND(PRODUCT,'',$condition);
		
		//echo $this->db->last_query(); die; 
		
	    $this->data['countryList'] = $this->product_model->get_all_details(COUNTRY_LIST,array())->result();
		
		$this->data['heading'] =$currentcatDetails->seo_title;
		$this->data['meta_title'] =$currentcatDetails->seo_title;		
		$this->data['meta_keyword'] =$currentcatDetails->seo_keyword; 
		$this->data['meta_description'] =$currentcatDetails->seo_description;   
		$this->load->view('site/list/product_listpage',$this->data);
	}	
	
	function Load_ajax_products_list($cat_id){
		
		//for($i=0; $i<10000000; $i++){ echo $i;} die;
		
		
	   if($this->input->get('cat_id') != ''){
		        $made_by='';   
		        if($this->input->get('marketplace') == 'handmade'){
				$filterid=1;
				$made_by="and p.made_by='".$filterid."'";
				} else if($this->input->get('marketplace') == 'vintage') {
				$filterid=2;
				$made_by="and p.made_by='".$filterid."'";
				}
		        
			    $minprice='';
			    $maxprice='';
			    if($this->input->get('max_price') != '' || $this->input->get('min_price') != ''){
				$minVal = $this->input->get('min_price')/$this->data['currencyValue']; $maxVal = $this->input->get('max_price')/$this->data['currencyValue'];  
					if($maxVal == ''){
					$price="and ((p.price >'".$minVal."')"; 
					$prcing="or (a.pricing >'".$minVal."'))";
					}else { 
					$price="and ((p.price >'".$minVal."' and p.price <'".$maxVal."')";
					$prcing="or (a.pricing >'".$minVal."' and a.pricing <'".$maxVal."'))"; 
					}
				}
				$shipto='';  
				if($this->input->get('shipto') != ''){
				$shipto="and ss.ship_id ='".$this->input->get('shipto')."'";
				}
				$shipfrom='';
				$location=mysql_real_escape_string($this->input->get('location'));
				if($location != ''){
				$shipfrom="and (u.city LIKE '%".$location."%' or u.district LIKE '%".$location."%' or u.state LIKE '%".$location."%' or u.country LIKE '%".$location."%')";
				}
				$gift_cards=''; 
				if($this->input->get('gift_cards') != ''){
				$gift_cards="and s.gift_card ='Yes'";
				} 
				$cat_id=explode('-',$this->input->get('cat_id'));
				$condition = " where p.status='Publish' and FIND_IN_SET('".$cat_id[0]."',p.category_id) ".$made_by." ".$gift_cards." ".$price." ".$prcing." ".$shipto." ".$shipfrom." and u.group='Seller' and u.status='Active' or p.status='Publish' and p.user_id=0 and a.pricing IS NOT NULL group by p.id order by p.created desc";
	  } 
		$product_list=$this->product_model->view_product_details($condition);  
		 //echo $this->db->last_query(); die;
		//print_r($product_list->result_array()); die;
	//$Imgheight=array(220,147,333,232,299,159,242,167,298,153,129);
	
	if($product_list->num_rows() > 0) {
	
       
		 $i=0; $hover=0; foreach($product_list->result_array() as $products) {
			$Images=explode(',',$products['image']);
			 $strhove="'".$hover."'";    // width="215" height="'.$Imgheight[$i].'"
               
        echo '<li class="style-type1"><a href="products/'.$products['seourl'].'"><img src="images/product/org-image/'.$Images[0].'" width="215" title=" '.stripslashes($products['product_name']).'" /> </a>
        <div class="product_hide">
        <a href="javascript:void(0);"> </a>
        <div class="product_fav">';
        	if($this->data['loginCheck'] !=''){
			$favArr = $this->product_model->getUserFavoriteProductDetails(stripslashes($products['id']));
			#print_r($favArr); die;
			if(empty($favArr)){ $status="'Fresh'";
			echo '<a href="javascript:void(0);" onclick="return changeProductToFavourite('.stripslashes($products['id']).','.$status.');">
			<input type="submit" value="" class="hoverfav_icon" />
			</a>';
			  } else {        $status="'Old'";               
			echo '<a href="javascript:void(0);" onclick="return changeProductToFavourite('.stripslashes($products['id']).','.$status.')">
			<input type="submit" value="" class="hoverfav_icon1" />
			</a>';
			 }} else { $status="'Fresh'";
			echo '<a href="javascript:void(0);" onclick="return changeProductToFavourite('.stripslashes($products['id']).','.$status.')">
			<input type="submit" value="" class="hoverfav_icon" />
			</a>';
            } 
          echo '<!--<a href="#">
              <input class="hoverfav_icon" type="submit" value="">
           </a>-->
         </div>
		 
     <div class="hoverdrop_icon">
    <a href="javascript:hoverView('.$strhove.');">
    <div id="hoverlist'.$hover.'" class="hover_lists" style="display: none;"><h2>Your Lists</h2><div class="lists_check">';
					foreach($this->data['userLists'] as $Lists){ 
					#print_r($this->data['userLists']); die;
					$haveListIn = $this->user_model->check_list_products(stripslashes($products['id']),$Lists['id'])->num_rows();
                    #echo $haveListIn;
                    if($haveListIn>0){$chk='checked="checked"';}else{ $chk='';}
                    
                    echo '<input type="checkbox" class="check_box" onclick="return addproducttoList('.$Lists['id'].','.stripslashes($products['id']).');" '.$chk.' />';
                    echo '<label>'.$Lists['name'].'</label>';
                    }
					if(!empty($this->data['userRegistry'])){ 
					$haveRegisryIn = $this->user_model->check_registry_products($products['id'],$this->data['userRegistry']->user_id)->num_rows();
					if($haveRegisryIn>0){$chk='checked="checked"';}else{ $chk='';}
					echo '<input type="checkbox" class="check_box" onclick="return manageRegisrtyProduct('.$this->data['userRegistry']->user_id.','.$products['id'].');"'.$chk.' />
					<label><span class="registry_icon"></span>Wedding Registry</label>';
					 }
                    echo '</div>                                                    
                    <div class="new_list">
                        <form method="post" action="site/user/add_list">
                            <input type="hidden" value="1" name="ddl" />
                            <input type="hidden" value="'.$products['id'].'" name="productId" />
                            <input type="text" placeholder="New list" class="list_scroll" name="list" id="creat_list_'.$i.'" />
                            <input type="submit" value="Add" class="primary-button" onclick="return validate_create_list('.$i.');" />
                        </form>
                    </div></div>'; 
	echo '</div>
</a>
</div>
</div>
</div>

<span class="image-detail-text"><a href="products/'.$products['seourl'].'">'.$products['product_name'].'</a></span>
<label><a class="bottom-text" href="shop-section/'.$products['shop_seourl'].'">'.$products['shop_name'].'</a>
<p class="dollar-sign">'; echo $this->data['currencySymbol']; if($products['price'] != 0.00) { echo number_format($this->data['currencyValue']*$products['price'],2); } else { echo number_format($this->data['currencyValue']*$products['pricing'],2); echo '+'; }
  echo '&nbsp;<span class="currency_code">'; echo $this->data['currencyType'];'</span></p></label> </li>'; 
  
  echo '<script type="text/javascript">';
    echo "var handler = null;
    var options = {
      autoResize: true, 
      container: $('#main'), 
      offset: 35,
      itemWidth: 200
    };
    function onScroll(event) {
      // Check if we're within 100 pixels of the bottom edge of the broser window.
      var winHeight = window.innerHeight ? window.innerHeight : $(window).height(); // iphone fix
      var closeToBottom = ($(window).scrollTop() + winHeight > $(document).height() - 100);
      if(closeToBottom) {
        handler = $('#tiles li');
        handler.wookmark(options);
      }
    };
    $(document).ready(new function() {
      $(document).bind('scroll', onScroll);
      handler = $('#tiles li');
      handler.wookmark(options);
    });
$(document).ready(function(){";
  echo '$(".hoverdrop_icon").click(function(){  
    $("#hoverlist1").toggle();
  });
});   
</script>';
   $hover++;
       $i++;  if($i == 10) { $i=0;} }
   
     
	}else{   
	
	$lin = substr($_SERVER['HTTP_REFERER'], 0, strpos($_SERVER['HTTP_REFERER'],'?'));
	echo ' <section>
                       <div class="main">
                        <div style="margin:20px 0" class="search-error">
                       <h3 class="crumbs"> Darn. No items match your selections. </h3>
              <p class="newline"> Try <a href="'.$lin.'">showing all items .</a>  </p>
                           </div> 
                       </div> 
                </section>';
	}
	
	
	}
	
			
	public function onboarding(){
		if ($this->checkLogin('U') == ''){
			redirect(base_url());
		}else {
			$this->data['userDetails'] = $this->product_model->get_all_details(USERS,array('id'=>$this->checkLogin('U')));
			if ($this->data['userDetails']->num_rows() == 1){
				if ($this->data['mainCategories']->num_rows()>0){
					foreach ($this->data['mainCategories']->result() as $cat){
//						$condition = " where p.category_id like '".$cat->id.",%' OR p.category_id like '%,".$cat->id."' OR p.category_id like '%,".$cat->id.",%' OR p.category_id='".$cat->id."' order by p.created desc";
						$condition = " where FIND_IN_SET('".$cat->id."',p.category_id) and p.quantity>0 and p.status='Publish' and u.group='Seller' and u.status='Active' or p.status='Publish' and p.quantity > 0 and p.user_id=0 and FIND_IN_SET('".$cat->id."',p.category_id) order by p.created desc";
						$this->data['productDetails'][$cat->cat_name] = $this->product_model->view_product_details($condition);
					}
				}
				$this->load->view('site/user/onboarding',$this->data);
			}else {
				redirect(base_url());
			}
		}
	}
	
	public function onboarding_get_products_categories(){
		$returnCnt = '<div id="onboarding-category-items"><ol class="stream vertical">';
		$left = $top = $count = 0;
		$width = 220;
		$productArr = array();
		$catID = explode(',', $this->input->get('categories'));
		if (count($catID)>0){
			foreach ($catID as $cat){
//				$condition = " where p.category_id like '".$cat.",%' AND p.status = 'Publish' OR p.category_id like '%,".$cat."' AND p.status = 'Publish' OR p.category_id like '%,".$cat.",%' AND p.status = 'Publish' OR p.category_id='".$cat."' AND p.status = 'Publish'";
				$condition = " where FIND_IN_SET('".$cat."',p.category_id) and p.quantity>0 and p.status='Publish' and u.group='Seller' and u.status='Active' or p.status='Publish' and p.quantity > 0 and p.user_id=0 and FIND_IN_SET('".$cat."',p.category_id) order by p.created desc";
				$productDetails = $this->product_model->view_product_details($condition);
				if ($productDetails->num_rows()>0){
					foreach ($productDetails->result() as $productRow){
						if (!in_array($productRow->id, $productArr)){
							array_push($productArr, $productRow->id);
							$img = '';
							$imgArr = explode(',', $productRow->image);
							if (count($imgArr)>0){
								foreach ($imgArr as $imgRow){
									if ($imgRow != ''){
										$img = $imgRow;
										break;
									}
								}
							}
							if ($img!=''){
								$count++;
								$leftPos = $count%3;
								$leftPos = ($leftPos==0)?3:$leftPos;
								$leftPos--;
								if ($count%3 == 0){
									$topPos = $count/3;
								}else {
									$topPos	= ceil($count/3);
								}
								$topPos--;
								$leftVal = $leftPos*$width;
								$topVal = $topPos*$width;
								$returnCnt .='
									<li style="opacity: 1; top: '.$topVal.'px; left: '.$leftVal.'px;" class="start_marker_"><span class="pre hide"></span>
										<div class="figure-item">
											<a class="figure-img">
												<span style="background-image:url(\''.base_url().'images/product/'.$img.'\')" class="figure">
													<em class="back"></em>
													<img height="200" data-height="640" data-width="640" src="'.base_url().'images/product/'.$img.'"/>
												</span>
											</a>
											<a tid="'.$productRow->seller_product_id.'" class="button fancy noedit" href="#"><span><i></i></span>'.LIKE_BUTTON.'</a>
										</div>
									</li>
								';
							}
						}
					}
				}
			}
		}
		$returnCnt .= '
			</div>
		';
		echo $returnCnt;
	}
	
	public function onboarding_get_users_follow(){
		$catID = explode(',', $this->input->get('categories'));
		$productArr = array();
		$userArr = array();
		$userCountArr = array();
		$returnArr = array();
		
		/************Get Suggested Users List******************************/
		
		$returnArr['suggested'] = '<ul class="suggest-list">';
		if (count($catID)>0){
			foreach ($catID as $cat){
//				$condition = " where p.category_id like '".$cat.",%' AND p.status = 'Publish' OR p.category_id like '%,".$cat."' AND p.status = 'Publish' OR p.category_id like '%,".$cat.",%' AND p.status = 'Publish' OR p.category_id='".$cat."' AND p.status = 'Publish'";
				$condition = " where FIND_IN_SET('".$cat."',p.category_id) and p.quantity>0 and p.status='Publish' and u.group='Seller' and u.status='Active' or p.status='Publish' and p.quantity > 0 and p.user_id=0 and FIND_IN_SET('".$cat."',p.category_id)";
				$productDetails = $this->product_model->view_product_details($condition);
				if ($productDetails->num_rows()>0){
					foreach ($productDetails->result() as $productRow){
						if (!in_array($productRow->id, $productArr)){
							array_push($productArr, $productRow->id);
							if ($productRow->user_id != ''){
								if (!in_array($productRow->user_id, $userArr)){
									array_push($userArr, $productRow->user_id);
									$userCountArr[$productRow->user_id] = 1;
								}else {
									$userCountArr[$productRow->user_id]++;
								}
							}
						}
					}
				}
			}
		}
		arsort($userCountArr);
		$limitCount = 0;
		foreach ($userCountArr as $user_id => $products){
			if ($user_id!=''){
				$condition = array('id'=>$user_id,'is_verified'=>'Yes','status'=>'Active');
				$userDetails = $this->product_model->get_all_details(USERS,$condition);
				if ($userDetails->num_rows()==1){
					$condition = array('user_id'=>$user_id,'status'=>'Publish');
					$userProductDetails = $this->product_model->get_all_details(PRODUCT,$condition);
					if ($limitCount<10){
						$userImg = $userDetails->row()->thumbnail;
						if ($userImg == ''){
							$userImg = 'user-thumb1.png';
						}
						$returnArr['suggested'] .= '
							<li><span class="vcard"><img src="'.base_url().'images/users/'.$userImg.'"></span>
							<b>'.$userDetails->row()->full_name.'</b><br>
							'.$userDetails->row()->followers_count.' followers<br>
							'.$userProductDetails->num_rows().' things<br>
							<a uid="'.$user_id.'" class="follow-user-link" href="javascript:void(0)">Follow</a>
							<span class="category-thum">';
						$plimit = 0;
                           if ($userProductDetails->num_rows()>0){
                           	foreach ($userProductDetails->result() as $userProduct){
                           		if ($plimit>3){break;}
                                 $img = '';
                                 $imgArr = explode(',', $userProduct->image);
                                 if (count($imgArr)>0){
                                 	foreach ($imgArr as $imgRow){
                                 		if ($imgRow != ''){
                                 			$img = $imgRow;
                                 			break;
                                 		}
                                 	}
                                 }
                                 if ($img != ''){
                                 
						$returnArr['suggested'] .='<img alt="'.$userProduct->product_name.'" src="'.base_url().'images/product/'.$img.'">';
							    $plimit++;
                                 }
                           	}
                           } 
                            
						$returnArr['suggested'] .='</span>
							</li>
						';
						$limitCount++;
					}
				}
			}
		}
		$returnArr['suggested'] .='</ul>';
		
		/***********************************************************/
		
		/****************Get Top Users For All Categories**********/
		$returnArr['categories'] = '';
		if ($this->data['mainCategories']->num_rows()>0){
			foreach ($this->data['mainCategories']->result() as $catRow){
				if ($catRow->id != '' && $catRow->cat_name != ''){
					$returnArr['categories'] .= '
					<div style="display:none;" class="intxt '.url_title($catRow->cat_name,'_',TRUE).'">
					<p class="stit"><span>'.$catRow->cat_name.'</span>
					<button class="btns-blue-embo btn-followall">Follow All</button></p>
					<ul class="suggest-list">';
					$userCountArr = $this->product_model->get_top_users_in_category($catRow->id);
					$limitCount = 0;
					foreach ($userCountArr as $user_id => $products){
						if ($user_id!=''){
							$condition = array('id'=>$user_id,'is_verified'=>'Yes','status'=>'Active');
							$userDetails = $this->product_model->get_all_details(USERS,$condition);
							if ($userDetails->num_rows()==1){
								$condition = array('user_id'=>$user_id,'status'=>'Publish');
								$userProductDetails = $this->product_model->get_all_details(PRODUCT,$condition);
								if ($limitCount<10){
									$userImg = $userDetails->row()->thumbnail;
									if ($userImg == ''){
										$userImg = 'user-thumb1.png';
									}
									$returnArr['categories'] .= '
											<li><span class="vcard"><img src="'.base_url().'images/users/'.$userImg.'"></span>
											<b>'.$userDetails->row()->full_name.'</b><br>
											'.$userDetails->row()->followers_count.' followers<br>
											'.$userProductDetails->num_rows().' things<br>
											<a uid="'.$user_id.'" class="follow-user-link" href="javascript:void(0)">Follow</a>
											<span class="category-thum">';
									$plimit = 0;
									if ($userProductDetails->num_rows()>0){
										foreach ($userProductDetails->result() as $userProduct){
										if ($plimit>3){break;}
											$img = '';
											$imgArr = explode(',', $userProduct->image);
											if (count($imgArr)>0){
												foreach ($imgArr as $imgRow){
													if ($imgRow != ''){
														$img = $imgRow;
														break;
													}
												}
											}
											if ($img != ''){
												 
												$returnArr['categories'] .='<img alt="'.$userProduct->product_name.'" src="'.base_url().'images/product/'.$img.'">';
													$plimit++;
											}
										}
									}

									$returnArr['categories'] .='</span>
											</li>
										';
									$limitCount++;
								}
							}
						}
					}
					$returnArr['categories'] .='</ul></div>';
				}
			}
		}
		
		/**********************************************************/
		
		echo json_encode($returnArr);
	}
	
	public function display_product_shuffle(){
		$productDetails = $this->product_model->view_product_details(' where p.quantity>0 and p.status="Publish" and u.group="Seller" and u.status="Active" or p.status="Publish" and p.quantity > 0 and p.user_id=0');
		if ($productDetails->num_rows()>0){
			$productId = array();
			foreach ($productDetails->result() as $productRow){
				array_push($productId, $productRow->id);
			}
			array_filter($productId);
			shuffle($productId);
			$pid = $productId[0];
			$productName = '';
			foreach ($productDetails->result() as $productRow){
				if ($productRow->id == $pid){
					$productName = $productRow->product_name;
				}
			}
			if ($productName == ''){
				redirect(base_url());
			}else {
				$link = 'things/'.$pid.'/'.url_title($productName,'-');
				redirect($link);
			}
		}else {
			redirect(base_url());
		}
	}
	
	public function display_product_detail($seourl){
			$dataArr=$this->data['preview_item_detail']=$this->product_model->get_all_details(PRODUCT,array('seourl'=>$seourl))->result_array();   
			
			/* update View Count*/
			$dataArrw = array('view_count'=>$this->data['preview_item_detail'][0]['view_count']+1);
			$conditionw = array('seourl'=>$seourl);
			$this->product_model->update_details(PRODUCT,$dataArrw,$conditionw);
		
		  
			$variation=$this->product_model->get_subproductdetail_Group(SUBPRODUCT,array('product_id'=> $this->data['preview_item_detail'][0]['id']),'attr_name');
	        $this->data['added_item_details']=$dataArr;
			if(count($variation)==0)
			{
				$this->data['variations_one']="";
				$this->data['variations_two']="";
			}
			if(count($variation)==1)
			{
				$this->data['variations_one']=$variation[0]['attr_name'];
				$this->data['variations_two']="";
				$this->data['variations_one_values']=$this->product_model->get_all_details(SUBPRODUCT,array('product_id'=> $this->data['preview_item_detail'][0]['id'],'attr_name'=>$variation[0]['attr_name']))->result_array();
			}
			if(count($variation)==2)
			{
				$this->data['variations_one']=$variation[0]['attr_name'];
				$this->data['variations_two']=$variation[1]['attr_name'];
				$this->data['variations_one_values']=$this->product_model->get_all_details(SUBPRODUCT,array('product_id'=> $this->data['preview_item_detail'][0]['id'],'attr_name'=>$variation[0]['attr_name']))->result_array();
				$this->data['variations_two_values']=$this->product_model->get_all_details(SUBPRODUCT,array('product_id'=> $this->data['preview_item_detail'][0]['id'],'attr_name'=>$variation[1]['attr_name']))->result_array();
			}
			$columns='*';
			$sellerid=$dataArr['0']['user_id'];
			$product_id=$this->data['preview_item_detail'][0]['id'];
			$this->data['selectedSeller_details']=$this->seller_model->display_seller_view_admin($sellerid)->result_array();
		$condition = " where p.quantity>0 and p.status='Publish' and u.group='Seller' and u.status='Active' and p.id!='".$product_id."' and p.user_id='".$sellerid."' group by p.id order by p.created desc";
			$this->data['shopProductDetails'] = $this->product_model->view_product_details($condition)->result_array();	
			$this->data['ProductFavoriteCount']= $this->product_model->getUserFavoriteProductCount($product_id);
			#$this->data['productReview']=$this->product_model->get_all_details(PRODUCT_FEEDBACK,array('seller_product_id'=> $this->data['preview_item_detail'][0]['id'],'status'=>'Active'))->result_array();
			$this->data['shipping_details']=$this->product_model->get_all_details(SUB_SHIPPING,array('product_id'=> $this->data['preview_item_detail'][0]['id']))->result_array();
			$this->data['productReview']=$this->product_model->get_productfeed_details($this->data['preview_item_detail'][0]['user_id'])->result_array();
			$this->data['subProduct']=$this->product_model->get_all_details(SUBPRODUCT,array('product_id'=> $this->data['preview_item_detail'][0]['id'],'digital_item !='=>''));
			#echo "<pre>";print_r($this->data['productReview']); die;
			$this->data['heading'] =$this->data['preview_item_detail'][0]['product_name'].' by '.$this->data['selectedSeller_details'][0]['seller_businessname'].' on '.$this->config->item('email_title');
			$this->data['meta_title'] =$this->data['preview_item_detail'][0]['product_name'].' by '.$this->data['selectedSeller_details'][0]['seller_businessname'].' on '.$this->config->item('email_title');
			$this->data['meta_keyword'] =$this->data['preview_item_detail'][0]['tag'];
			$this->data['meta_description'] =substr($this->data['preview_item_detail'][0]['description'],0,150);
			$this->load->view('site/product/product_detail',$this->data);
				
	}
	
	public function delete_featured_find(){
		$uid = $this->checkLogin('U');
		$dataArr = array('feature_product'=>'');
		$condition = array('id'=>$uid);
		$this->product_model->update_details(USERS,$dataArr,$condition);
		echo '1';
	}
	
	
	/* Ajax update for Product Details product */
	public function ajaxProductDetailAttributeUpdate(){
	
		$attrPriceVal = $this->product_model->get_all_details(SUBPRODUCT,array('pid'=>$this->input->post('attId'),'product_id'=>$this->input->post('prdId')));
		/*$shopattrVal = $this->product_model->get_all_details(SHOPPING_CART,array('user_id'=>$this->checkLogin('U'),'attribute_values'=>$attrPriceVal->row()->attr_id,'product_id'=>$this->input->post('prdId')));
		if($shopattrVal->row()->quantity != ''){ $ShopVals = $shopattrVal->row()->quantity; }else{ $ShopVals = 0;} .'|'.$ShopVals*/
		
		echo $attrPriceVal->row()->attr_id.'|'.$attrPriceVal->row()->attr_price;
		
	}
		public function feedback(){
		
			$user_id = $this->input->post('rate');
			$rating = $this->input->post('rating_value');
			$title = $this->input->post('title');
			$description = $this->input->post('description');
			$store_name = $this->input->post('store_name');
			$seller_product_id = $this->input->post('seller_product_id');

			if($user_id!='')
			{
				$this->user_model->simple_insert(PRODUCT_FEEDBACK,array('title' => $title,'description' => $description,'seller_product_id' => $seller_product_id,'rating' => $rating, 'voter_id' => $user_id));
			}
				redirect($base_url.'store/'.$user_id.'-'.$store_name);
	}
	
	public function feedback_product_view()
	{
		
		$product_seourl = $this->uri->segment(3, 0);
		$seller_id = $this->uri->segment(2, 0);
		$this->data['userVal'] = $this->seller_model->get_userselldetail_data('product_template,seller_businessname,seourl',$seller_id);

		$this->data['productVal'] = $this->product_model->get_productdetail_data($product_seourl);

		$nametemp = $userVal[0]['product_template'];		
		$pid = $this->data['productVal'][0]['id'];
		
		
		$this->data['PrdAttrName'] = $this->product_model->view_subproduct_details_group($pid);
		$this->data['PrdAttrVal'] = $this->product_model->view_subproduct_details_join($pid);
	

//$this->data['productVal'] = $this->product_model->get_storedetail_data_store('id,seourl,product_name,sale_price,image,product_featured,user_id',$cat_id,$searchPerPage,$paginationNo,$seller_id);
		

		$this->load->view('site/product/product_feedback.php',$this->data);
		}
	
	public function add_featured_find(){
		$pid = $this->input->post('tid');
		$uid = $this->checkLogin('U');
		$dataArr = array('feature_product'=>$pid);
		$condition = array('id'=>$uid);
		$this->product_model->update_details(USERS,$dataArr,$condition);
		$datestring = "%Y-%m-%d %h:%i:%s";
		$time = time();
		$createdTime = mdate($datestring,$time);
		$actArr = array(
			'activity'		=>	'featured',
			'activity_id'	=>	$pid,
			'user_id'		=>	$this->checkLogin('U'),
			'activity_ip'	=>	$this->input->ip_address(),
			'created'		=>	$createdTime
		);
		$this->product_model->simple_insert(NOTIFICATIONS,$actArr);
		$this->send_feature_noty_mail($pid);
		echo '1';
	}
	
	public function share_with_someone(){
		$returnStr['status_code'] = 0;
		$thing = array();
		$thing['url'] = $this->input->post('url');
		$thing['name'] = $this->input->post('name');
		$thing['id'] = $this->input->post('oid');
		$thing['refid'] = $this->input->post('ooid');
		$thing['msg'] = $this->input->post('message');
		$thing['uname'] = $this->input->post('uname');
		$thing['timage'] = base_url().$this->input->post('timage');
		$email = $this->input->post('emails');
		$users = $this->input->post('users');
		if (valid_email($email)){
			$this->send_thing_share_mail($thing,$email);
			$returnStr['status_code'] = 1;
		}else {
			$returnStr['message'] = 'Invalid email';
		}
		echo json_encode($returnStr);
	}
	
	public function send_thing_share_mail($thing='',$email=''){
	
							$newsid='2';
							$template_values=$this->product_model->get_newsletter_template_details($newsid);
							$adminnewstemplateArr=array('meta_title'=> $this->config->item('meta_title'),'logo'=> $this->data['logo'],'uname'=>ucfirst($thing['uname']),'name'=>$thing['name'],'url'=>$thing['url'],'msg'=>$thing['msg'],'email_title'=>$this->config->item('email_title'));
							extract($adminnewstemplateArr);
							$subject = ucfirst($thing['uname']).' '.$template_values['news_subject'].' '.$this->config->item('email_title');
							$message .= '<!DOCTYPE HTML>
								<html>
								<head>
								<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
								<meta name="viewport" content="width=device-width"/>
								<title>'.$adminnewstemplateArr['meta_title'].' - Share Things</title>
								<body>';
							include('./newsletter/registeration'.$newsid.'.php');	
							
							$message .= '</body>
								</html>';
		if($template_values['sender_name']=='' && $template_values['sender_email']==''){
			$sender_email=$this->config->item('site_contact_mail');
			$sender_name=$this->config->item('email_title');
		}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'=>$subject,
							'body_messages'=>$message
							);
		$email_send_to_common = $this->product_model->common_email_send($email_values);
		
/*		echo $this->email->print_debugger();die;
*/	
	}
	
	public function add_have_tag(){
		$returnStr['status_code'] = 0;
		$tid = $this->input->post('thing_id');
		$uid = $this->checkLogin('U');
		if ($uid != ''){
			$ownArr = explode(',', $this->data['userDetails']->row()->own_products);
			$ownCount = $this->data['userDetails']->row()->own_count;
			if (!in_array($tid, $ownArr)){
				array_push($ownArr, $tid);
				$ownCount++;
				$dataArr = array('own_products'=>implode(',', $ownArr),'own_count'=>$ownCount);
				$wantProducts = $this->product_model->get_all_details(WANTS_DETAILS,array('user_id'=>$this->checkLogin('U')));
				if ($wantProducts->num_rows() == 1){
					$wantProductsArr = explode(',', $wantProducts->row()->product_id);
					if (in_array($tid, $wantProductsArr)){
						if (($key = array_search($tid, $wantProductsArr))!== false){
							unset($wantProductsArr[$key]);
						}
						$wantsCount = $this->data['userDetails']->row()->want_count;
						$wantsCount--;
						$dataArr['want_count'] = $wantsCount;
						$this->product_model->update_details(WANTS_DETAILS,array('product_id'=>implode(',', $wantProductsArr)),array('user_id'=>$uid));
					}
				}
				$this->product_model->update_details(USERS,$dataArr,array('id'=>$uid));
				$returnStr['status_code'] = 1;
			}
		}
		echo json_encode($returnStr);
	}
	
	public function delete_have_tag(){
		$returnStr['status_code'] = 0;
		$tid = $this->input->post('thing_id');
		$uid = $this->checkLogin('U');
		if ($uid != ''){
			$ownArr = explode(',', $this->data['userDetails']->row()->own_products);
			$ownCount = $this->data['userDetails']->row()->own_count;
			if (in_array($tid, $ownArr)){
				if ($key = array_search($tid, $ownArr) !== false){
					unset($ownArr[$key]);
					$ownCount--;
				}
				$this->product_model->update_details(USERS,array('own_products'=>implode(',', $ownArr),'own_count'=>$ownCount),array('id'=>$uid));
				$returnStr['status_code'] = 1;
			}
		}
		echo json_encode($returnStr);
	}
	
	public function upload_product_image(){
		$returnStr['status_code'] = 0;
		$config['overwrite'] = FALSE;
    	$config['allowed_types'] = 'jpg|jpeg|gif|png';
//	    $config['max_size'] = 2000;
	    $config['upload_path'] = './images/product';
	    $this->load->library('upload', $config);
		if ( $this->upload->do_upload('thefile')){
	    	$imgDetails = $this->upload->data();
	    	$returnStr['image']['url'] = base_url().'images/product/'.$imgDetails['file_name'];
	    	$returnStr['image']['width'] = $imgDetails['image_width'];
	    	$returnStr['image']['height'] = $imgDetails['image_height'];
	    	$returnStr['image']['name'] = $imgDetails['file_name'];
	    	$this->imageResizeWithSpace(650, 320, $imgDetails['file_name'], './images/product/');
			@copy('./images/product/'.$imgDetails['file_name'], './images/product/thumb/'.$imgDetails['file_name']);
			$this->imageResizeWithSpace(280, 206, $imgDetails['file_name'], './images/product/thumb/');
	    	$returnStr['status_code'] = 1;
		}else {
			$returnStr['message'] = 'Can\'t be upload';
		}
		echo json_encode($returnStr);
	}
	
	
	
	
	public function add_new_thing(){
		$returnStr['status_code'] = 0;
		$returnStr['message'] = '';
		if ($this->checkLogin('U') != ''){
			$pid = $this->product_model->add_user_product($this->checkLogin('U'));
			$returnStr['status_code'] = 1;
			$userDetails = $this->data['userDetails'];
			$total_added = $userDetails->row()->products;
			$total_added++;
			$this->product_model->update_details(USERS,array('products'=>$total_added),array('id'=>$this->checkLogin('U')));
			$returnStr['thing_url'] = 'user/'.$userDetails->row()->user_name.'/things/'.$pid.'/'.url_title($this->input->post('name'),'-');
		}
		echo json_encode($returnStr);
	}
	
	public function display_user_thing(){
		$uname = $this->uri->segment(2,0);
		$pid = $this->uri->segment(4,0);
		$this->data['productUserDetails'] = $this->product_model->get_all_details(USERS,array('user_name'=>$uname));
		$this->data['productDetails'] = $this->product_model->get_all_details(USER_PRODUCTS,array('seller_product_id'=>$pid,'status'=>'Publish'));
		if ($this->data['productDetails']->num_rows() == 1){
			$this->data['heading'] = $this->data['productDetails']->row()->product_name;
			$categoryArr = explode(',', $this->data['productDetails']->row()->category_id);
			$catID = 0;
			if (count($categoryArr)>0){
				foreach ($categoryArr as $catRow){
					if ($catRow != ''){
						$catID = $catRow;
						break;
					}
				}
			}
			$this->data['relatedProductsArr'] = $this->product_model->get_products_by_category($catID);
			if ($this->data['productDetails']->row()->meta_title != ''){
				$this->data['meta_title'] = $this->data['productDetails']->row()->meta_title;
			}
			if ($this->data['productDetails']->row()->meta_keyword != ''){
		    	$this->data['meta_keyword'] = $this->data['productDetails']->row()->meta_keyword;
			}
			if ($this->data['productDetails']->row()->meta_description != ''){
		    	$this->data['meta_description'] = $this->data['productDetails']->row()->meta_description;
			}
			$this->load->view('site/product/display_user_product',$this->data);
		}else {
			$this->load->view('site/product/product_detail',$this->data);
//			$this->setErrorMessage('error','Product details not available');
	//		redirect(base_url());
		}
	}
	
	public function sales_create(){
		if ($this->checkLogin('U') == ''){
			redirect('login');
		}else {
			$userType = $this->data['userDetails']->row()->group;
			if ($userType == 'Seller'){
				$pid = $this->input->get('ntid');
				$productDetails = $this->product_model->get_all_details(USER_PRODUCTS,array('seller_product_id'=>$pid));
				if ($productDetails->num_rows()==1){
					if ($productDetails->row()->user_id == $this->data['userDetails']->row()->id){
						$this->data['productDetails'] = $productDetails;
						$this->data['editmode'] = '0';
						$this->load->view('site/product/edit_seller_product',$this->data);
					}else {
						show_404();
					}
				}else {
					show_404();
				}
			}else {
				redirect('seller-signup');
			}
		}
	}

	/**
	 * 
	 * Ajax function for delete the product pictures
	 */
	public function editPictureProducts(){
		$ingIDD = $this->input->post('imgId');
		$currentPage = $this->input->post('cpage');
		$id = $this->input->post('val');
		$productImage = explode(',',$this->session->userdata('product_image_'.$ingIDD));
		if(count($productImage) < 2) {
			echo json_encode("No");exit();
		} else {
			$empImg = 0;
			foreach ($productImage as $product) {
				if ($product != ''){
					$empImg++;
				}
			}
			if ($empImg<2){
				echo json_encode("No");exit();
			}
			$this->session->unset_userdata('product_image_'.$ingIDD);
			$resultVar = $this->setPictureProducts($productImage,$this->input->post('position'));
			$insertArrayItems = trim(implode(',',$resultVar)); //need validation here...because the array key changed here
			
			$this->session->set_userdata(array('product_image_'.$ingIDD => $insertArrayItems));	
			$dataArr = array('image' => $insertArrayItems);
			$condition = array('id' => $ingIDD);
			$this->product_model->update_details(PRODUCT,$dataArr,$condition);
			echo json_encode($insertArrayItems);
		}
	}
	
		public function edit_product(){
			$pid = $this->uri->segment(3);
					$this->data['heading'] =$this->config->item('meta_title').' - Edit product'; 
					$productDetails = $this->product_model->get_all_details(PRODUCT,array('id'=>$pid,'status'=>'Publish'));
					$shipping = $this->seller_model->get_all_details(SHIPPING,array('status'=>'Active'));
					$this->data['shipping'] = $shipping;
					$this->data['productDetails'] = $productDetails;
			$this->load->view('site/product/edit_product',$this->data);
		}
		
		
		public function edit_seller_products()
		{
		
		
			$returnStr['status_code'] = 0;
			$config['encrypt_name'] = TRUE;
			$config['overwrite'] = FALSE;
			$config['allowed_types'] = 'jpg|jpeg|gif|png|bmp';
			$config['upload_path'] = './images/product';
			$this->load->library('upload', $config);
			if ( $this->upload->do_multi_upload('product_image')){
			
					$imgDetails = $this->upload->get_multi_upload_data();

                           foreach ($imgDetails as $fileDetails){
	   						 	$returnStr['image']['width'] = $fileDetails['image_width'];
	    						$returnStr['image']['height'] = $fileDetails['image_height'];
	    						$returnStr['image']['name'] = $fileDetails['file_name'];
	    						$this->imageResizeWithSpace(650, 360, $fileDetails['file_name'], './images/product/');
								@copy('./images/product/'.$fileDetails['file_name'], './images/product/thumb/'.$fileDetails['file_name']);
								$this->imageResizeWithSpace(280, 206, $fileDetails['file_name'], './images/product/thumb/');
								   $ImageName .= $fileDetails['file_name'].',';
								}
	    					
							$returnStr['status_code'] = 1;
								
								}else{
						    			$this->setErrorMessage('error','Choose file to upload ');
    									redirect(base_url().'add');
								}
				
		$product_name =  $this->input->post('product_name');
		$product_id =  $this->input->post('product_id');
	
		$product_featured = $this->input->post('product_featured');
		$price = $this->input->post('price');
		$sale_price = $this->input->post('sale_price');
		$quantity = $this->input->post('quantity');
		$max_quantity = $this->input->post('max_quantity');
		$shipMethod = $this->input->post('shipMethod');
		$category1 =  $this->input->post('category1');
		$category2 =  $this->input->post('category2');
		$category3 =  $this->input->post('category3');
		$store1 = $this->input->post('store1');
		$store2 = $this->input->post('store2');
		$store3 = $this->input->post('store3');
		$description = $this->input->post('description');
		$shipping = $this->input->post('shipping');
		$materials = $this->input->post('materials');
		$pre_shipping = $this->input->post('pre_shipping');
		$tag = $this->input->post('amounts');
		$meta_title = $this->input->post('meta_title');
		$meta_keyword = $this->input->post('meta_keyword');
		$product_meta_desc = $this->input->post('product_meta_desc');

		$category_id = $category1.",".$category2.",".$category3;
		$store_id = $store1.",".$store2.",".$store3;
		$image	= $ImageName;
		$condition = array('id'=>$product_id);
			$seourlBase = $seourl = url_title($product_name, '-', TRUE);
			$seourl_check = '0';
			$duplicate_url = $this->product_model->get_all_details(PRODUCT,array('seourl'=>$seourl));
			if ($duplicate_url->num_rows()>0){
				$seourl = $seourlBase.'-'.$duplicate_url->num_rows();
			}else {
				$seourl_check = '1';
			}
			$urlCount = $duplicate_url->num_rows();
			while ($seourl_check == '0'){
				$urlCount++;
				$duplicate_url = $this->product_model->get_all_details(PRODUCT,array('seourl'=>$seourl));
				if ($duplicate_url->num_rows()>0){
					$seourl = $seourlBase.'-'.$urlCount;
				}else {
					$seourl_check = '1';
				}
			}
		$product_seller_id = rand(1111, 999999);
		$dataArr = array('product_name' => $product_name,
					'product_featured' => $product_featured,
					'description' => $description,
					'shipping' => $shipping,
					'price' => $price,
					'sale_price' => $sale_price,
					'quantity' => $quantity,
					'max_quantity' => $max_quantity,
					'image' => $image,
					'category_id' => $category_id,
					'store_id' => $store_id,
					'tag' => $tag,
					'materials' => $materials,
					'shippingType_id' => $shipMethod,
					'ship_immediate' => $pre_shipping,
					'seourl' => $seourl,
					'user_id' => $this->checkLogin('U'),
					'seller_product_id' => $product_seller_id,
					'meta_title' => $meta_title,
					'meta_keyword' => $meta_keyword,
					'meta_description' => $product_meta_desc);		
					
						$this->product_model->edit_product($dataArr,$condition);
						$this->session->set_userdata('added_product_details',$dataArr);	
						
						
						$AttrId = $_POST['product_color'];
						$AttrName = $_POST['product_Colortxt'];
						
						$last_insert_id = $this->db->insert_id();
						
						 for($i=0;$i< sizeof($AttrName);$i++){
							$seourlBase = $seourl[$i] = url_title($AttrName[$i], '-', TRUE);
							$seourl_check = '0';
							$duplicate_url = $this->product_model->get_all_details(PRODUCT,array('seourl'=>$seourl[$i]));
								if ($duplicate_url->num_rows()>0){
									$seourl[$i] = $seourlBase.'-'.$duplicate_url->num_rows();
									}else {
										$seourl_check = '1';
									}
									$urlCount = $duplicate_url->num_rows();
									while ($seourl_check == '0'){
										$urlCount++;
										$duplicate_url = $this->product_model->get_all_details(PRODUCT,array('seourl'=>$seourl[$i]));
									if ($duplicate_url->num_rows()>0){
										$seourl[$i] = $seourlBase.'-'.$urlCount;
									}else {
										$seourl_check = '1';
										}
								} 
						
		$dataArr1 = array('attr_id' => $AttrId[$i],
							'attr_name' => $AttrName[$i],
							'attr_seourl' => $seourl[$i],
							'product_id' => $last_insert_id);
							$this->product_model->add_subproduct_insert($dataArr1);

						}
				echo json_encode($returnStr);
			$this->setErrorMessage('success','Product Added Successfully');
			
				redirect(base_url());
		
		

		
		
		}
		
	public function edit_product_detail(){
	
	
		if ($this->checkLogin('U')==''){
			redirect('login');
		}else {
			$pid = $this->uri->segment(2,0);
			$viewMode = $this->uri->segment(4,0);
			$productDetails = $this->product_model->get_all_details(USER_PRODUCTS,array('seller_product_id'=>$pid));
	

			if ($productDetails->num_rows()==1){
				if ($productDetails->row()->user_id == $this->checkLogin('U')){
					$this->data['productDetails'] = $productDetails;
					$this->load->view('site/product/edit_user_product',$this->data);
				}else {
					show_404();
				}
			}else {
				$productDetails = $this->product_model->get_all_details(PRODUCT,array('seller_product_id'=>$pid));
				$this->data['categoryView'] = $this->product_model->get_category_details($productDetails->row()->category_id);
				$this->data['atrributeValue'] = $this->product_model->view_atrribute_details();
				$this->data['PrdattrVal'] = $this->product_model->view_product_atrribute_details();	
				$this->data['SubPrdVal'] = $this->product_model->view_subproduct_details($productDetails->row()->id);
				if ($productDetails->num_rows()==1){
					if ($productDetails->row()->user_id == $this->checkLogin('U')){
						$this->data['productDetails'] = $productDetails;
						$this->data['editmode'] = '1';
						if ($viewMode == ''){
							$this->load->view('site/product/edit_seller_product',$this->data);
						}else {
							$this->load->view('site/product/edit_seller_product_'.$viewMode,$this->data);
						}
					}else {
						show_404();
					}
				}else {
					show_404();
				}
			}
		}
	}
	
	
	public function edit_user_product_process(){
		$mode = $this->input->post('submit');
		$pid = $this->input->post('productID');
		if ($pid != ''){
			if ($mode == 'Upload'){
				$config['overwrite'] = FALSE;
		    	$config['allowed_types'] = 'jpg|jpeg|gif|png';
//			    $config['max_size'] = 2000;
			    $config['upload_path'] = './images/product';
			    $this->load->library('upload', $config);
				if ( $this->upload->do_upload('uploadphoto')){
			    	$imgDetails = $this->upload->data();
			    	$this->imageResizeWithSpace(650, 360, $imgDetails['file_name'], './images/product/');
					@copy('./images/product/'.$imgDetails['file_name'], './images/product/thumb/'.$imgDetails['file_name']);
					$this->imageResizeWithSpace(280, 206, $imgDetails['file_name'], './images/product/thumb/');
			    	$dataArr['image'] = $imgDetails['file_name'];
			    	$this->product_model->update_details(USER_PRODUCTS,$dataArr,array('seller_product_id'=>$pid));
					$this->setErrorMessage('success','Photo changed successfully');
					echo '<script>window.history.go(-1)</script>';
				}else {
					$this->setErrorMessage('error','Can\'t able to upload');
					echo '<script>window.history.go(-1)</script>';
				}
			}else {
				$excludeArr = array('productID','submit','uploadphoto');
				$dataArr = array(
					'seourl'		=>	url_title($this->input->post('product_name'),'-'),
					'sale_price'	=>	$this->input->post('price') + $this->input->post('product_shipping'),
					'modified'		=>	'now()'
				);
				$this->product_model->commonInsertUpdate(USER_PRODUCTS,'update',$excludeArr,$dataArr,array('seller_product_id'=>$pid));
				$this->setErrorMessage('success','Details updated successfully');
				redirect('user/'.$this->data['userDetails']->row()->user_name.'/things/'.$pid.'/'.url_title($this->input->post('product_name'),'-'));
				//	/*echo '<script>window.history.go(-1)/script>';*/
			}
		}
	}
	
	public function sell_it(){ 
		$mode = $this->uri->segment(4,0);
		$pid = $this->input->post('PID');
		$nextMode = $this->input->post('nextMode');
		$excludeArr = array('PID','nextMode','changeorder','imaged','gateway_tbl_length','category_id','attribute_name','attribute_val','product_attribute_name','product_attribute_val','attr_name1','attr_val1');
		$dataArr = array('seller_product_id'=>$pid);
		$checkProduct = $this->product_model->get_all_details(PRODUCT,$dataArr);
		if ($mode == '1'){
			$price_range = 0;
			$price = $this->input->post('sale_price');
			if ($price>0 && $price<21){
				$price_range = '1-20';
			}else if ($price>20 && $price<101){
				$price_range = '21-100';
			}else if ($price>100 && $price<201){
				$price_range = '101-200';
			}else if ($price>200 && $price<501){
				$price_range = '201-500';
			}else if ($price>500){
				$price_range = '501+';
			}
			
			if ($checkProduct->num_rows()==0){
				$userProduct = $this->product_model->get_all_details(USER_PRODUCTS,$dataArr);
				if ($userProduct->num_rows()==1){
					$dataArr['image']	=	$userProduct->row()->image;
					$dataArr['seourl']	=	url_title($this->input->post('product_name'),'-');
					$dataArr['user_id'] =	$userProduct->row()->user_id;
					$dataArr['price_range'] =	$price_range;
					$dataArr['category_id']	=	$userProduct->row()->category_id;
					$this->product_model->commonInsertUpdate(PRODUCT,'insert',$excludeArr,$dataArr);
					$this->product_model->commonDelete(USER_PRODUCTS,array('seller_product_id'=>$pid));
					$this->setErrorMessage('success','Yeah ! changes have been saved');
					$addedProd = $this->session->userdata('prodID');
					if ($addedProd == ''){
						$addedProd = array();
					}
					array_push($addedProd, $pid);
					$this->session->set_userdata('prodID',$addedProd);
					redirect('things/'.$pid.'/edit/'.$nextMode);
				}
			}else {
				$dataArr['seourl']	=	url_title($this->input->post('product_name'),'-');
				$dataArr['price_range'] =	$price_range;
				$this->product_model->commonInsertUpdate(PRODUCT,'update',$excludeArr,$dataArr,array('seller_product_id'=>$pid));
				$this->setErrorMessage('success','Yeah ! changes have been saved');
				redirect('things/'.$pid.'/edit');
			}
		}else if ($mode == 'seo'){
			$this->product_model->commonInsertUpdate(PRODUCT,'update',$excludeArr,array(),array('seller_product_id'=>$pid));
			$this->setErrorMessage('success','Yeah ! changes have been saved');
			redirect('things/'.$pid.'/edit/'.$nextMode);
		}else if ($mode == 'images'){
			$config['overwrite'] = FALSE;
	    	$config['allowed_types'] = 'jpg|jpeg|gif|png';
//		    $config['max_size'] = 2000;
	    	$config['upload_path'] = './images/product';
		    $this->load->library('upload', $config);
			//echo "<pre>";print_r($_FILES);die;
			$ImageName = '';
		    if ( $this->upload->do_multi_upload('product_image')){
		    	$logoDetails = $this->upload->get_multi_upload_data();
			    foreach ($logoDetails as $fileDetails){
			    	$this->imageResizeWithSpace(650, 360, $fileDetails['file_name'], './images/product/');
					@copy('./images/product/'.$fileDetails['file_name'], './images/product/thumb/'.$fileDetails['file_name']);
					$this->imageResizeWithSpace(280, 206, $fileDetails['file_name'], './images/product/thumb/');
		    		$ImageName .= $fileDetails['file_name'].',';
		    	}
			}
			$existingImage = $this->input->post('imaged');
		 
			$newPOsitionArr = $this->input->post('changeorder');
			$imagePOsit = array();
			 
			for($p=0;$p<sizeof($existingImage);$p++) {
				$imagePOsit[$newPOsitionArr[$p]] = $existingImage[$p];
			}
	
			ksort($imagePOsit);
			foreach ($imagePOsit as $keysss => $vald) {
			 $imgArraypos[]=$vald;
			}
			$imagArraypo0 = @implode(",",$imgArraypos);
			$allImages = $imagArraypo0.','.$ImageName;
			
			$dataArr = array( 'image' => $allImages);
			$this->product_model->update_details(PRODUCT,$dataArr,array('seller_product_id'=>$pid));
			$this->setErrorMessage('success','Yeah ! changes have been saved');
			redirect('things/'.$pid.'/edit/'.$nextMode);
		}else if ($mode == 'categories'){
			if ($this->input->post('category_id') != ''){
				$category_id = implode(',', $this->input->post('category_id'));
			}else {
				$category_id = '';
			}
			$dataArr = array( 'category_id' => $category_id);
			$this->product_model->update_details(PRODUCT,$dataArr,array('seller_product_id'=>$pid));
			$this->setErrorMessage('success','Yeah ! changes have been saved');
			redirect('things/'.$pid.'/edit/'.$nextMode);
		}else if ($mode == 'list') {
			$list_name_str = $list_val_str = '';
			$list_name_arr = $this->input->post('attribute_name');
			$list_val_arr = $this->input->post('attribute_val');
			if (is_array($list_name_arr) && count($list_name_arr)>0){
				$list_name_str = implode(',', $list_name_arr);
				$list_val_str = implode(',', $list_val_arr);
			}
			$dataArr = array( 'list_name' => $list_name_str,'list_value'=>$list_val_str);
			$this->product_model->update_details(PRODUCT,$dataArr,array('seller_product_id'=>$pid));
			
			//Update the list table
			if (is_array($list_val_arr)){
				foreach ($list_val_arr as $list_val_row){
					$list_val_details = $this->product_model->get_all_details(LIST_VALUES,array('id'=>$list_val_row));
					if ($list_val_details->num_rows()==1){
						$product_count = $list_val_details->row()->product_count;
						$products_in_this_list = $list_val_details->row()->products;
						$products_in_this_list_arr = explode(',', $products_in_this_list);
						if (!in_array($pid, $products_in_this_list_arr)){
							array_push($products_in_this_list_arr, $pid);
							$product_count++;
							$list_update_values = array(
								'products'=>implode(',', $products_in_this_list_arr),
								'product_count'=>$product_count
							);
							$list_update_condition = array('id'=>$list_val_row);
							$this->product_model->update_details(LIST_VALUES,$list_update_values,$list_update_condition);
						}
					}
				}
			}
			
			$this->setErrorMessage('success','Yeah ! changes have been saved');
			redirect('things/'.$pid.'/edit/'.$nextMode);
		
		}else if ($mode == 'attribute') {
			
			$prodId = $checkProduct->row()->id;
			$Attr_name_str = $Attr_val_str = '';
			$Attr_name_arr = $this->input->post('product_attribute_name');
			$Attr_val_arr = $this->input->post('product_attribute_val');
			if (is_array($Attr_name_arr) && count($Attr_name_arr)>0){				
				for($k=0;$k<sizeof($Attr_name_arr);$k++){
					$dataSubArr = '';
					$dataSubArr = array('product_id'=> $prodId,'attr_id'=>$Attr_name_arr[$k],'attr_price'=>$Attr_val_arr[$k]);
					//echo '<pre>'; print_r($dataSubArr); 
					$this->product_model->add_subproduct_insert($dataSubArr);
				}
			}
		
			$this->setErrorMessage('success','Yeah ! changes have been saved');
			redirect('things/'.$pid.'/edit/'.$nextMode);
		
		}else {
			show_404();
		}
	}
	
	public function delete_product(){
		$pid = $this->uri->segment(2,0);
		if ($this->checkLogin('U')==''){
			redirect('login');
		}else {
			$productDetails = $this->product_model->get_all_details(USER_PRODUCTS,array('seller_product_id'=>$pid));
			if ($productDetails->num_rows()==1){
				if ($productDetails->row()->user_id == $this->checkLogin('U')){
					$this->product_model->commonDelete(USER_PRODUCTS,array('seller_product_id'=>$pid));
					$productCount = $this->data['userDetails']->row()->products;
					$productCount--;
					$this->product_model->update_details(USERS,array('products'=>$productCount),array('id'=>$this->checkLogin('U')));
					$this->product_model->commonDelete(SUBPRODUCT,array('product_id' => $productDetails->row()->id));
					$this->setErrorMessage('success','Product deleted successfully');
					redirect('user/'.$this->data['userDetails']->row()->user_name.'/added');
				}else {
					show_404();
				}
			}else {
				$productDetails = $this->product_model->get_all_details(PRODUCT,array('seller_product_id'=>$pid));
				if ($productDetails->num_rows()==1){
					if ($productDetails->row()->user_id == $this->checkLogin('U')){
						$this->product_model->commonDelete(PRODUCT,array('seller_product_id'=>$pid));
						$productCount = $this->data['userDetails']->row()->products;
						$productCount--;
						$this->product_model->update_details(USERS,array('products'=>$productCount),array('id'=>$this->checkLogin('U')));
						$this->product_model->commonDelete(SUBPRODUCT,array('product_id' => $productDetails->row()->id));
						$this->setErrorMessage('success','Product deleted successfully');
						redirect('user/'.$this->data['userDetails']->row()->user_name.'/added');
					}else {
						show_404();
					}
				}else {
					show_404();
				}
			}
		}
	}
	
	public function add_reaction_tag(){
		$returnStr['status_code'] = 0;
		if ($this->checkLogin('U') == ''){
			$returnStr['message'] = 'You must login';
		}else {
			$tid = $this->input->post('thing_id');
			$checkProductLike = $this->user_model->get_all_details(PRODUCT_LIKES,array('product_id'=>$tid,'user_id'=>$this->checkLogin('U')));
			if ($checkProductLike->num_rows() == 0){
				$productDetails = $this->user_model->get_all_details(PRODUCT,array('seller_product_id'=>$tid));
				if ($productDetails->num_rows() == 0){
					$productDetails = $this->user_model->get_all_details(USER_PRODUCTS,array('seller_product_id'=>$tid));
					$productTable = USER_PRODUCTS;
				}else {
					$productTable = PRODUCT;
				}
				if ($productDetails->num_rows()==1){
					$likes = $productDetails->row()->likes;
					$dataArr = array('product_id'=>$tid,'user_id'=>$this->checkLogin('U'),'ip'=>$this->input->ip_address());
					$this->user_model->simple_insert(PRODUCT_LIKES,$dataArr);
					$actArr = array(
						'activity_name'	=>	'fancy',
						'activity_id'	=>	$tid,
						'user_id'		=>	$this->checkLogin('U'),
						'activity_ip'	=>	$this->input->ip_address()
					);
					$this->user_model->simple_insert(USER_ACTIVITY,$actArr);
					$likes++;
					$dataArr = array('likes'=>$likes);
					$condition = array('seller_product_id'=>$tid);
					$this->user_model->update_details($productTable,$dataArr,$condition);
					$totalUserLikes = $this->data['userDetails']->row()->likes;
					$totalUserLikes++;
					$this->user_model->update_details(USERS,array('likes'=>$totalUserLikes),array('id'=>$this->checkLogin('U')));
/*
 * -------------------------------------------------------
 * Creating list automatically when user likes a product 
 * -------------------------------------------------------
 *
					$listCheck = $this->user_model->get_list_details($tid,$this->checkLogin('U'));
					if ($listCheck->num_rows() == 0){
						$productCategoriesArr = explode(',', $productDetails->row()->category_id);
						if (count($productCategoriesArr)>0){
							foreach ($productCategoriesArr as $productCategoriesRow){
								if ($productCategoriesRow != ''){
									$productCategory = $this->user_model->get_all_details(CATEGORY,array('id'=>$productCategoriesRow));
									if ($productCategory->num_rows()==1){
										
									}
								}
							}
						}
					}
*/
					$returnStr['status_code'] = 1;
				}else {
					$returnStr['message'] = 'Product not available';
				}
			}else {
				$returnStr['status_code'] = 1;
			}
		}
		echo json_encode($returnStr);	
	
	}
	
	public function delete_reaction_tag(){
		$returnStr['status_code'] = 0;
		if ($this->checkLogin('U') == ''){
			$returnStr['message'] = 'You must login';
		}else {
			$tid = $this->input->post('thing_id');
			$checkProductLike = $this->user_model->get_all_details(PRODUCT_LIKES,array('product_id'=>$tid,'user_id'=>$this->checkLogin('U')));
			if ($checkProductLike->num_rows() == 1){
				$productDetails = $this->user_model->get_all_details(PRODUCT,array('seller_product_id'=>$tid));
				if ($productDetails->num_rows()==0){
					$productDetails = $this->user_model->get_all_details(USER_PRODUCTS,array('seller_product_id'=>$tid));
					$productTable = USER_PRODUCTS;
				}else {
					$productTable = PRODUCT;
				}
				if ($productDetails->num_rows()==1){
					$likes = $productDetails->row()->likes;
					$conditionArr = array('product_id'=>$tid,'user_id'=>$this->checkLogin('U'));
					$this->user_model->commonDelete(PRODUCT_LIKES,$conditionArr);
					$actArr = array(
						'activity_name'	=>	'unfancy',
						'activity_id'	=>	$tid,
						'user_id'		=>	$this->checkLogin('U'),
						'activity_ip'	=>	$this->input->ip_address()
					);
					$this->user_model->simple_insert(USER_ACTIVITY,$actArr);
					$likes--;
					$dataArr = array('likes'=>$likes);
					$condition = array('seller_product_id'=>$tid);
					$this->user_model->update_details($productTable,$dataArr,$condition);
					$totalUserLikes = $this->data['userDetails']->row()->likes;
					$totalUserLikes--;
					$this->user_model->update_details(USERS,array('likes'=>$totalUserLikes),array('id'=>$this->checkLogin('U')));
					$returnStr['status_code'] = 1;
				}else {
					$returnStr['message'] = 'Product not available';
				}
			}else {
				$returnStr['status_code'] = 1;
			}
		}
		echo json_encode($returnStr);	
	}
	
	public function loadListValues(){
		$returnStr['listCnt'] = '<option value="">--Select--</option>';
		$lid = $this->input->post('lid');
		$lvID = $this->input->post('lvID');
		if ($lid != ''){
			$listValues = $this->product_model->get_all_details(LIST_VALUES,array('list_id'=>$lid));
			if ($listValues->num_rows()>0){
				foreach ($listValues->result() as $listRow){
					$selStr = '';
					if ($listRow->id == $lvID){
						$selStr = 'selected="selected"';
					}
					$returnStr['listCnt'] .= '<option '.$selStr.' value="'.$listRow->id.'">'.$listRow->list_value.'</option>';
				}
			}
		}
		echo json_encode($returnStr);
	}
	
	public function approve_comment(){
		$returnStr['status_code'] = 0;
		if ($this->checkLogin('U')!=''){
			$cid = $this->input->post('cid');
			$this->product_model->update_details(PRODUCT_COMMENTS,array('status'=>'Active'),array('id'=>$cid));
			$datestring = "%Y-%m-%d %h:%i:%s";
			$time = time();
			$createdTime = mdate($datestring,$time);
			$product_id = $this->input->post('tid');
			$user_id = $this->input->post('uid');
			$this->product_model->commonDelete(NOTIFICATIONS,array('comment_id'=>$cid));
			$actArr = array(
				'activity'		=>	'comment',
				'activity_id'	=>	$product_id,
				'user_id'		=>	$user_id,
				'activity_ip'	=>	$this->input->ip_address(),
				'comment_id'	=>	$cid,
				'created'		=>	$createdTime
			);
			$this->product_model->simple_insert(NOTIFICATIONS,$actArr);
			$this->send_comment_noty_mail($product_id,$cid);
			$returnStr['status_code'] = 1;
		}
		echo json_encode($returnStr);
	}
	
	public function delete_comment(){
		$returnStr['status_code'] = 0;
		if ($this->checkLogin('U')!=''){
			$cid = $this->input->post('cid');
			$this->product_model->commonDelete(PRODUCT_COMMENTS,array('id'=>$cid));
			$returnStr['status_code'] = 1;
		}
		echo json_encode($returnStr);
	}
	
	public function send_feature_noty_mail($pid='0'){
		if ($pid!= '0'){
			$productUserDetails = $this->product_model->get_product_full_details($pid);
			if ($productUserDetails->num_rows()>0){
				$emailNoty = explode(',', $productUserDetails->row()->email_notifications);
				if (in_array('featured', $emailNoty)){
					if ($productUserDetails->prodmode == 'seller'){
						$prodLink = base_url().'things/'.$productUserDetails->row()->id.'/'.url_title($productUserDetails->row()->product_name,'-');
					}else {
						$prodLink = base_url().'user/'.$productUserDetails->row()->user_name.'/things/'.$productUserDetails->row()->seller_product_id.'/'.url_title($productUserDetails->row()->product_name,'-');
					}
                    
                    $newsid='10';
		  		$template_values=$this->product_model->get_newsletter_template_details($newsid);
		$adminnewstemplateArr=array('logo'=> $this->data['logo'],'meta_title'=>$this->config->item('meta_title'),'full_name'=>$productUserDetails->row()->full_name,'cfull_name'=>$this->data['userDetails']->row()->full_name,'product_name'=>$productUserDetails->row()->product_name,'user_name'=>$this->data['userDetails']->row()->user_name);
        extract($adminnewstemplateArr);
		$subject = 'From: '.$this->config->item('email_title').' - '.$template_values['news_subject'];
  		$message .= '<!DOCTYPE HTML>
			<html>
			<head>
			<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
			<meta name="viewport" content="width=device-width"/>
			<title>'.$template_values['news_subject'].'</title><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'=>$productUserDetails->row()->email,
										'subject_message'=>$subject,
										'body_messages'=>$message
										);
					$email_send_to_common = $this->product_model->common_email_send($email_values);
				}
			}
		}
	}
	
	public function contactform(){
	
		$dataArrVal = array();
		foreach($this->input->post() as $key => $val){
				$dataArrVal[$key] = trim(addslashes($val));
		}
		
		$this->product_model->contact_seller_add($dataArrVal);
		//$contact_id = $this->product_model->get_last_insert_id();
		$this->data['productVal'] = $this->product_model->get_all_details(PRODUCT,array( 'id' => $this->input->post('product_id')));
		
		
		$newimages = @explode(',',$this->data['productVal']->row()->image);				
		
		$newsid='11';
		$template_values=$this->product_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'],
							'name'=>$this->input->post('name'),
							'question'=>$this->input->post('question'),
							'email'=>$this->input->post('selleremail'),
							'phone'=>$this->input->post('phone'),
							'productId'=>$this->data['productVal']->row()->id,
							'productName'=>$this->data['productVal']->row()->product_name,
							'productSeourl'=>$this->data['productVal']->row()->seourl,
							'productImage'=>$newimages[0],
							);
		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'=>$this->input->post('email'),
							'cc_mail_id'=>$this->config->item('site_contact_mail'),
							'subject_message'=>$template_values['news_subject'],
							'body_messages'=>$message
							);

		$email_send_to_common = $this->product_model->common_email_send($email_values);
		$this->setErrorMessage('success','Contact Seller Successfully!');		
		echo 'Success';
	
	}

	public function usercontactform(){
	
		$dataArrVal = array();
		foreach($this->input->post() as $key => $val){
				$dataArrVal[$key] = trim(addslashes($val));
		}
		
		$this->product_model->contact_user_add($dataArrVal);
		//$contact_id = $this->product_model->get_last_insert_id();
		$this->data['productVal'] = $this->product_model->get_all_details(USER_PRODUCTS,array( 'id' => $this->input->post('product_id')));
		
		
		$newimages = @explode(',',$this->data['productVal']->row()->image);				
		
		$newsid='11';
		$template_values=$this->product_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'],
							'name'=>$this->input->post('name'),
							'question'=>$this->input->post('question'),
							'email'=>$this->input->post('selleremail'),
							'phone'=>$this->input->post('phone'),
							'productId'=>$this->data['productVal']->row()->id,
							'productName'=>$this->data['productVal']->row()->product_name,
							'productSeourl'=>$this->data['productVal']->row()->seourl,
							'productImage'=>$newimages[0],
							);
		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'=>$this->input->post('email'),
							'cc_mail_id'=>$this->config->item('site_contact_mail'),
							'subject_message'=>$template_values['news_subject'],
							'body_messages'=>$message
							);
			
		//echo '<pre>'; print_r($email_values); die;
		$email_send_to_common = $this->product_model->common_email_send($email_values);
		$this->setErrorMessage('success','Contact Seller Successfully!');		
		echo 'Success';
	
	}
	
	
	
	
	
	
	
	
	
	
	 // Cat search
	
	public function cat_view(){
		 $catid_id = $this->uri->segment(2, 0); 
		 
		 
		 //$cat_idname = $this->uri->segment(3, 0); 
		// echo $cat_id; die;
		 $seller_idexplopde = @explode('-',$catid_id);
		 
		 $cat_id = $seller_idexplopde[0];
		// print_r($cat_id); die;
		//$cat_idnameexplopde = @explode('-',$cat_idname);

		//$cat_id = $cat_idnameexplopde[0];
		
		//echo $cat_id; die;
		// $this->data['userVal'] = $this->seller_model->get_userselldetail_data('shop_template,seller_businessname,seller_firstname,seller_id',$seller_id);
		// $this->data['userpersonalVal'] = $this->seller_model->get_userdetail_datastore('full_name,city,thumbnail',$seller_id);
		
		//echo $this->db->last_query(); die;
		
		    $searchPerPage = 10;
		    $paginationNo = $this->uri->segment('2');  
	     
			if($paginationNo == '')
			{
					$paginationNo = 0;
			}
			else
			{
					$paginationNo = $paginationNo;
			}
			
		$this->data['productVal'] = $this->product_model->get_categorydetail_view('id,seourl,product_name,sale_price,image,product_featured,user_id',$cat_id,$searchPerPage,$paginationNo);
		
		$this->data['catVal'] = $catVal = $this->product_model->view_cat_details($cat_id);
		/*echo $this->db->last_query(); die;
		echo $catVal; die;*/
		//echo $this->data['catVal'][0]['cat_name']; die;
	    /* print_r($this->data['catVal']); die;
		echo "<pre>";print_r($this->data['catVal']->result_array()); die;*/
		
		$searchbaseUrl = base_url().$this->uri->segment('1').'/';
			$product_routes_name = $this->uri->segment(); 
			$config['prev_link'] = '<img src="images/page_prevt_hover.png" />';
			$config['num_links'] = 3;
			$config['display_pages'] = TRUE; 
			$config['next_link'] = '<img src="images/page_next.png" />';
			$config['base_url'] = $searchbaseUrl;
			$config['total_rows'] = count($blogTotal); 
			$config["per_page"] = $searchPerPage;
			$config["uri_segment"] = 2;
			$config['first_link'] = '';
			$config['last_link'] = '';
			$this->pagination->initialize($config); 
			 $paginationLink = $this->pagination->create_links(); 
			$this->data['paginationLink'] = $paginationLink;
			
			$this->data['heading'] = $this->data['catVal'][0]['cat_name'];
			$this->data['meta_title'] = $this->data['catVal'][0]['seo_title'];
			$this->data['meta_keyword'] = $this->data['catVal'][0]['seo_keyword'];
			$this->data['meta_description'] = $this->data['catVal'][0]['seo_description'];
			
		/*echo '<pre>';
		print_r($this->data['productVal']); die;*/
		$this->load->view('site/shop/catproduct_view.php',$this->data);
			
	}	
	
	
	
	
	
	
	
	
	
	
	

	public function send_comment_noty_mail($pid='0',$cid='0'){
		if ($pid!= '0' && $cid != '0'){
			$likeUserList = $this->product_model->get_like_user_full_details($pid);
			if ($likeUserList->num_rows()>0){
				$productUserDetails = $this->product_model->get_product_full_details($pid);
				$commentDetails = $this->product_model->view_product_comments_details('where c.id='.$cid);
				if ($productUserDetails->num_rows()>0 && $commentDetails->num_rows()==1){
					foreach ($likeUserList->result() as $likeUserListRow){
						$emailNoty = explode(',', $likeUserListRow->email_notifications);
						if (in_array('comments_on_fancyd', $emailNoty)){
							if ($productUserDetails->prodmode == 'seller'){
								$prodLink = base_url().'things/'.$productUserDetails->row()->id.'/'.url_title($productUserDetails->row()->product_name,'-');
							}else {
								$prodLink = base_url().'user/'.$productUserDetails->row()->user_name.'/things/'.$productUserDetails->row()->seller_product_id.'/'.url_title($productUserDetails->row()->product_name,'-');
							}
                            
                            $newsid='8';
                            $template_values=$this->product_model->get_newsletter_template_details($newsid);
                            $adminnewstemplateArr=array('logo'=> $this->data['logo'],'meta_title'=>$this->config->item('meta_title'),'full_name'=>$likeUserListRow->full_name,'cfull_name'=>$commentDetails->row()->full_name,'user_name'=>$commentDetails->row()->user_name,'product_name'=>$productUserDetails->row()->product_name);
                            extract($adminnewstemplateArr);
                            $subject = 'From: '.$this->config->item('email_title').' - '.$template_values['news_subject'];
                            $message = '<!DOCTYPE HTML>
                                <html>
                                <head>
                                <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
                                <meta name="viewport" content="width=device-width"/>
                                <title>'.$template_values['news_subject'].'</title><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'=>$likeUserListRow->email,
												'subject_message'=>$subject,
												'body_messages'=>$message
												);
							$email_send_to_common = $this->product_model->common_email_send($email_values);
						}
					}
				}
			}
		}
	}
/* Ajax select for levl 1 subcategorty from add shop list items */
	public function select_ajax_level1_subcategory(){
	  
	  
		$selectSubcatval = $this->product_model->get_all_details(CATEGORY,array('rootID'=>$this->input->get('main_cat_id'),'status'=> 'Active'));
		if($selectSubcatval->num_rows() > 0){
		 echo '<option value="">Select a category</option>';
		 foreach($selectSubcatval->result() as $MaincatValues) {
			 
         echo '<option value="'.$MaincatValues->id.'">'.$MaincatValues->cat_name.'</option>'; 
		 } } else {
		 
		 echo 'Nocat';}
		
	}
	
	/* Ajax select for level 2 subcategorty from add shop list items */
	/*public function select_ajax_level2_subcategory(){
		
	    for($i=0; $i<500000; $i++)
		{
			echo $i;
		}
		
		$selectSubcatval = $this->product_model->get_all_details(CATEGORY,array('rootID'=>$this->input->get('level1_sub_cat'),'status'=> 'Active'));
		
		 echo '<option>Select a category</option>';
		 foreach($selectSubcatval->result() as $MaincatValues) {
			 
                                echo '<option value="'.$MaincatValues->id.'">'.$MaincatValues->cat_name.'</option>'; 
		 }
		
	}*/
	
	
	public function select_ajax_attr_options(){
		
		
		//echo $this->input->get('property_level'); die;
		              $select_attr_val = $this->product_model->get_all_details(PRODUCT_ATTRIBUTE,array('attr_name' => $this->input->get('property_level'),'status'=> 'Active'));
                      $optionsVal=explode(',',$select_attr_val->row()->attr_options);
					  
					 // echo '<form >';
				      if(!empty($select_attr_val->row()->attr_options)){
				  
				        echo '<select id="attr_options" onchange="return alpha_check(this);">';
				        echo '<option value="">Select available options...</option>';
		                foreach($optionsVal as $variations) {
		        	                           echo '<option>'.$variations.'</option>';
											    }
                                
                           echo  '</optgroup>
                            <!--<optgroup label="Could not find a property">
                                <option >Add a new option</option>
                            </optgroup>--> </select>';
							
							if($select_attr_val->row()->scaling_option == 'Yes')
							{
								echo '<div style="display:none;" id="add_textbox_button"><br><br><span class="opition-offer">Enter the options you offer. </span>';
			echo '<input id="option_value" type="text"  style="float:left; width:120px; height:10px;  font-size:12px; color:#333; padding:5px 6px;"/><input type="button" class="add_button" value="Add" onclick="return add_options_with_scal();"/></div>';
								echo '<script>$("#have_scalling").html("Yes");</script>';	
							}
							else
							{		
								echo '<script>$("#have_scalling").html("No");</script>';	  
							}
				  
				   } else {
					   echo '<div id="add_textbox_button"><br><br><span class="opition-offer" >Enter the options you offer. </span>';
		   echo '<input id="option_value" type="text"  style="float:left; width:120px; height:10px;  font-size:12px; color:#333; padding:5px 6px;"/><input type="button" class="add_button" value="Add" onclick="return add_options_without_scale();"/></div>';
                          
				  }
	}
	
	
	
	public function select_ajax_attr_options1(){
				  
				  $select_attr_val = $this->product_model->get_all_details(PRODUCT_ATTRIBUTE,array('attr_name' => $this->input->get('property_level1'),'status'=> 'Active'));
                      $optionsVal=explode(',',$select_attr_val->row()->attr_options);
					  
					  //echo '<form >';
				      if(!empty($select_attr_val->row()->attr_options)){
				  
				        echo '<select id="attr_options1" onchange="return alpha_check1(this);">';
				        echo '<option value="">Select available options...</option>';
		                foreach($optionsVal as $variations) {
		        	                           echo '<option>'.$variations.'</option>';
											    }
                                
                           echo  '</optgroup>
                            <!--<optgroup label="Could not find a property">
                                <option >Add a new option</option>
                            </optgroup>--> </select>';
							
							if($select_attr_val->row()->scaling_option == 'Yes')
							{
								echo '<div style="display:none;" id="add_textbox_button1"><br><br><span class="opition-offer" >Enter the options you offer. </span>';
			echo '<input id="option_value1" type="text"  style="float:left; width:120px; height:10px;  font-size:12px; color:#333; padding:5px 6px;"/><input type="button" class="add_button" value="Add" onclick="return add_options_with_scal1();"/></div>'; //</form>
								echo '<script>$("#have_scalling1").html("Yes");</script>';	
							}
							else
							{		
								echo '<script>$("#have_scalling1").html("No");</script>';	  
							}
				  
				   } else {
					   echo '<div id="add_textbox_button1"><br><br><span class="opition-offer" >Enter the options you offer. </span>';
		   echo '<input id="option_value1" type="text"  style="float:left; width:120px; height:10px;  font-size:12px; color:#333; padding:5px 6px;"/><input type="button" class="add_button" value="Add" onclick="return add_options_without_scale1();"/></div>'; //</form>
                          
				  }
	}
	
	
	
	
	public function ajax_load_images(){
		
			list($w, $h) = getimagesize($_FILES["image_upload"]["tmp_name"]);
			if($w > 500 && $h > 320){
			
				$path = "images/product/temp_img/"; 
				$imgRnew = @explode('.',$_FILES["image_upload"]["name"]);
			    $NewImg = url_title($imgRnew[0], '-', TRUE);
		    	$ImgTmpName = $NewImg.'.'.$imgRnew[1];
			
				if($ImgTmpName != ''){
			 		move_uploaded_file($_FILES["image_upload"]["tmp_name"], $path.$ImgTmpName);
					echo 'Success|'.$path.$ImgTmpName;
		   		}
			}else{
				echo 'Failure|Upload Image Too Small. Please Upload Image Size More than or Equalto 550 X 350 .';
			}
				
	}
	
	
	
	public function ajax_load_images1(){
		   list($w, $h) = getimagesize($_FILES["image_upload1"]["tmp_name"]);
			if($w > 500 && $h > 320){
			
				$path = "images/product/temp_img/"; 
				$imgRnew = @explode('.',$_FILES["image_upload1"]["name"]);
				$NewImg = url_title($imgRnew[0], '-', TRUE);
				$ImgTmpName = $NewImg.'.'.$imgRnew[1];
				if($ImgTmpName != ''){
					move_uploaded_file($_FILES["image_upload1"]["tmp_name"], $path.$ImgTmpName);
					echo 'Success|'.$path.$ImgTmpName;
			   }
			}else{
				echo 'Failure|Upload Image Too Small. Please Upload Image Size More than or Equalto 550 X 350 .';
			}				   
	}
	
	
	public function ajax_load_images2(){
		 list($w, $h) = getimagesize($_FILES["image_upload2"]["tmp_name"]);
			if($w > 500 && $h > 320){
			
				$path = "images/product/temp_img/"; 
				$imgRnew = @explode('.',$_FILES["image_upload2"]["name"]);
				$NewImg = url_title($imgRnew[0], '-', TRUE);
				$ImgTmpName = $NewImg.'.'.$imgRnew[1];
				if($ImgTmpName != ''){
					move_uploaded_file($_FILES["image_upload2"]["tmp_name"], $path.$ImgTmpName);
					echo 'Success|'.$path.$ImgTmpName;
			   }
			}else{
				echo 'Failure|Upload Image Too Small. Please Upload Image Size More than or Equalto 550 X 350 .';
			}	
	}
	
	public function ajax_load_images3(){
		   list($w, $h) = getimagesize($_FILES["image_upload3"]["tmp_name"]);
			if($w > 500 && $h > 320){
			
				$path = "images/product/temp_img/"; 
				$imgRnew = @explode('.',$_FILES["image_upload3"]["name"]);
				$NewImg = url_title($imgRnew[0], '-', TRUE);
				$ImgTmpName = $NewImg.'.'.$imgRnew[1];
				if($ImgTmpName != ''){
					move_uploaded_file($_FILES["image_upload3"]["tmp_name"], $path.$ImgTmpName);
					echo 'Success|'.$path.$ImgTmpName;
			   }  
			}else{
				echo 'Failure|Upload Image Too Small. Please Upload Image Size More than or Equalto 550 X 350 .';
			}	
		
	}
	
	public function ajax_load_images4(){
		    list($w, $h) = getimagesize($_FILES["image_upload4"]["tmp_name"]);
			if($w > 500 && $h > 320){
			
				$path = "images/product/temp_img/"; 
				$imgRnew = @explode('.',$_FILES["image_upload4"]["name"]);
				$NewImg = url_title($imgRnew[0], '-', TRUE);
				$ImgTmpName = $NewImg.'.'.$imgRnew[1];
				if($ImgTmpName != ''){
					move_uploaded_file($_FILES["image_upload4"]["tmp_name"], $path.$ImgTmpName);
					echo 'Success|'.$path.$ImgTmpName;
			   }
			 }else{
				echo 'Failure|Upload Image Too Small. Please Upload Image Size More than or Equalto 550 X 350 .';
			}	
	}
	
	
	
	public function load_ajax_options_table($option_val,$scale,$status)
	{
		$idval=time();   if($scale == 'No'){ $scale='';}
		          echo ' <tr>
                            <td width="20%">'.$option_val.'&nbsp;<input type="hidden" value="'.$option_val.'" name="variation_value[]"/><span class=scale_change>'.$scale.'</span><input type="hidden" class="scale_change_txt" value="'.$scale.'" name="variation_scale1"/></td>
                            <td width="20%"><span class="price_box" style="display:'.$status.';">$&nbsp;<input type="text" name="pricing[]" style="width:70px;" class="priceingbox"></span>&nbsp;</td>
                            <td width="20%"><input type="checkbox"  id="'.$idval.'" class="stock"  onchange="return stock_check(this);" checked="checked"><input type="hidden" name="listing_variation[]" id="stock_opt_'.$idval.'" value="1"></td>
                             <td width="10%"><a href="javascript:void(0)"  class="close_icon"></a></td>
                        </tr>'; 
	}
	
	
	
	public function load_ajax_options_table1($option_val,$scale)
	{
		$idval1=time();
		          echo ' <tr>
                            <td width="20%">'.$option_val.'&nbsp;<input type="hidden" value="'.$option_val.'" name="variation_value1[]"/><span class=scale_change1>'.$scale.'</span><input type="hidden" class="scale_change_txt1" value="'.$scale.'" name="variation_scale2"/></td>
                            <td width="20%"><span class="price_box1" style="display:none">$&nbsp;<input type="text" name="pricing1[]" style="width:70px;" class="priceingbox1"></span>&nbsp;</td>
                            <td width="20%"><input type="checkbox" name="listing_variation1[]" id="'.$idval1.'" class="stock" value="1" onchange="return stock_check(this);" checked="checked"><input type="hidden" name="listing_variation1[]" id="stock_opt_'.$idval1.'" value="1"></td>
                             <td width="10%"><a href="javascript:void(0)"  class="close_icon1"></a></td>
                        </tr>'; 
	}
	
	
	public function load_ajax_options_table_noScale($option_val,$status)
	{
				//echo strlen($scale); die;  
				  if(strlen($option_val) > 0)
				  {
				         $idval=time();
		          echo ' <tr>
                            <td width="20%">'.$option_val.'&nbsp;<input type="hidden" value="'.$option_val.'" name="variation_value[]"/></td>
                            <td width="20%"><span class="price_box" style="display:'.$status.';">$&nbsp;<input type="text" name="pricing[]" style="width:70px;" class="priceingbox"></span>&nbsp;</td>
                            <td width="20%"><input type="checkbox"  id="'.$idval.'" class="stock"  onchange="return stock_check(this);" checked="checked"><input type="hidden" name="listing_variation[]" id="stock_opt_'.$idval.'" value="1"></td>
                             <td width="10%"><a href="javascript:void(0)"  class="close_icon"></a></td>
                        </tr>'; 
				  }
	}
	
	
   public function load_ajax_options_table_noScale1($option_val,$status)
	{
				//echo strlen($scale); die;  
				  if(strlen($option_val) > 0)
				  {
				          $idval=time();
		          echo ' <tr>
                            <td width="20%">'.$option_val.'&nbsp;<input type="hidden" value="'.$option_val.'" name="variation_value1[]"/></td>
                            <td width="20%"><span class="price_box1" style="display:none">$&nbsp;<input type="text" name="pricing[]" style="width:70px;" class="priceingbox1"></span>&nbsp;</td>
                            <td width="20%"><input type="checkbox"  id="'.$idval.'" class="stock"  onchange="return stock_check(this);" checked="checked"><input type="hidden" name="listing_variation1[]" id="stock_opt_'.$idval.'" value="1"></td>
                             <td width="10%"><a href="javascript:void(0)"  class="close_icon"></a></td>
                        </tr>'; 
				  }
	}
	public function load_ajax_options_div()
	{
				/*echo '<div style="float:right;">
						<a href="javascript:void(0)" onclick="return clear_data();" id="close_var_one" class="close_icon" style="display:none;"></a>
					</div>
					<div class="list_inner_right list_small_width" id="attr_loader" style="display:none">
						<img src="images/ajax_loading.gif" alt="loading variations" />
					</div>
					<div class="list_inner_right list_small_width" id="options_level" name="options_level" style="display:none"></div>
					<div class="list_inner_right list_small_width" id="attr_options_val" name="attr_options_val" style="display:none">
								<select onchange="return alpha_check(this);" id="checked_alpha_value" class="alpha_value_one">
										<option value="">Select available options...</option>
									 	<option>XXS</option>
									 	<option>XS</option>
									 	<option>S</option>
									 	<option>M</option>
									 	<option>L</option>
									 	<option>XL</option>
									 	<option>XXL</option> 
									 	<option>3XL</option>
                                    	<option>4XL</option>
                                    	<option>5XL</option>                               
                                    	<!--<optgroup label="Could not find a property">
                                        	<option >Add a new option</option>
                                    	</optgroup>-->
                                </select>
                            </div>
                            <div class="list_inner_fields" style="border-bottom:none;">
                                <label>&nbsp;</label> 
                                <div class="list_inner_right" id="options_table" style="display:none">
								<center><img src="images/ajax-loader/ajax-loader(14).gif" alt="Adding variations" style="display:none;" id="variation_add_loading1" /></center><br />
                                    <table width="100%" class="inner_table"  align="center" cellpadding="0" cellspacing="0" id="options_list">              
                                  <tbody>
                                    <tr>
                                       <td width="40%" ><strong>Options</strong></td>
                                       <td width="25%">
                                            <span class="non-pricing-mode">
                                                <a href="javascript:void(0)" class="enable-variations-pricing" id="price_opt"  onclick="price_opt_click();">Add Pricing</a>
                                            </span>
                                            <span class="pricing-mode retail">
                                                <a href="#variations-section" class="disable-variations-pricing remove button-remove"></a>
                                                   <!--<span class="price-header-label retail">
                                                          Price
                                                    <small>USD</small>
                                                </span>-->
                                            </span>
                                        </td>
                                       <td  width="25%" ><strong>In Stock</strong></td>
                                       <td  width="10%" ></td>
                                    </tr>
                                </tbody>
                                </table>
                                </div>   
                            </div> ';*/
							
							
							
			echo '<div style="float:right;">
                            	<a href="javascript:void(0)" onclick="return clear_data();" id="close_var_one" style="display:none;" class="close_icon"></a>
                            </div>
                            <div class="list_inner_right list_small_width" id="attr_loader" style="display:none"><img src="images/ajax_loading.gif" alt="loading variations" /></div>
                            <div class="list_inner_right list_small_width" id="options_level" name="options_level" style="display:none"></div>
                            <div class="list_inner_right list_small_width" id="attr_options_val" name="attr_options_val" style="display:none">
                                <select onchange="return alpha_check(this);" id="checked_alpha_value" class="alpha_value_one">
                                    <option value="">';if($this->lang->line('shop_selavailableoptions') != '') { echo stripslashes($this->lang->line('shop_selavailableoptions')); } else echo 'Select available options'; echo '...</option>
                                    <option>XXS</option>
                                    <option>XS</option>
                                    <option>S</option>
                                    <option>M</option>
                                    <option>L</option>
                                    <option>XL</option>
                                    <option>XXL</option>
                                    <option>3XL</option>
                                    <option>4XL</option>
                                    <option>5XL</option>                               
                                    <!--<optgroup label="Couldnt find a property">
                                        <option >Add a new option</option>
                                    </optgroup>-->
                                </select>
                            </div>
                            <div class="list_inner_fields" style="border-bottom:none;">
                                <label>&nbsp;</label> 
                                
                                <div class="list_inner_right" id="options_table" style="display:none">
                                <center><img src="images/ajax-loader/ajax-loader(14).gif" alt="Adding variations" style="display:none;" id="variation_add_loading1" /></center><br />

                                	<table width="100%" class="inner_table"  align="center" cellpadding="0" cellspacing="0" id="options_list">              
                                        <tbody>
                                            <tr style="background:#E9F6FC;; margin: 0px; padding: 9px 0px 0px;">
                                               <td width="20%" ><strong>';if($this->lang->line('shop_options') != '') { echo stripslashes($this->lang->line('shop_options')); } else echo 'Options'; echo '</strong></td>
                                               <td width="20%">
                                                    <span class="non-pricing-mode">
                                                        <a href="javascript:void(0)" class="enable-variations-pricing" id="price_opt" onclick="price_opt_click();">';if($this->lang->line('shop_addpricing') != '') { echo stripslashes($this->lang->line('shop_addpricing')); } else echo 'Add Pricing';echo '</a>
                                                    </span>
                                                    <span class="pricing-mode retail">
                                                        <a href="#variations-section" class="disable-variations-pricing remove button-remove"></a>
                                                           <!--<span class="price-header-label retail">
                                                                  Price
                                                            <small>USD</small>
                                                        </span>-->
                                                    </span>
                                                </td>
                                               <td  width="20%" ><strong>';if($this->lang->line('shop_instock') != '') { echo stripslashes($this->lang->line('shop_instock')); } else echo 'In Stock'; echo '</strong></td>
                                               <td  width="10%" ></td>
                                            </tr>
                                        </tbody>
                                	</table>
                                </div>   
                            </div> ';				
	}
	
	public function load_ajax_options_div1()
	{
				/*echo '<div style="float:right;">
                              	<a href="javascript:void(0)" onclick="return clear_data1();" id="close_var_two" style="display:none;" class="close_icon"></a>
                             </div>
                             <div class="list_inner_right list_small_width" id="attr_loader1" style="display:none">
                              	<img src="images/ajax_loading.gif" alt="loading variations" />
                             </div>
                             <div class="list_inner_right list_small_width" id="options_level1" name="options_level1" style="display:none"></div>
                             <div class="list_inner_right list_small_width" id="attr_options_val1" name="attr_options_val1" style="display:none">
                                    <select onchange="return alpha_check1(this);" id="checked_alpha_value1" class="alpha_value_two">
                                        <option value="">Select available options...</option>
                                        <option>XXS</option>
                                        <option>XS</option>
                                        <option>S</option>
                                        <option>M</option>
                                        <option>L</option>
                                        <option>XL</option>
                                        <option>XXL</option>
                                        <option>3XL</option>
                                        <option>4XL</option>
                                        <option>5XL</option>                               
                                        <!--<optgroup label="Could not find a property">
                                            <option >Add a new option</option>
                                        </optgroup>-->
                                    </select>
                              </div>
                             <div class="list_inner_fields" style="border-bottom:none;">
                                    <label>&nbsp;</label> 
                                    <div class="list_inner_right" id="options_table1" style="display:none">
                                        <table width="100%" class="inner_table"  align="center" cellpadding="0" cellspacing="0" id="options_list1">  
										<center><img src="images/ajax-loader/ajax-loader(14).gif" alt="Adding variations" style="display:none;" id="variation_add_loading2" /></center><br />            
                                            <tbody>
                                                <tr>
                                                   <td width="40%" ><strong>Options</strong></td>
                                                   <td width="25%">
                                                        <span class="non-pricing-mode">&nbsp;
                                                        <!--<a href="javascript:void(0)" class="enable-variations-pricing" id="price_opt1" onclick="price_opt_click1();">Add Pricing</a>-->
                                                        </span>
                                                        <span class="pricing-mode retail">
                                                            <a href="#variations-section" class="disable-variations-pricing remove button-remove"></a>
                                                               <!--<span class="price-header-label retail">
                                                                      Price
                                                                <small>USD</small>
                                                            </span>-->
                                                        </span>
                                                    </td>
                                                   <td  width="25%" ><strong>In Stock</strong></td>
                                                   <td  width="10%" ></td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>   
                                </div>';*/
								
				echo ' <div style="float:right;">
                              	<a href="javascript:void(0)" onclick="return clear_data1();" id="close_var_two" style="display:none;" class="close_icon"></a>
                             </div>
                             <div class="list_inner_right list_small_width" id="attr_loader1" style="display:none">
                              	<img src="images/ajax_loading.gif" alt="loading variations" />
                             </div>
                             <div class="list_inner_right list_small_width" id="options_level1" name="options_level1" style="display:none"></div>
                             <div class="list_inner_right list_small_width" id="attr_options_val1" name="attr_options_val1" style="display:none">
                                    <select onchange="return alpha_check1(this);" id="checked_alpha_value1" class="alpha_value_two">
                                        <option value="">';if($this->lang->line('shop_selavailableoptions') != '') { echo stripslashes($this->lang->line('shop_selavailableoptions')); } else echo 'Select available options'; echo '...</option>
                                        <option>XXS</option>
                                        <option>XS</option>
                                        <option>S</option>
                                        <option>M</option>
                                        <option>L</option>
                                        <option>XL</option>
                                        <option>XXL</option>
                                        <option>3XL</option>
                                        <option>4XL</option>
                                        <option>5XL</option>                               
                                        <!--<optgroup label="Couldnt find a property">
                                            <option >Add a new option</option>
                                        </optgroup>-->
                                    </select>
                              </div>
                             <div class="list_inner_fields" style="border-bottom:none;">
                                    <label>&nbsp;</label> 
                                    <div class="list_inner_right" id="options_table1" style="display:none">
                                    <center><img src="images/ajax-loader/ajax-loader(14).gif" alt="Adding variations" style="display:none;" id="variation_add_loading2" /></center><br />
                                        <table width="100%" class="inner_table"  align="center" cellpadding="0" cellspacing="0" id="options_list1">              
                                            <tbody>
                                                <tr style="background:#E9F6FC;; margin: 0px; padding: 9px 0px 0px;">
                                                   <td width="20%" ><strong>';if($this->lang->line('shop_options') != '') { echo stripslashes($this->lang->line('shop_options')); } else echo 'Options'; echo '</strong></td>
                                                   <td width="20%">
                                                        <span class="non-pricing-mode">&nbsp;
                                                        <!--<a href="javascript:void(0)" class="enable-variations-pricing" id="price_opt1" onclick="price_opt_click1();">Add Pricing</a>-->
                                                        </span>
                                                        <span class="pricing-mode retail">
                                                            <a href="#variations-section" class="disable-variations-pricing remove button-remove"></a>
                                                               <!--<span class="price-header-label retail">
                                                                      Price
                                                                <small>USD</small>
                                                            </span>-->
                                                        </span>
                                                    </td>
                                                   <td  width="20%" ><strong>';if($this->lang->line('shop_instock') != '') { echo stripslashes($this->lang->line('shop_instock')); } else echo 'In Stock'; echo '</strong></td>
                                                   <td  width="10%" ></td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>   
                                </div>';				
	}
	


	
		
	public function search_product($item){
		
		$item_search='';  $s_key='';
		if($this->input->get('item') != ''){
			$s_key=mysql_real_escape_string($this->input->get('item')); 
			$checkShopName=$this->product_model->get_all_details(SELLER,array('seller_businessname' => $s_key,'status' => 'active'));
			if($checkShopName->num_rows() == 1){ 
			redirect('shop-section/'.$checkShopName->row()->seourl);
			}
			$this->data['searchKey'] =$this->input->get('item');
			$item_search="and (p.product_name LIKE '%".$s_key."%' or p.tag LIKE '%".$s_key."%' or p.materials LIKE '%".$s_key."%')";
		}
	      //echo 'sdfbjh'; die;
		$segmentArr=$this->uri->segment_array();
		$this->data['cats1']='No';
		$this->data['cats2']='No';
	    if($this->uri->segment(3) != '') {
			$Catid1=explode('-',$this->uri->segment(3)); 
			$sortArr2 = array('field'=>'cat_position','type'=>'asc');
			$sortArr1 = array($sortArr2);
			$this->data['cat1']=$this->product_model->get_all_details(CATEGORY,array('id' => $Catid1[0],'status'=>'Active'))->row();
			$this->data['cats1']=$this->product_model->get_all_details(CATEGORY,array('rootID'=>$Catid1[0],'status'=>'Active'),$sortArr1);
			
			//print_r($this->data['cats1']->result()); die;
			/*if($currentcatDetails->rootID == 0){
			redirect('category-list/'.$this->uri->segment(count($segmentArr)));
			} */
			
			if($this->uri->segment(4) != '') {
				$Catid2=explode('-',$this->uri->segment(4));
				$this->data['cat2']=$this->product_model->get_all_details(CATEGORY,array('id' => $Catid2[0],'status'=>'Active'))->row();
				$this->data['cats2']=$this->product_model->get_all_details(CATEGORY,array('rootID'=>$Catid2[0],'status'=>'Active'),$sortArr1);
						/*if($this->data['cats2']->num_rows() == 0){
							$this->data['cat2']=$this->product_model->get_all_details(CATEGORY,array('rootID'=>$this->data['cat2']->rootID,'status'=>'Active'),$sortArr1);
						}*/
				if($this->uri->segment(5) != '') {
					$Catid3=explode('-',$this->uri->segment(5));
					$this->data['cat3']=$this->product_model->get_all_details(CATEGORY,array('id' => $Catid3[0],'status'=>'Active'))->row();
					//$this->data['cats3']=$this->product_model->get_all_details(CATEGORY,array('rootID'=>$Catid3[0],'status'=>'Active'),$sortArr1);		
		    	}
		   }
		}
		
		//echo $item_search; die;
		
		$marketplace1=array_search('handmade',$segmentArr); 
		$made_by='';
		if($this->uri->segment($marketplace1) != ''){
		$filterid=1;
		$made_by="and p.made_by='".$filterid."'"; 
		} 
		$marketplace2=array_search('vintage',$segmentArr);
		if($this->uri->segment($marketplace2) != ''){
		$filterid=2;
		$made_by="and p.made_by='".$filterid."'"; 
		} 
		$marketplace3=array_search('supplies',$segmentArr);
		if($this->uri->segment($marketplace3) != ''){
		$filterid=3;
		$made_by="and p.made_by='".$filterid."'"; 
		} 
		$minprice='';
		$maxprice='';  
		if($this->input->get('max_price') != '' || $this->input->get('min_price') != ''){
		$minVal = $this->input->get('min_price')/$this->data['currencyValue']; $maxVal = $this->input->get('max_price')/$this->data['currencyValue'];  
			if($maxVal == ''){
			$price="and ((p.price >='".$minVal."')"; 
			$prcing="or (a.pricing >='".$minVal."'))";
			}else { 
			$price="and ((p.price >='".$minVal."' and p.price <='".$maxVal."')";
			$prcing="or (a.pricing >='".$minVal."' and a.pricing <='".$maxVal."'))"; 
			}
		} 
		$shipto='';  
		if($this->input->get('shipto') != ''){
		$shipto="and (ss.ship_id ='".$this->input->get('shipto')."' or ss.ship_id ='232')"; 
		} 
		$shipfrom='';
		$location=mysql_real_escape_string($this->input->get('location'));
		if($location != ''){
		$shipfrom="and (u.city LIKE '%".$location."%' or u.district LIKE '%".$location."%' or u.state LIKE '%".$location."%' or u.country LIKE '%".$location."%')"; 
		}
		
		$gift_cards='';  $gift='';
		if($this->input->get('gift_cards') != ''){
		$gift_cards="and s.gift_card ='Yes'";
		$gift=$this->input->get('gift_cards');
		} 
		$this->data['gift']=$gift;
		$category='';
		if($this->uri->segment(3) != ''){
			$catid=explode('-',$this->uri->segment(count($segmentArr)));
		$category="and FIND_IN_SET('".$catid[0]."',p.category_id)";
		}
		$order='';
		if($this->input->get('order') == 'date_desc'){   //
		$order="order by p.created desc";
		}
		if($this->input->get('order') == 'most_relevant'){   //
		$order="order by p.category_id asc";
		}
		//$order="order by p.price,a.pricing asc";
		
		
		$condition = " where p.status='Publish' ".$item_search." ".$category." ".$made_by." ".$gift_cards." ".$price." ".$prcing." ".$shipto." ".$shipfrom." and u.group='Seller' and u.status='Active' or p.status='Publish' and p.user_id=0 and a.pricing IS NOT NULL group by p.id ".$order." LIMIT 0,3";
		$this->data['product_list']=$this->product_model->view_product_details($condition);
		
		
		
		$condition = " where p.status='Publish' ".$item_search." ".$category." ".$made_by." ".$gift_cards." ".$price." ".$prcing." ".$shipto." ".$shipfrom." and u.group='Seller' and u.status='Active' or p.status='Publish' and p.user_id=0 and a.pricing IS NOT NULL group by p.id ".$order."";
		$this->data['product_count']=$this->product_model->view_product_details_count($condition);
		
		
		//$this->data['product_list']=$this->product_model->get_limited_details_FIND(PRODUCT,'',$condition);
		
		#echo $this->db->last_query(); die; 
		
	    //$this->data['countryList'] = $this->product_model->get_all_details(COUNTRY_LIST,array())->result();
		$this->data['countTitle'] =$this->data['product_count']->num_rows().' items';
		
		$this->data['title'] ='Search items in '.$this->config->item('email_title');
		$this->data['meta_title'] ='Search items in '.$this->config->item('email_title');
		$this->data['meta_keyword'] ='Search items in '.$this->config->item('email_title');
		$this->data['meta_description'] =$currentcatDetails->seo_description;   
	
		
	$this->load->view('site/product/product_search',$this->data);
	}
	
	
	public function display_product_favoriters($seourl){
		$condition = " where p.status='Publish' and p.seourl='".$seourl."' and u.group='Seller' and u.status='Active' or p.status='Publish' and p.user_id=0 and a.pricing IS NOT NULL group by p.id order by p.created desc";		
		$this->data['prodInfo']=$prodInfo=$this->product_model->view_product_details($condition)->result();
		$this->data['favUserList']=$favUserList=$this->product_model->getProductFavDetails($prodInfo[0]->id);
					#echo "<pre>"; print_r($favUserList);die;
		if (count($favUserList)>0){
			foreach ($favUserList as $favUser){
				$this->data['favoritersUserfavDetails'][$favUser['user_id']] = $this->user_model->get_userfav_products($favUser['user_id']);
				$this->data['favoritersUserfavProdDetails'][$favUser['user_id']] = $this->user_model->get_userfav_products($favUser['user_id'])->result_array();
			}
		}
		#echo "<pre>"; print_r($this->data['favoritersUserfavDetails']);die;
		$condition = array('id'=>$this->checkLogin('U'));
		$this->data['userProfileDetails'] = $this->product_model->get_all_details(USERS,$condition)->result_array();
		$this->data['title'] = 'People who have favorited '.$prodInfo[0]->product_name.' by '.$prodInfo[0]->shop_name.' - '.$this->config->item('meta_title');
		$this->data['meta_title'] ='People who have favorited '.$prodInfo[0]->product_name.' by '.$prodInfo[0]->shop_name.' - '.$this->config->item('meta_title');	
		$this->data['meta_description'] =$currentcatDetails->seo_description;   
		
		$this->load->view('site/product/product_favorites',$this->data);
	}
	/*DeleteShopProducts*/
	public function DeleteShopProducts(){
		$deleteProducts =$this->input->post('deleteProducts');
		foreach($deleteProducts as $PrdId){
			//$this->product_model->commonDelete(PRODUCT,array('id' =>$PrdId));
			$this->product_model->update_details(PRODUCT,array('status' => 'Deleted'),array('id' =>$PrdId));
		}
		redirect($_SERVER['HTTP_REFERER']);
	}
	
	/*laod more ajax for product search*/	
	public function ajax_search_product(){	
	$loginCheck = $this->checkLogin('U');	
		$item_search='';  $s_key='';
		if($this->input->get('item') != ''){
			$s_key=mysql_real_escape_string($this->input->get('item')); 
			$checkShopName=$this->product_model->get_all_details(SELLER,array('seller_businessname' => $s_key,'status' => 'active'));
			if($checkShopName->num_rows() == 1){ 
			redirect('shop-section/'.$checkShopName->row()->seourl);
			}
			$this->data['searchKey'] =$this->input->get('item');
			$item_search="and (p.product_name LIKE '%".$s_key."%' or p.tag LIKE '%".$s_key."%' or p.materials LIKE '%".$s_key."%')";
		}
		$segmentArr=$this->uri->segment_array();
		$this->data['cats1']='No';
		$this->data['cats2']='No';
	    
		$marketplace1=array_search('handmade',$segmentArr); 
		$made_by='';
		if($this->uri->segment($marketplace1) != ''){
		$filterid=1;
		$made_by="and p.made_by='".$filterid."'"; 
		} 
		$marketplace2=array_search('vintage',$segmentArr);
		if($this->uri->segment($marketplace2) != ''){
		$filterid=2;
		$made_by="and p.made_by='".$filterid."'"; 
		} 
		$marketplace3=array_search('supplies',$segmentArr);
		if($this->uri->segment($marketplace3) != ''){
		$filterid=3;
		$made_by="and p.made_by='".$filterid."'"; 
		} 
		$minprice='';
		$maxprice='';  
		if($this->input->get('max_price') != '' || $this->input->get('min_price') != ''){
		$minVal = $this->input->get('min_price')/$this->data['currencyValue']; $maxVal = $this->input->get('max_price')/$this->data['currencyValue'];  
			if($maxVal == ''){
			$price="and ((p.price >='".$minVal."')"; 
			$prcing="or (a.pricing >='".$minVal."'))";
			}else { 
			$price="and ((p.price >='".$minVal."' and p.price <='".$maxVal."')";
			$prcing="or (a.pricing >='".$minVal."' and a.pricing <='".$maxVal."'))"; 
			}
		} 
		$shipto='';  
		if($this->input->get('shipto') != ''){
		$shipto="and (ss.ship_id ='".$this->input->get('shipto')."' or ss.ship_id ='232')"; 
		} 
		$shipfrom='';
		$location=mysql_real_escape_string($this->input->get('location'));
		if($location != ''){
		$shipfrom="and (u.city LIKE '%".$location."%' or u.district LIKE '%".$location."%' or u.state LIKE '%".$location."%' or u.country LIKE '%".$location."%')"; 
		}
		
		$gift_cards='';  $gift='';
		if($this->input->get('gift_cards') != ''){
		$gift_cards="and s.gift_card ='Yes'";
		$gift=$this->input->get('gift_cards');
		} 
		$this->data['gift']=$gift;
		$category='';
		if($this->uri->segment(6) != ''){
			$catid=explode('-',$this->uri->segment(count($segmentArr)));
		$category="and FIND_IN_SET('".$catid[0]."',p.category_id)";
		}
		$order='';
		if($this->input->get('order') == 'date_desc'){   //
		$order="order by p.created desc";
		}
		if($this->input->get('order') == 'most_relevant'){   //
		$order="order by p.category_id asc";
		}		
		$offset = is_numeric($_POST['offset']) ? $_POST['offset'] : die();
		$postnumbers = is_numeric($_POST['number']) ? $_POST['number'] : die();
		$condition = " where p.status='Publish' ".$item_search." ".$category." ".$made_by." ".$gift_cards." ".$price." ".$prcing." ".$shipto." ".$shipfrom." and u.group='Seller' and u.status='Active' or p.status='Publish' and p.user_id=0 and a.pricing IS NOT NULL group by p.id ".$order." LIMIT ".$offset.",".$postnumbers."";
		$this->data['product_list']=$product_list=$this->product_model->view_product_details($condition);
		
		$productsDetail=$product_list->result_array();	
		#echo "<br><pre>"; print_r($product_list); die;			
				if(!empty($productsDetail)){ $i=0;
				foreach($productsDetail as $proddetails){
                  	$imgSplit = explode(",",$proddetails['image']); 				
            	 $content .='<li>     
                    <div class="product_img">
                                <div class="product_hide">                                    
                                    <div class="product_fav">';                             
										if($loginCheck !=''){
                                        $favArr = $this->product_model->getUserFavoriteProductDetails(stripslashes($proddetails['id']));
                                        if(empty($favArr)){ 
                                       $content .='<a href="javascript:void(0);" onclick="return changeProductToFavourite(\''.stripslashes($proddetails['id']).'\',\'Fresh\');">
                                            <input type="submit" value="" class="hoverfav_icon" />
                                        </a>';
                                         } else {                        
                                       $content .='<a href="javascript:void(0);" onclick="return changeProductToFavourite(\''.stripslashes($proddetails['id']).'\',\'Old\');">
                                            <input type="submit" value="" class="hoverfav_icon1" />
                                        </a>';
                                        }} else {
                                         $content .='<a href="login" >
                                            <input type="submit" value="" class="hoverfav_icon" />
                                        </a>';
                                          }
                                     $content .='</div>                                       
                                    <div class="hoverdrop_icon">
                                    	<a href="javascript:hoverView(\''.$i.'\');">  </a>
                                        	<div class="hover_lists" id="hoverlist'.$i.'">
                                               	<h2>';
												if($this->lang->line('user_your_lists') != '') {  $content .= stripslashes($this->lang->line('user_your_lists')); } else  $content .= "Your Lists";  $content .='</h2>
                                                <div class="lists_check">';
                                                	foreach($this->data['userLists'] as $Lists){
													$haveListIn = $this->user_model->check_list_products(stripslashes($proddetails['id']),$Lists['id'])->num_rows();
													if($haveListIn>0){$chk='checked="checked"';}else{ $chk='';}
                                                     $content .='<input type="checkbox" class="check_box" onclick="return addproducttoList(\''.$Lists['id'].'\',\''.stripslashes($proddetails['id']).'\');" '.$chk.'/>
                                                    <label>'.$Lists['name'].'</label>';
                                                     } 
                                                     if(!empty($this->data['userRegistry'])){
														$haveRegisryIn = $this->user_model->check_registry_products($proddetails['id'],$this->data['userRegistry']->user_id)->num_rows();
														if($haveRegisryIn>0){$chk='checked="checked"';}else{ $chk='';}
													 $content .='<input type="checkbox" class="check_box" onclick="return manageRegisrtyProduct(\''.$this->data['userRegistry']->user_id.'\',\''.$proddetails['id'].'\');" '.$chk.' />
													<label><span class="registry_icon"></span>';
													if($this->lang->line('prod_wedding') != '') {  $content .= stripslashes($this->lang->line('prod_wedding')); } else  $content .= "Wedding Registry"; $content .='</label>';
													 }  
                                                    $content .='</div>                                                    
                                                    <div class="new_list">
                                                    <form method="post" action="site/user/add_list">
                                                        <input type="hidden" value="1" name="ddl" />
                                                        <input type="hidden" value="'.$proddetails['id'].'" name="productId" />
                                                        <input type="text" placeholder="';if($this->lang->line('user_new_list') != '') { $content .= stripslashes($this->lang->line('user_new_list')); } else $content .= "New list"; $content .='" class="list_scroll" name="list" id="creat_list_'.$i.'" />
                                                        <input type="submit" value="';if($this->lang->line('user_add') != '') { $content .= stripslashes($this->lang->line('user_add')); } else $content .= "Add"; $content .='" class="primary-button" onclick="return validate_create_list(\''.$i.'\');" />
                                                    </form>
                                                </div>
                                        	</div>	
                                    	
                                   	</div>  
                               </div>
                      
                        <a href="products/'.$proddetails['seourl'].'">
                            <img  src="';if(!empty($imgSplit[0])){ $content .='images/product/thumb/'.stripslashes($imgSplit[0]); } else { $content .="images/dummyProductImage.jpg";  }$content .='" 
                              alt="'.stripslashes($proddetails['product_name']).'" title="'.stripslashes($proddetails['product_name']).'" width="350px" height="400px" />
                        </a>
                    </div>
                                
                    <div class="product_title"><a href="products/'.$proddetails['seourl'].'">'.$proddetails['product_name'].'</a></div>
                    <div class="product_maker"><a href="shop-section/'.$proddetails['shop_seourl'].'">'.$proddetails['shop_name'].'</a></div>
                    <div class="product_price">';
						if($proddetails['price'] != 0.00) {
                        $content .='<span class="currency_value">'.$this->data['currencySymbol'].' '. number_format($this->data['currencyValue']*$proddetails['price'],2).'</span>
                        <span class="currency_code">'.$this->data['currencyType'].'</span>';
                         } else { 
                        $content .='<span class="currency_value">'.$this->data['currencySymbol'].' '.number_format($this->data['currencyValue']*$proddetails['pricing'],2).'+'.'</span>
                        <span class="currency_code">'.$this->data['currencyType'].'</span>';
                         }
                   $content .=' </div>
                            
                </li> ';
				$i++;	} 	}  else { $content=''; }
				echo $content;
	}
	/**
	* Adding Product using csv file
	* Upload csv file 
	* Extract the values and import into the table
	*/
	public function upload_the_file()
	{
		if($this->checkLogin('U')=='')
		{
			redirect('login');
		}
		else
		{
			$file = $this->input->post('upload_csv');
			$logoDirectory ='./images/csv';
			if(!is_dir($logoDirectory))
			{
				mkdir($logoDirectory,0777);
			}
			$config['overwrite'] = FALSE;
			$config['remove_spaces'] = TRUE;
			$config['upload_path'] = $logoDirectory;
			$config['allowed_types'] = '*';

			$this->load->library('upload', $config);

			$file_element_name = 'upload_csv';
			if( $this->upload->do_upload('upload_csv'))
			{
				$fileDetails = $this->upload->data();
				$coun = 0; $row = 1;
				$handle = fopen($logoDirectory."/".$fileDetails['file_name'],"r");
				if(($data1 = fgetcsv($handle, 10000, ",")) !== FALSE)
				{
					$data_format = array('type','product_condition','when_did_you_make_it','category','name','description','image','price','quantity','country','ship_cost','ship_cost_with_other');
					if ($data_format==$data1){
						fclose($handle);
						$handle = fopen($logoDirectory."/".$fileDetails['file_name'],"r");
						while(($data = fgetcsv($handle, 10000, ",")) !== FALSE){
							if($row == 1){ $row++; continue; }
							$finalImgArr=array();
							$who_made_it 			=  		$data[0];
							$what_is_it 			=  		$data[1];
							$when_did_you_make_it 	=  		$data[2];
							$category 				=  		$data[3];
							$name					=  		$data[4];
							$description 			=  		$data[5];
							$image 					=  		$data[6];
							$price 					=  		$data[7];
							$quantity 				=  		$data[8];
							$country 				=  		$data[9];
							$ship_cost 				=  		$data[10];
							$ship_cost_with_other 	=  		$data[11];


							$price_range = 0;
							if ($sale_price>0 && $sale_price<21)
								$price_range = '1-20';
							else if ($sale_price>20 && $sale_price<101)
								$price_range = '21-100';
							else if ($sale_price>100 && $sale_price<201)
								$price_range = '101-200';
							else if ($sale_price>200 && $sale_price<501)
								$price_range = '201-500';
							else if ($sale_price>500)
								$price_range = '501+';
							
							if($who_made_it=='handmade'){
								$made_by=1;
							}else if($who_made_it=='vintage'){
								$made_by=2;
							}else if($who_made_it=='craft supply'){
								$made_by=3;
							}
							
							if($what_is_it=='finished'){
								$product_condition=1;
							}else if($what_is_it=='unfinished'){
								$product_condition=2;
							}
							
							$maked_on=str_replace('-',',',$when_did_you_make_it);


							$seller_product_id = mktime();
							$checkId = $this->check_product_id($seller_product_id);
							while ($checkId->num_rows()>0){
								$seller_product_id = mktime();
								$checkId = $this->check_product_id($seller_product_id);
							}

							/****----------Move image to server-------------****/

							$image_url = $image;
							
							$imageurlArr=@explode(',',$image);
							foreach($imageurlArr as $image_url){

							$img_data = file_get_contents($image_url);

							$img_full_name = substr($image_url, strrpos($image_url, '/')+1);
							$img_name_arr = explode('.', $img_full_name);
							$img_name = $img_name_arr[0];
							$ext = $img_name_arr[1];
							$ext_arr = explode('?', $ext);
							$ext = $ext_arr[0];
							if (!$ext) $ext='jpg';
							$new_name = str_replace(array(',','$','(',')','~','&'), '', $img_name.mktime().'.'.$ext);
							$new_img = 'images/product/temp_img/'.$new_name;

							file_put_contents($new_img, $img_data);

							/****----------Move image to server-------------****/

							$image_name = $new_name;

							#$this->imageResizeWithSpace(600, 600, $image_name, './images/product/');
							
							@copy('./images/product/temp_img/'.$image_name, './images/product/org-image/'.$image_name);
							@copy('./images/product/temp_img/'.$image_name, './images/product/'.$image_name);
							$this->ImageResizeWithCrop(550, 350, $image_name, './images/product/');
							@copy('./images/product/'.$image_name, './images/product/thumb/'.$image_name);
							$this->ImageResizeWithCrop(175, 150, $image_name, './images/product/thumb/');
							@copy('./images/product/temp_img/'.$image_name, './images/product/list-image/'.$image_name);
							$this->ImageResizeWithCrop(75, 75, $image_name, './images/product/list-image/');
							
							$finalImgArr[]=$image_name;
							}
							
							$finalimage_name = implode(',', $finalImgArr);

							$catArr = $this->product_model->get_all_details(CATEGORY,array('cat_name'=>$category));
							if ($catArr->num_rows()>0){
								$category_id_arr = array($catArr->row()->id);
								while ($catArr->row()->rootID>0){
									$catArr = $this->product_model->get_all_details(CATEGORY,array('id'=>$catArr->row()->rootID));
									if ($catArr->num_rows()>0){
										$category_id_arr[] = $catArr->row()->id;
									}else {
										break;
									}
								}
								$category_id = implode(',',array_reverse($category_id_arr));
							}else {
								$category_id = '252';
							}
							
							
							$seourlBase = $seourl = url_title($name, '-', TRUE);
							$seourl_check = '0';
							$duplicate_url = $this->product_model->get_all_details(PRODUCT,array('seourl'=>$seourl));
							if ($duplicate_url->num_rows()>0){
								$seourl = $seourlBase.'-'.$duplicate_url->num_rows();
							}else {
								$seourl_check = '1';
							}
							$urlCount = $duplicate_url->num_rows();
							while ($seourl_check == '0'){
								$urlCount++;
								$duplicate_url = $this->product_model->get_all_details(PRODUCT,array('seourl'=>$seourl));
								if ($duplicate_url->num_rows()>0){
									$seourl = $seourlBase.'-'.$urlCount;
								}else {
									$seourl_check = '1';
								}
							}
							$modifyDate='';
							if($this->checkLogin('U')==1){
								$status='Publish';
								$pay_status='Paid';
							}else{
								$status='UnPublish';
								$pay_status='Pending';
							}
						 	$ship_duration='';
							$insertdata = array(
										'seller_product_id' => $seller_product_id,
										'made_by' => $made_by,
										'product_condition' => $product_condition,
										'modified' => $modifyDate,
										'maked_on' => $maked_on,
										'product_name' => $name,
										'description' => $description,
										'price' => $price,
										'quantity' => $quantity,
										'image' => $finalimage_name,
										'category_id' => $category_id,
										'status' => $status, 
										'pay_status' => $pay_status, 
										'seourl' => $seourl,
										'ship_duration' => $ship_duration,
										'ship_from' => $country,
										'user_id' => $this->checkLogin('U')
										);
							
							$this->product_model->simple_insert(PRODUCT,$insertdata);
							$idArr = $this->product_model->get_last_insert_id();
							
							$ship_to = $this->input->post('shipping_to');  
							$ship_to_id = $this->input->post('ship_to_id'); 
							
							$cost_individual = $ship_cost;	
							$cost_with_another = $ship_cost_with_other;
							$shipName=$country;
							$countryInfo = $this->product_model->get_all_details(COUNTRY_LIST,array('name'=>$country));
							$shipId=$countryInfo->row()->id; 
							
							$seourlBase = $seourl = url_title($shipName, '-', TRUE);
							$seourl_check = '0';
							$duplicate_url = $this->product_model->get_all_details(SUB_SHIPPING,array('ship_seourl'=>$seourl));
							if ($duplicate_url->num_rows()>0){
								$seourl = $seourlBase.'-'.$duplicate_url->num_rows();
							}else {
								$seourl_check = '1';
							}
							$urlCount = $duplicate_url->num_rows();
							while ($seourl_check == '0'){
								$urlCount++;
								$duplicate_url = $this->product_model->get_all_details(SUB_SHIPPING,array('ship_seourl'=>$seourl));
								if ($duplicate_url->num_rows()>0){
									$seourl = $seourlBase.'-'.$urlCount;
								}else {
									$seourl_check = '1';
								}
							}
					
						 	$dataArrShip=array('product_id' => $idArr,
									'ship_id' => $shipId,
									'ship_name' => $shipName,
									'ship_cost' => $cost_individual,
									'ship_seourl' => $seourl,
									'ship_other_cost' => $cost_with_another
								);
						 	$this->product_model->simple_insert(SUB_SHIPPING,$dataArrShip);
						 
							$usrdetails = $this->product_model->get_all_details(USERS,array('id'=>$this->checkLogin('U')));
							if($usrdetails->num_rows()>0)
							{
								$prodCount = $usrdetails->row()->products;
								$prodCount = $prodCount+1;
								$this->product_model->update_details(USERS,array('products'=>$prodCount),array('id'=>$this->checkLogin('U')));
							}

							$row++;
						}
						fclose($handle);
						$this->setErrorMessage('success','Your csv file is uploaded and the product details are added');
						redirect(base_url().'upload-products');
					}else {
						fclose($handle);
						$this->setErrorMessage('error','The coloumns in this csv file does not match to the database');
						redirect('upload-products');
					}

				}
				fclose($handle);
				$this->setErrorMessage('error','The coloumns in this csv file does not match to the database');
				redirect('upload-products');
			}else {
				$this->setErrorMessage('error',strip_tags($this->upload->display_errors()));
				redirect(base_url().'upload-products');
			}
		}
			
	}
	public function check_product_id($pid=''){
		$checkId = $this->product_model->get_all_details(USER_PRODUCTS,array('seller_product_id'=>$pid));
		if ($checkId->num_rows()==0){
			$checkId = $this->product_model->get_all_details(PRODUCT,array('seller_product_id'=>$pid));
		}
		return $checkId;
	}
	public function upload_product_form(){
		if ($this->checkLogin('U')==''){
    		redirect(base_url().'login');
    	}else {
    		$this->data['heading'] = 'Upload CSV';
    		$this->data['countryList'] = $this->user_model->get_all_details(COUNTRY_LIST,array(),array(array('field'=>'name','type'=>'asc')));
	    	$this->data['shippingList'] = $this->user_model->get_all_details(SHIPPING_ADDRESS,array('user_id'=>$this->checkLogin('U')));
    		$this->load->view('site/shop/upload_csv',$this->data);
    	}
	}
	
}
/*End of file product.php */
/* Location: ./application/controllers/site/product.php */
