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

class Quick_order extends CI_Controller {


	private $cart_qty   = '' ;
	private $logged 	= 0  ;	
	private $user 		= '' ;
	
	public function __construct()
	{
		parent::__construct();
		
		$this->load->model('Db_model');
		
		$this->load->library('cart');
		
		$this->load->helper('basic_helper');
		$ic=0;
		foreach ($this->cart->contents() as $items):
		$ic++;
		
		endforeach;
		$this->cart_qty = ''.$ic.'';
		
		if($this->session->userdata('shop_user2'))
		{
			$this->load->library('encrypt') ;
			$this->user = $this->encrypt->decode($this->session->userdata('shop_user2'));
			$this->logged = 1;
		}
		
	}
	
	public function index()
	{	
		
		$data['product'] = array();
		$data['preproduct'] = array();
		$data['result']= array();
		$data['categoryes']=array();
		$data['subcategoryquick']=array();
		$data['cart_qty'] = $this->cart_qty ;
		$data['brand_id'] = $this->brand_id ;
		$data['email'] = $this->user;
		$data['logged'] = $this->logged;
		
		$data['allproduct']= $this->Db_model->get_where_by_order('shop_product',array('active'=>'Y'),'order','asc') ;
        $data['brand'] = $this->Db_model->get_where_by_order('shop_brand',array(),'order','asc') ;
		$data['contactus'] = $this->Db_model->get_where_by_order('shop_contact',array('status'=>'1'),'id','desc') ;
		$data['site'] = $this->Db_model->get_all('site',array()) ;
		$data['service'] = $this->Db_model->get_where_by_order('shop_pages',array('active'=>'Y','type'=>'service'),'order','asc') ;
		$data['category']=$data['result'] = $this->Db_model->get_where_by_order('shop_category',array(),'order','asc') ;
		$data['subcategoryquick'] = $this->Db_model->get_where_by_order('shop_subcategory',array(),'id','asc') ;	
		$data['gift'] = $this->Db_model->get_where_by_order('shop_category',array(),'order','asc') ;

		
		
		if($product!==FALSE)
		{
		$data['product'] = $product;
	
		}
		
		

		if($this->input->post('addtocart'))
		{
			
			
			echo $sub_cat=$this->input->post('sub_categories');
			echo $pro_id=$this->input->post('sub_categories_products');
			echo $qty=$this->input->post('pro_qty');
			
	   $this->load->model('Db_model') ;
		$product = $this->Db_model->get_by_id('shop_product','aid',$pro_id) ;	
			
			
			$data = array(
               //'id'      => 'sku_'.$id,
			   'id'      => $pro_id ,
               'qty'     => $qty,
               'price'   => $product->price,
			   'unit_id' => $product->unit_id,
               'name'    => $product->title,
			   'image'   => $product->img,
               'options' => $option_array
            );
	

		$this->cart->insert($data);

		redirect('Quick_order') ;
			
			//redirect('Cart/quckinsert/'.$pro_id.'/'.$qty.'/'.$price.'/'.$unit_id.'/'.$url.'/'.$cid.'/'.$sid.'/'.$bid);
			//'Cart/insert/'.$row_off['aid'].'/1/'.$row_off['price'].'/'.$row_off['unit_id'].'/'.$url.'/'.url_title($row_off->title,'-',true)
		}
		
		
		
		
		
		
		$this->load->view('website/header',$data);
        $this->load->view('website/menu',$data);
		$this->load->view('website/quickorder',$data);
        $this->load->view('website/footer');
	}
	
