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

class Dashboard extends CI_Controller {
	function __Construct(){
		parent::__Construct();
		if(!isset($_SESSION['USERS_DATA'])){
			redirect(base_url("login"));
		}
		$this->load->library('ts_functions');
		$this->load->helper('text');
	
	}
	
	public function index(){
	   
	   if(!empty($_SESSION['USERS_DATA']) && $_SESSION['USERS_DATA']['userType'] ==1){
	    
    	    $data['customer'] = $this->my_model->select_data('*' , 'users',array('userType' => 2,'status'=>1),'','');
    	    $data['wholesaler'] = $this->my_model->select_data('*' , 'users',array('userType' => 3,'status'=>1),'','');
    	    $data['items'] = $this->my_model->select_data('*' , 'sub_categories',array('itemStatus' => 1),'','');
    	    $data['orders'] = $this->my_model->select_data('*' , 'wholesale_item_invoice',array('deliveryStatus' => 0),'','');
    	     
	   }else{
	        $userId = $_SESSION['USERS_DATA']['userId'];
	        $data['items'] = $this->my_model->select_data('*' , 'sub_categories',array('itemStatus' => 1,'partyId'=>$userId),'','');
    	    $data['orders'] = $this->my_model->select_data('*' , 'wholesale_item_invoice',array('deliveryStatus' => 0,'vendorId'=>$userId),'','');
	   }
	    $data['title']="Dashboard";
	    $dataPoints = array();
	    for ($x = 14; $x >= 0; $x--) {
	      $today = date('Y-m-d');     
          $date = strtotime(date("Y-m-d", strtotime($today)) . " -$x day");
         
          $strtotime = intval($date."000");
          $updatedate = date('Y-m-d', $date);
          $condd ="totalAmount>0 AND saleDate ='$updatedate'";  
          if(!empty($_SESSION['USERS_DATA']) && $_SESSION['USERS_DATA']['userType'] ==1){
            $totalOrders = count($this->my_model->select_data('*' , 'wholesale_item_invoice',$condd,'',array('createdAt','DESC')));
              
          }else{
            $userId = $_SESSION['USERS_DATA']['userId'];
            $condd ="totalAmount>0 AND saleDate ='$updatedate' AND vendorId='$userId'";  
            $totalOrders = count($this->my_model->select_data('*' , 'wholesale_item_invoice',$condd,'',array('createdAt','DESC')));
          }
          $dataPoints[] = array(
                              "x" => $strtotime ,
                              "y" => $totalOrders
                              );
        }
       
        $data['active'] ="dashboard";
        $data['dataPoints']= $dataPoints; 
		$this->load->view('header',$data);
		$this->load->view('sidebar',$data);
		$this->load->view('dashboard',$data);
		$this->load->view('footer',$data);
		 
	} 
	
	/*====== Item Section Start ===========*/
	public function items_master($id=null){ 
	    $data['title']="Items";
	    $data['active'] ="Items";
		$this->load->view('header',$data);
		$this->load->view('sidebar',$data);
		
		$data['userId'] = $id;
		$data['categories'] = $this->my_model->select_data('*' , 'categories','','',array('catName','ASC'));
		$data['item_unit'] = $this->my_model->select_data('*' , 'item_unit','','',array('unitName','ASC'));
		if(!empty($_SESSION['USERS_DATA']) && $_SESSION['USERS_DATA']['userType'] ==1){
    		if(!empty($id)){
    		    if(is_numeric($id)){
    		        $items = $this->my_model->select_data('*' , 'sub_categories',array('partyId' => $id),'',array('stockQnt','ASC'));
    		    }else{
    		        $cond = "subCatName LIKE '%$id%'";
        		    $items = $this->my_model->select_data('*' ,'sub_categories',$cond);
        		    
    		    }
    		}
		}else{
		    $userId = $_SESSION['USERS_DATA']['userId'];
		    $data['userId'] =$userId;
		    $items = $this->my_model->select_data('*' , 'sub_categories',array('partyId' => $userId),'',array('stockQnt','ASC'));
		}
    
      // print_r($items);
      // die();
	   if(!empty($items)){ 
		foreach($items as $key =>$value){
		    $cat_id = $value['mainCatId'];
		    $saler_id = $value['partyId'];
		    
		    $where = array(
			               'catId'    => $cat_id
						   );
		    $categories = $this->my_model->select_data('*','categories', $where);
		    if($categories){
		        $items[$key]['catName']=$categories[0]['catName'];
		    }else{
		        $items[$key]['catName']="";
		    }
		    
		    $where = array(
			               'userId'    => $saler_id,
			               'userType'=>3
						   );
		    $users = $this->my_model->select_data('*','users', $where);
		    if($users){
		        $items[$key]['userName']=$users[0]['userName'];
		    }else{
		        $items[$key]['userName']="";
		    }
		}
		//echo"<pre>";
		//print_r($items);
		//die();
		$data['allitems'] = $items;
	   }
		$data['wholesaler'] = $this->my_model->select_data('*' , 'users' , array('userType' => 3,'status'=>1),'',array('userName','ASC'));
		$this->load->view('master/items',$data);
		$this->load->view('footer');
	}
	