	public function sub_categories_products()
	{	
		$sub_categories=$this->input->post('sub_categories');
		$sub_categories_products= $this->Db_model->get_where_by_order('shop_product',array('subcategory_id'=>$sub_categories),'aid','asc') ;
		echo json_encode($sub_categories_products);
	}
	
	
		function delete_item($row_id='',$link='')
	{ 
	
	echo $link=base64_decode(urldecode($link));
		$data = array(
               'rowid' => $row_id,
               'qty'   => 0
            );

		$this->cart->update($data);
		
		redirect('Quick_order') ;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	function update($link='')
	{
	
	$link=base64_decode(urldecode($link));
		/*$data = array(
               'rowid' => 'b99ccdf16028f015540f341130b6d8ec',
               'qty'   => 3
            );*/
		
		/*echo '<pre>' ;
		print_r($this->input->post());
		echo '</pre>' ;*/
		
       //print_r($this->input->post());
		//$this->cart->update($this->input->post());
		
	 	$dtype=$this->input->post('dtype');
		
		/*echo '<pre>' ;
		print_r($this->input->post());
		echo '</pre>' ;*/
		
		
		
$formValues = $this->input->post();
foreach($formValues as $key => $username) 
{


$rowids=$username['rowid'];
$new_cart_quty=$username['qty'];
$pro_id= $username['id'];
 $product = $this->Db_model->get_by_id('shop_product','aid',$pro_id) ;
 $product->stock;
  
 
$data[] = array(
        'rowid'  => $rowids,
        'qty'    => $new_cart_quty,
        'id'  => $pro_id,
        'options' => array('cupon' => $dtype));
  
}
		
$this->cart->update($data);		


		if($this->input->post('update'))
		{
		redirect($link);
		
		}	
		if($this->input->post('cupdate'))
		{
		redirect('Product/categorylist');
			
		}
			
		if($this->input->post('placeorder'))
		{
		redirect('Quick_order/guest');
		}
		

		//$this->view();		
		
		//redirect('cart') ;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public function guest()
	{

		$data['cart_qty'] = $this->cart_qty;
		//$data['email'] = $this->user;
		//$data['logged'] = $this->logged;
		$data['error'] = '';
		$data['suc_msg'] = '';
		$data['c_page'] = 'shipaddress';
		$data['allproduct']= $this->Db_model->get_where_by_order('shop_product',array('active'=>'Y'),'order','asc') ;
		$data['category']=$data['result'] = $this->Db_model->get_where_by_order('shop_category',array('gift'=>1),'order','asc') ;	
		//$data['gift'] = $this->Db_model->get_where_by_order('shop_category',array('gift'=>2),'order','asc') ;
		$data['site'] = $this->Db_model->get_all('site',array()) ;
		
		
	$data['post_list'] = $this->Db_model->get_where_by_order('delivery',array('type'=>'delivery','active'=>'Y'),'title','asc') ;
		
		
		//$data['category']=$data['result'] = $this->Db_model->get_all_by_order('shop_category','order','asc') ;	
		$data['subcate'] = $this->Db_model->get_all_by_order('shop_subcategory','id','desc') ;
		
 		$data['contactus'] = $this->Db_model->get_where_by_order('shop_contact',array('status'=>'1'),'id','desc') ;
		
	
		//$data['offer'] = $this->Db_model->get_all_by_order('shop_category','order','asc') ;
		if($this->Db_model->get_all_by_order('shop_shipping','area','asc')!==FALSE)
		{
			$area_det = $this->Db_model->get_all_by_order('shop_shipping','area','asc');
		}
		else
		{
			$area_det = array() ;
		}
		
		$data['area_det'] = $area_det;
		
		
		$this->load->library('form_validation');
		
		
		if($this->input->post('submit'))
		{


$ddate=$_POST['ddate']; $dtime=$_POST['dtime']; $gifts=$_POST['gifts']; $gifts=$_POST['gifts'];



if(function_exists('date_default_timezone_set')) {
date_default_timezone_set("Asia/Kolkata");
}



if($ddate==''){  $data['error'] = 'Pick a date' ;$this->_ship_inc($data);}
else{


			//make sure session is not empty
			if($this->cart->total_items())
			{ 
								
				//if there are form validation errors
				//if ($this->form_validation->run() === FALSE)
			//	{
					//$this->_ship_inc($data);
			//	}
				//else
			//	{ 
					/**
					*	save detials to `shop_shipdetails` and to `shop_order`	
					*/
					
					date_default_timezone_set('Asia/Kolkata');



					$order_id = $this->_maxorderid_plus_one(); 

					//$user_id = $this->_userid() ; 
					
					$batch_det = array() ;
					
					//retrieve session details and save to `shop_order`
					foreach($this->cart->contents() as $item)
					{
						
						$prod_det = $this->Db_model->get_one('shop_product',array('aid'=>$item['id']));
						
						if($prod_det!==FALSE)
						{
							//$prod_cat = $prod_det->category_id;
							$prod_subcat = $prod_det->subcategory_id;
						}	
						else
						{
							//$prod_cat = 0;
							$prod_subcat = 0;
						}
							
							//echo $item['subtotal'];
							
							//if($item['subtotal']<1000.00){$finaltotal=$item['subtotal']+100;} else {$finaltotal=$item['subtotal'];} echo $finaltotal;
							
							
						$batch_det[] = array(
										  'order_id' => $order_id,
										 // 'user_id' => $user_id,
										  'prod_id' => $item['id'],
										  'prod_name' => $item['name'],
										 
										 // 'prod_cat' => $prod_cat,
										  'prod_subcat' => $prod_subcat,
										  'prod_price' => $item['price'],
										  'prod_qty' => $item['qty'],
										  'subtotal' => $item['subtotal']
										   ) ;
						
					}
					
					if($this->Db_model->insert_batch('shop_order',$batch_det)===TRUE)
						$order_inserted = 1;						
					else
						$order_inserted = 0;
						
						
						
					$stat = $this->Db_model->get_one('shop_shipping',array('id'=>$this->input->post('area'))) ;
					
					
					//if($item['subtotal']<1000.00){$final=100;} else {$final=0;} 
					
					if($stat!==FALSE)
					{
						$ship_charge = $stat->cost ;
					}
					else
					{
						$ship_charge = 0 ;
					}
					
					
					//save shipping details to `shop_shipdetails`
					$ship_det = array(
									  'order_id'=>$order_id,
									//  'user_id'=>$user_id,
									  'name'=>$this->input->post('name',TRUE),
									  'address'=>$this->input->post('address',TRUE),
									  'pin'=>$this->input->post('pin',TRUE),
									  'address'=>$this->input->post('address',TRUE),
									  'landmark'=>$this->input->post('landmark',TRUE),
									  'city'=>$this->input->post('city',TRUE),
									  'state'=>$this->input->post('state',TRUE),
									 // 'area'=>$this->input->post('area',TRUE),
									  'tel'=>$this->input->post('tel',TRUE),
									   'gst'=>$this->input->post('gst',TRUE),
									  'mobile'=>$this->input->post('mobile',TRUE),
									  'ddate'=>$this->input->post('ddate',TRUE),
									  'dtime'=>$this->input->post('dtime',TRUE),
									  'order_date' => date('Y-m-d H:i:s'),
									  'gifts'=>$this->input->post('gifts',TRUE),
									  'post'=>$this->input->post('post',TRUE),
									  'dtype'=>$this->input->post('dtype',TRUE),
									 // 'giftmsg'=>$this->input->post('giftmsg',TRUE),
									'ship_charge' => $this->input->post('ship_charge',TRUE),
									  'status' => 'P' // P means pending
									  );
									  
									  
					$checkoutusers = array(
									  
									  'name'=>$this->input->post('name',TRUE),
									  'shaddress'=>$this->input->post('address',TRUE),
									  'shpin'=>$this->input->post('pin',TRUE),
									  'landmark'=>$this->input->post('landmark',TRUE),
									  'city'=>$this->input->post('city',TRUE),
									  'state'=>$this->input->post('state',TRUE),
									  'ddate'=>$this->input->post('ddate',TRUE),
									  'dtime'=>$this->input->post('dtime',TRUE),
									 // 'area'=>$this->input->post('area',TRUE),
									  'shtel'=>$this->input->post('tel',TRUE),
									  'sgst'=>$this->input->post('gst',TRUE),
									  'shmobile'=>$this->input->post('mobile',TRUE),
									  'gifts'=>$this->input->post('gifts',TRUE),
									  'post'=>$this->input->post('post',TRUE),
									  // 'dtype'=>$this->input->post('dtype',TRUE),
									 // 'giftmsg'=>$this->input->post('giftmsg',TRUE),
									  
									  );				  
					             					
				
					if($this->Db_model->insert('shop_shipdetails',$ship_det)!==FALSE)
						$ship_inserted = 1;		
										
					else
						$ship_inserted = 0;	
						
						
					
					/**
					*	make sure details inserted to `shop_order` & `shop_shipdetails`
					*	else delete the inserted rows corresponding to order_id
					*/
					//echo $order_inserted; echo $ship_inserted;
					if($order_inserted==1 && $ship_inserted==1)	
					{
											
					
				
						
					//	$amail_status = $this->_send_ordermail('hello@novelkart.com',$order_id,'A');
						
						
						//mail successfully sent to admin & customer
						if($amail_status)
						{
							//empty cart
							
							
							
							
							
							
						$this->cart->destroy();
							
				          //  $this->Db_model->update('shop_checkoutusers',$checkoutusers,array('id'=>$this->_userid(),'email'=>$this->user));
							//$data['suc_msg'] = 'Order details have been sent successfully.' ;
							
							$this->_ship_inc($data);
						
						//	$this->output->set_header('refresh:2;url=Payment'); 
						if($gifts==2) { redirect('Quick_order/order_detailspay/'.$order_id.''); }
						else { redirect('Quick_order/order_detailspay/'.$order_id.'');}
						}
						
						//problem on sending mail
						else
						{
							//delete data from shop_order corresponding to order_id
							//$this->Db_model->delete('shop_order',array('order_id'=>$order_id));
							
							//delete data from shop_order corresponding to order_id
							//$this->Db_model->delete('shop_shipdetails',array('order_id'=>$order_id));
						
							//$data['error'] = 'Problem on sending mail, Try again.' ;
							
							$this->_ship_inc($data);
							
							
							
							
							
							
							
							
							
							
							
						$this->cart->destroy();
							
							
							
							
							
							
							
							
							
							
							
							
							$data['suc_msg'] = 'Novel: Order details has been sent successfully.' ;
							
							$this->_ship_inc($data);
						
							//$this->output->set_header('refresh:5;url=userpage/vieworders'); 
							//$this->output->set_header('refresh:2;url=Payment');
						
						if($gifts==2) { redirect('Quick_order/order_detailspay/'.$order_id.''); }
						else { redirect('Quick_order/order_detailspay/'.$order_id.'');}
						
						}
						
						 
					}
					
					
					/**
					*	if order details OR shipping details not inserted
					*/
					
					else
					{
						//delete data from shop_order corresponding to order_id
						$this->Db_model->delete('shop_order',array('order_id'=>$order_id));
						
						//delete data from shop_order corresponding to order_id
						$this->Db_model->delete('shop_shipdetails',array('order_id'=>$order_id));
						
						$data['error'] = 'Error occured try again.' ;
						
						$this->_ship_inc($data);
					}
					
					
				//}
			
			}
			else
			{
				$data['error'] = 'Your cart is empty .' ;
				$this->_ship_inc($data);
			}
			
		}}
		else
		{
			/**
			*
			*	show login form at first time page loads,
			*	ie, before clicking submit button
			*
			*/
			
			$this->_ship_inc($data);			
		}
		
		
	}
	
	
	
	public function order_detailspay($order_id='')
	{
	
	$data = array(
				'cart_qty'=>$this->cart_qty,	  
				'user' => $this->user,
				'email' => $this->user,
				'logged' => $this->logged,
				'capimage' => $capimage,
				//'c_val' => $this->encrypt->encode($cap_result),
				'suc_msg' => '',
			'result' => '',
			'result2' => '',
				'offer' => '',
				'error' => ''
				);
	
	 
		 $data['category']=$data['result'] = $this->Db_model->get_where_by_order('shop_category',array('gift'=>1),'order','asc') ;	
		$data['gift'] = $this->Db_model->get_where_by_order('shop_category',array('gift'=>2),'order','asc') ;
        $data['allproduct']= $this->Db_model->get_where_by_order('shop_product',array('active'=>'Y'),'order','asc') ;
		$data['site'] = $this->Db_model->get_all('site',array()) ;
		$data['result2'] = $this->Db_model->get_where('shop_order',array('order_id'=>$order_id));
		
		$data['contactus'] = $this->Db_model->get_where_by_order('shop_contact',array('status'=>'1'),'id','desc') ;
		
		$data['product'] = $this->Db_model->get_where('shop_product',array('active'=>'Y'));
		$data['shipdetails'] = $ship_det = $this->Db_model->get_one('shop_shipdetails',array('order_id'=>$order_id));
		//$data['category'] = $this->Db_model->get_all_by_order('shop_category','order','asc') ;
        //$data['area'] = $this->_getarea($ship_det->area) ;	
	 
	
		$this->load->view('website/header',$data);
		$this->load->view('website/menu',$data); 
		$this->load->view('website/order_detailspay2',$data);
		 $this->load->view('website/footer');
	}
	
		
	private function _ship_inc($data=array())
	{
		$this->load->view('website/header',$data);
		$this->load->view('website/menu',$data);
		$this->load->view('website/shipping_form',$data);
		$this->load->view('website/footer');
	}
	
	
		private function _maxorderid_plus_one()
	{
		if($this->Db_model->max_orderid()!==FALSE)
		{
			$det = $this->Db_model->max_orderid();
			$order_id = $det->order_id + 1 ;
		}
		else
		{
			$order_id = 1 ;
		}
		
		return $order_id ;
	}
	
	

}