	public function create_item(){
		  if(isset($_POST['ItemName']) && !empty($_POST['ItemName'])){
		      
		     $update_Arr =  array('subCatName' =>$_POST['ItemName'],
		                          'stockQnt' => $_POST['ItemMinStock'],
		                          'qntUnit'=> $_POST['stock_unit'],
		                          'rate'=>$_POST['retailRate'],
		                          'itemMrp'=>$_POST['retaiMrplRate'],
		                          'partyId'=>$_POST['wholesalerId'],
		                          'itemStockWeight'=>$_POST['ItemWeight'],
		                          'mainCatId'=>$_POST['categoryId'],
		                          );
	        if(isset($_FILES['ItemImage']['name']) && !empty($_FILES['ItemImage']['name'])){
				$ItemImage = $this->upload_image('/assets/uploads/' , 'ItemImage' );	
				$update_Arr['image'] = $ItemImage; 
			}
			if(isset($_POST['ItemUpdateId']) && !empty($_POST['ItemUpdateId'])){
			     
				$this->my_model->update_data_limit('sub_categories' ,$update_Arr,array('subCatId' => $_POST['ItemUpdateId']), 1); 
				$resp = array('status' => 1 ,'redirect' => 'master/items','msg'=>'Successfully updated');
			}else{
			    $where = array(
			               'subCatName' =>$_POST['ItemName'],
			               'mainCatId'=>$_POST['categoryId'],
			               'partyId'=>$_POST['wholesalerId']
			              
						   );
		        $item_dete = $this->my_model->select_data('*','sub_categories', $where);
		        if(empty($item_dete)){
				$this->my_model->insert_data('sub_categories' ,$update_Arr); 
				$resp = array('status' => 1 ,'redirect' => 'master/items','msg'=>'Added successfully');
		        }else{
		            $resp = array('status' => 0 , 'error' => 'You already have this item.');
		        }
			}  
		}else{ 
			$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
		}
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	
	public function edit_item(){ 
		if(isset($_POST['itemId']) && !empty($_POST['itemId'])){
			$itemId = $_POST['itemId'];
			$itemData = $this->my_model->select_data('*' , 'sub_categories' , array('subCatId' => $itemId),'1');
			if(!empty($itemData)){
				$resp = array('status' => 1 , 'itemdata' => $itemData[0]);
			}else{
				$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
			} 
		}else{
			$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
		}
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	
	public function delete_item(){
		if(isset($_POST['itemId']) && !empty($_POST['itemId'])){
			$this->my_model->delete_data('sub_categories' , array('subCatId' => $_POST['itemId'])); 
			$resp = array('status' => 1 ,'redirect' => 'master/items','msg'=>'Successfully deleted');
		}else{ 
			$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
		} 
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	
	public function delete_categories(){
		if(isset($_POST['itemId']) && !empty($_POST['itemId'])){
		    $where = array(
			               'mainCatId'=>$_POST['itemId']
						   );
	        $catData = $this->my_model->select_data('*','sub_categories', $where);
	        if(empty($catData)){
	            $this->my_model->delete_data('categories' , array('catId' => $_POST['itemId'])); 
			    $resp = array('status' => 1 ,'redirect' => 'dashboard/category','msg'=>'Successfully deleted');
	        }else{
	            $resp = array('status' => 0 , 'error' => 'category already exists for item list.');
	        }
			
		}else{ 
			$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
		} 
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	/*====== Item Section End ===========*/	
	
	
	
	function upload_image($upPath , $name , $postFix = NULL){
		$this->CI = get_instance();
		$basePath = explode('application',dirname(__FILE__))[0];
		$uploadPath = $basePath.$upPath; 
		$config['upload_path'] = $uploadPath;
		$config['allowed_types'] = '*';
		$this->CI->load->library('upload', $config);
		if ($this->CI->upload->do_upload($name)){
			//$this->upload->display_errors();	
			$uploaddata = $this->CI->upload->data();
			$imgName = $uploaddata['raw_name'];
			$imgExt = $uploaddata['file_ext'];
			$randomstr = substr(md5(microtime()), 0, 10);
			$uploadedImage = $randomstr.$postFix.$imgExt;
			rename($uploadPath.$imgName.$imgExt, $uploadPath.$uploadedImage);
			return $uploadedImage;
		}else{ 
			return '';
		}
	}
	
	/*====== Category Section End ===========*/	
	public function category(){ 
	    
	    $data['title'] ="Categories";
	    $data['active'] ="Categories";
		$this->load->view('header',$data);
		$this->load->view('sidebar',$data);
		$data['categories'] = $this->my_model->select_data('*' , 'categories','','',array('catId','DESC'));
		$this->load->view('master/item_category',$data);
		$this->load->view('footer');
	}
	
	public function create_catigory(){
		  if(isset($_POST['ItemName']) && !empty($_POST['ItemName'])){
		      
		     $update_Arr =  array('catName' => html_escape($_POST['ItemName'])
		                          );
	        if(isset($_FILES['ItemImage']['name']) && !empty($_FILES['ItemImage']['name'])){
				$ItemImage = $this->upload_image('/assets/uploads/' , 'ItemImage' );	
				$update_Arr['catImage'] = html_escape($ItemImage); 
			}
// 			print_r($update_Arr);
// 			die();
		    if(isset($_POST['ItemUpdateId']) && !empty($_POST['ItemUpdateId'])){
			     
			    $where = array(
			               'catName'=>html_escape($_POST['ItemName']),
			               'catId !=' =>html_escape($_POST['ItemUpdateId'])
						   );
		        $itemData = $this->my_model->select_data('*','categories', $where);
		        if(empty($itemData)){
    				
    				$this->my_model->update_data_limit('categories' ,$update_Arr,array('catId' => $_POST['ItemUpdateId']), 1); 
    				$resp = array('status' => 1 ,'redirect' => 'dashboard/category','msg'=>'Successfully updated');
			    }else{
			        $resp = array('status' => 0 , 'error' => 'Category name already exists.');
			    }
		        
			}else{ 
			    
			    $where = array(
			               'catName'=>html_escape($_POST['ItemName'])
						   );
		        $itemData = $this->my_model->select_data('*','categories', $where);
			    if(empty($itemData)){
				$this->my_model->insert_data('categories' ,$update_Arr); 
				$resp = array('status' => 1 ,'redirect' => 'dashboard/category','msg'=>'Successfully created');
			    }else{
			        $resp = array('status' => 0 , 'error' => 'Category name already exists.');
			    }
			}
		}else{ 
			$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
		}
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	
	public function edit_catigory(){ 
		if(isset($_POST['itemId']) && !empty($_POST['itemId'])){
			$itemId = $_POST['itemId'];
			$itemData = $this->my_model->select_data('*' , 'categories' , array('catId' => $itemId),'1');
			if(!empty($itemData)){
				$resp = array('status' => 1 , 'itemdata' => $itemData[0]);
			}else{
				$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
			} 
		}else{
			$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
		}
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	
	public function delete_catigory(){
		if(isset($_POST['itemId']) && !empty($_POST['itemId'])){
			$this->my_model->delete_data('sub_categories' , array('subCatId' => $_POST['itemId'])); 
			$resp = array('status' => 1 ,'redirect' => 'master/items','msg'=>'Successfully deleted');
		}else{ 
			$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
		} 
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	
	public function catStatus(){
		
		if(isset($_POST['UserId']) && !empty($_POST['UserId']))
		{  
	        $user_id = $_POST['UserId'];
	        $status = $_POST['status'];
			
    		    $where = array(
    			               'catId'    => $user_id
    						   );
    		$userData = $this->my_model->select_data('*','categories', $where);
    		    
			if(!empty($userData))
			{   
			   
			    $data = array(
			              'cat_status'=>$status
			            );
			    $this->my_model->update_data('categories' ,$data, array('catId'=>$user_id));	
			    $resp = array('status' => 1 , 'msg' => 'Successfully updated.');
			}else{
				$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
			}
		}else{
			$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
		}
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	
	
	/*====== catigory Section End ===========*/	
	
	/*====== search form start ===========*/	
		public function search_form($search_item=null,$other=null){
		   
		    $this->load->view('header');
    		$this->load->view('sidebar');
            //print_r($search_item);
            //print_r($other);
            //die();
		    if($other=="items"){
		        $cond = "subCatName LIKE '%$search_item%'";
    		    //$categories = $this->my_model->select_data('*' ,'categories',$cond);
    		    //$data['userId'] = $id;
        		$data['categories'] = $this->my_model->select_data('*' , 'categories','','',array('catId','DESC'));
        		
        		//$items = $this->my_model->select_data('*' , 'sub_categories',array('partyId' => $id),'',array('subCatId','DESC'));
        		$items = $this->my_model->select_data('*' , 'sub_categories','','',array('subCatId','DESC'));
        		
        		foreach($items as $key =>$value){
        		    $cat_id = $value['mainCatId'];
        		    $saler_id = $value['partyId'];
        		    
        		    $where = array(
        			               'catId'    => $cat_id
        						   );
        		    $categories = $this->my_model->select_data('*','categories', $where);
        		    if($categories){
        		        $items[$key]['catName']=$categories[0]['catName'];
        		    }else{
        		        $items[$key]['catName']="";
        		    }
        		    
        		    $where = array(
        			               'userId'    => $saler_id,
        			               'userType'=>3
        						   );
        		    $users = $this->my_model->select_data('*','users', $where);
        		    if($users){
        		        $items[$key]['userName']=$users[0]['userName'];
        		    }else{
        		        $items[$key]['userName']="";
        		    }
        		}
        		//echo"<pre>";
        		//print_r($items);
        		//die();
        		$data['allitems'] = $items;
        		$data['wholesaler'] = $this->my_model->select_data('*' , 'users' , array('userType' => 3,'status'=>1),'',array('userId','DESC'));
        		$this->load->view('master/items',$data);
        		        
		    }else if($other=="wholesaler"){
		        $cond = "userName LIKE '%$search_item%' AND userType = 3 AND status= 1";
    		    $data['customer'] = $this->my_model->select_data('*' ,'users',$cond);
		        $this->load->view('users/wholesaler',$data);
		    }else if($other=="customers"){
		        $cond = "userName LIKE '%$search_item%' AND userType = 2 AND status= 1";
    		    $data['customer'] = $this->my_model->select_data('*' ,'users',$cond);
		        $this->load->view('users/customer',$data);
		    }else{
    		    $cond = "subCatName LIKE '%$search_item%' AND itemStatus = 1";
    		    $items = $this->my_model->select_data('*' ,'sub_categories',$cond); 
    		    if($items){
                    $data['categories'] = $this->my_model->select_data('*' , 'categories','','',array('catId','DESC'));
            		foreach($items as $key =>$value){
            		    $cat_id = $value['mainCatId'];
            		    $saler_id = $value['partyId'];
            		    
            		    $where = array(
            			               'catId'    => $cat_id
            						   );
            		    $categories = $this->my_model->select_data('*','categories', $where);
            		    if($categories){
            		        $items[$key]['catName']=$categories[0]['catName'];
            		    }else{
            		        $items[$key]['catName']="";
            		    }
            		    
            		    $where = array(
            			               'userId'    => $saler_id,
            			               'userType'=>3
            						   );
            		    $users = $this->my_model->select_data('*','users', $where);
            		    if($users){
            		        $items[$key]['userName']=$users[0]['userName'];
            		    }else{
            		        $items[$key]['userName']="";
            		    }
            		}
            		//echo"<pre>";
            		//print_r($items);
            		//die();
            		$data['allitems'] = $items;
            		$data['wholesaler'] = $this->my_model->select_data('*' , 'users' , array('userType' => 3,'status'=>1),'',array('userId','DESC'));
            		$this->load->view('master/items',$data);
    		    }else{
    		        $this->load->view('master/items');
    		    }
		    }
		    
	    	$this->load->view('footer');
		}
		
	/*====== search form end ===========*/	
	/*====== Item unit Section start ===========*/	
	public function item_unit(){ 
	    
	    $data['title'] ="Item Unit";
	    $data['active'] ="ItemUnit";
		$this->load->view('header',$data);
		$this->load->view('sidebar',$data);
		$data['unitdetail'] = $this->my_model->select_data('*' , 'item_unit','','',array('unitName','ASC'));
		$this->load->view('master/item_unit',$data);
		$this->load->view('footer');
	}
	
	public function create_unit(){
		  if(isset($_POST['UnitName']) && !empty($_POST['UnitName'])){
		      
		     $update_Arr =  array('unitName' =>$_POST['UnitName']
		                          );
	        
		    if(isset($_POST['ItemUnitId']) && !empty($_POST['ItemUnitId'])){
			     
			    $where = array(
			               'unitName'=>$_POST['UnitName'],
			               'unitId !=' => $_POST['ItemUnitId']
						   );
		        $itemData = $this->my_model->select_data('*','item_unit', $where);
		        if(empty($itemData)){
    				
    				$this->my_model->update_data_limit('item_unit' ,$update_Arr,array('unitId' => $_POST['ItemUnitId']), 1); 
    				$resp = array('status' => 1 ,'redirect' => 'dashboard/item_unit','msg'=>'Successfully updated');
			    }else{
			        $resp = array('status' => 0 , 'error' => 'Item unit name already exists.');
			    }
		        
			}else{ 
			    
			    $where = array(
			               'unitName'=>$_POST['UnitName']
						   );
		        $itemData = $this->my_model->select_data('*','item_unit', $where);
			    if(empty($itemData)){
				$this->my_model->insert_data('item_unit' ,$update_Arr); 
				$resp = array('status' => 1 ,'redirect' => 'dashboard/item_unit','msg'=>'Successfully created');
			    }else{
			        $resp = array('status' => 0 , 'error' => 'Item unit name already exists.');
			    }
			}
		}else{ 
			$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
		}
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	
	public function edit_unit(){ 
		if(isset($_POST['itemId']) && !empty($_POST['itemId'])){
			$itemId = $_POST['itemId'];
			$itemData = $this->my_model->select_data('*' , 'item_unit' , array('unitId' => $itemId),'1');
			if(!empty($itemData)){
				$resp = array('status' => 1 , 'itemdata' => $itemData[0]);
			}else{
				$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
			} 
		}else{
			$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
		}
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
		/*====== Item unit Section and ===========*/	
}