<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Eshanya extends CI_Controller {
	public function __construct()
	{
		parent::__construct();
		$this->load->database();
		$this->db2 = $this->load->database('otherdb', TRUE);
		$this->db3 = $this->load->database('otherdb1', TRUE);
		$this->load->library('session');
		$this->load->model('user_model');
		$this->load->model('master_model');
		$this->load->model('eshanya_model');
		$this->load->model('report_model');
		if(!isset($_SESSION['user_logged'])) {
			$this->session->set_flashdata("error", "please login first to view dashboard");
			redirect("Login/login");
		}
	}
	var $master_url='https://cake-master.com/inv_mod';
	public function recipeCategory($sub_mod_id)
	{
		$user_id = $_SESSION['user_id'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['thead_permission'] = $this->user_model->get_thead_permission($user_id,$sub_mod_id);
		$data['submod_id']=$sub_mod_id;
	    $data['moduleName']='Product';
		$data['sub_ModuleName']='Category Entry';
		$data['productCategory'] = $this->eshanya_model->getProductCategory();
		$data['combination'] = $this->eshanya_model->getCombination();
		$data['counter'] = $this->eshanya_model->get_CounterUser();
		$this->load->view('Eshanya/Master/categoryEntry',$data);
	}
	
	public function recipeCategoryInsert(){
		$this->eshanya_model->addRecipeCategory($this->input->post());
		$sub_mod_id = $this->input->post('sub_mod_id');
		redirect('Eshanya/recipeCategory/'.$sub_mod_id);
	}
	
	public function recipeCatEdit($sub_mod_id,$pr_cat_id){
		$user_id = $_SESSION['user_id'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['thead_permission'] = $this->user_model->get_thead_permission($user_id,$sub_mod_id);
		$data['submod_id']=$sub_mod_id;
		$data['moduleName']='Product';
		$data['sub_ModuleName']='Category Updation';
		$data['cat_view'] = $this->eshanya_model->getRecipeCategoryId($pr_cat_id);
		$data['combination'] = $this->eshanya_model->getCombination();
		$data['counter'] = $this->eshanya_model->get_CounterUser();
		$this->load->view('Eshanya/Master/editPrCategory',$data);
	}
	
	public function prCat_update($pr_cat_id){
		
		$user_id = $_SESSION['user_id'];
		
		$pr_cat_name= $this->input->post('pr_cat_name');
		$effective_from= date('Y-m-d',strtotime($this->input->post('effective')));
		$combination= $this->input->post('combination');
		$qty_limit= $this->input->post('qty_limit');
		$sub_mod_id= $this->input->post('sub_mod_id');
		//$fdelivery= $this->input->post('fdelivery');
		//$applicable= $this->input->post('applicable');
		$cbranch = $this->input->post('cbranch');
		$cbranch_code = $this->input->post('$cbranch_code');
		$cbranch_id = $this->input->post('$cbranch_id');
		
		$crt_date = date('Y-m-d H:i:s');
		
		if(!empty($combination))
		{
		    $comb = implode(',',$combination);
		}
		else
		{
		    $comb = '';
		}
		
		if($this->input->post('effective') == '')
		{
		    $effect_from = '';
		}
		else
		{
		    $effect_from = date('Y-m-d',strtotime($this->input->post('effective')));
		}
		$data1 = array(
			'pr_cat_name' => $pr_cat_name,
			'effective_from' => $effect_from,
			//'applicable_for' => $applicable,
			'combination' => $comb,
			'combo_qty_limit' => $qty_limit,
			//'social_order' => $fdelivery
		);
		$this->db->where('pr_cat_id',$pr_cat_id);
		$this->db->update('EshProduct_category',$data1);
		
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['thead_permission'] = $this->user_model->get_thead_permission($user_id,$sub_mod_id);
		$data['submod_id']=$sub_mod_id;
		$data['productCategory'] = $this->eshanya_model->getProductCategory();
		redirect('Eshanya/recipeCategory/'.$sub_mod_id);
	}
	
	public function rccategoryDelete($sub_mod_id,$pr_cat_id){
		$user_id = $_SESSION['user_id'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['thead_permission'] = $this->user_model->get_thead_permission($user_id,$sub_mod_id);
		$data['submod_id']=$sub_mod_id;
		$this->db->query("delete from eshRecipe where pr_cat_id='$pr_cat_id'");
		$this->db->query("delete from EshProduct_category where pr_cat_id='$pr_cat_id'");
		redirect('Eshanya/recipeCategory/'.$sub_mod_id);
	}
	
	public function change_prcat_status(){
		$this->db2 = $this->load->database('otherdb', TRUE);
		$cat_id = $this->input->post('cat_id');
		$status = $this->input->post('cat_status');
		$effective = $this->input->post('effective');
		
		$effective_date = date('Y-m-d',strtotime($effective));
		if($status == 'Enabled')
		{
			$cat_status = 'Active';
		}
		else
		{
			$cat_status = 'InActive';
		}
		
		if($status != ''){
			$this->db->query("update eshRecipe set status='$status',status_effective='$effective_date' where pr_cat_id='$cat_id'");
			
			$this->db->query("update EshProduct_category set status='$status',effective_from='$effective_date' where pr_cat_id='$cat_id'");
		
			echo 1;
		}else{
			echo 0;
		}
	}
	
	public function recipeEntry()
	{
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['category'] = $this->eshanya_model->get_Category();
		$data['tax'] = $this->eshanya_model->get_Tax();
		$data['kitchen'] = $this->eshanya_model->get_KitchenUser();
		$data['chef'] = $this->eshanya_model->get_Chef();
		$data['counter'] = $this->eshanya_model->get_CounterUser();
		$data['branch'] = $this->user_model->get_branch();
		$data['items'] = $this->eshanya_model->get_RcpItems();
		$data['products'] = $this->eshanya_model->get_Products($branch_id);
		$data['combination'] = $this->eshanya_model->getCombination();
		$this->load->view('Eshanya/Master/eshProduct',$data);
	}
	
	
	public function addEshProduct()
	{
		$this->eshanya_model->addProduct($this->input->post());
		redirect('Eshanya/recipeEntry');
	}
	
	public function productList($sub_mod_id)
	{
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['thead_permission'] = $this->user_model->get_thead_permission($user_id,$sub_mod_id);
		$data['products'] = $this->eshanya_model->getProducts($branch_id);
		$this->load->view('Eshanya/Master/eshProduct_list',$data);
	}
	
	public function cproductList($sub_mod_id)
	{
		$user_id = $_SESSION['user_id'];
		$branch_id = 34;
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['thead_permission'] = $this->user_model->get_thead_permission($user_id,$sub_mod_id);
		$data['products'] = $this->eshanya_model->getProducts($branch_id);
		$this->load->view('Eshanya/Master/product_Clist',$data);
	}
	
	public function productApprove()
	{
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		//$data['thead_permission'] = $this->user_model->get_thead_permission($user_id,$sub_mod_id);
		$data['products'] = $this->eshanya_model->getApproveProducts();
		$this->load->view('Eshanya/Master/product_approve',$data);
	}
	
	public function productApproveView($id)
	{
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['product'] = $this->eshanya_model->getProductDetails($id);
		$data['category'] = $this->eshanya_model->get_Category();
		$data['tax'] = $this->eshanya_model->get_Tax();
		$data['kitchen'] = $this->eshanya_model->get_KitchenUser();
		$data['chef'] = $this->eshanya_model->get_Chef();
		$data['sales_price'] = $this->master_model->get_CounterSalesPrice($id);
		$data['branch'] = $this->user_model->get_branch();
		$data['rcpbranch'] = $this->eshanya_model->get_rcpbranch();
		$data['counter'] = $this->eshanya_model->get_CounterUser();
		$data['santhe'] = $this->master_model->get_SantheUser();
		$data['recipe_items'] = $this->eshanya_model->get_RecipeItems($id);
		$data['sub_recipe_items'] = $this->eshanya_model->get_SubRecipeItems($id);
		$data['combination'] = $this->eshanya_model->getCombination();
		$this->load->view('Eshanya/Master/product_approve_view',$data);
	}
	
	public function productEdit($id,$rc_no)
	{
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['moduleName']='Product';
		$data['sub_ModuleName']='Product Updation';
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['product'] = $this->eshanya_model->getProductDetails($id);
		$data['category'] = $this->eshanya_model->get_Category();
		$data['tax'] = $this->eshanya_model->get_Tax();
		$data['kitchen'] = $this->eshanya_model->get_KitchenUser();
		$data['chef'] = $this->eshanya_model->get_Chef();
		
		$data['branch'] = $this->user_model->get_branch();
		$data['pbranch'] = $this->eshanya_model->getProductBranch($rc_no);
		$data['rcpbranch'] = $this->eshanya_model->get_rcpbranch();
		$data['counter'] = $this->eshanya_model->get_CounterUser();
		$data['santhe'] = $this->master_model->get_SantheUser();
		$data['recipe_items'] = $this->eshanya_model->get_RecipeItems($id);
		$data['sub_recipe_items'] = $this->eshanya_model->get_SubRecipeItems($id);
		$data['items'] = $this->eshanya_model->get_eshItems();
		$data['products'] = $this->eshanya_model->get_Products($branch_id);
		$data['combination'] = $this->eshanya_model->getCombination();
		$this->load->view('Eshanya/Master/product_edit',$data);
	}
	
	public function productView($id)
	{
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		//$data['thead_permission'] = $this->master_model->get_thead_permission($user_id,$sub_mod_id);
		$data['products'] = $this->eshanya_model->getProducts($branch_id);
		$this->load->view('Eshanya/Master/product_list',$data);
	}
	
	public function updateProduct(){
		$this->eshanya_model->updateProduct($this->input->post());
		redirect('Eshanya/recipeEntry');
	}
/*	public function productUpdate($id)
	{
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		//$data['thead_permission'] = $this->master_model->get_thead_permission($user_id,$sub_mod_id);
		$data['products'] = $this->master_model->getProducts($branch_id);
		$this->load->view('master/product_list',$data);
	}*/
	
	public function approveProduct()
	{
		$this->eshanya_model->approveProduct($this->input->post());
		redirect('Eshanya/productApprove');
	}
	
	public function change_product_status(){
		$this->db2 = $this->load->database('otherdb', TRUE);
		$pr_no = $this->input->post('pr_no');
		$status = $this->input->post('pr_status');
		$effective = $this->input->post('effective');
		
		$effective_date = date('Y-m-d',strtotime($effective));
		if($pr_status == 'Enabled')
		{
			$pr_status = 'Active';
		}
		else
		{
			$pr_status = 'InActive';
		}
		
		if($status != ''){
			$this->db->query("update eshRecipe set status='$status',status_effective='$effective_date' where recipe_no='$pr_no'");
			echo 1;
		}else{
			echo 0;
		}
	}
	
	/*** STOCK UPDATE***/
	public function stock_updateEsh(){
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['moduleName'] = 'Stock Update';
		$data['sub_ModuleName'] = 'Stock Update Entry';
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$this->load->view('Eshanya/Stock_update/stockUpdateEsh',$data);
	}
	
	public function export_Stock(){
		$branchname = $_SESSION['branch_name'];
		$branch_id = $_SESSION['branch_id'];
		
        $filename = 'Month_Stock_Update(RM)_'.$branchname.'_'.date('d-m-Y').'.csv';
       header("Content-Description: File Transfer"); 
       header("Content-Disposition: attachment; filename=$filename"); 
       header("Content-Type: application/csv; ");
       
       // get data 
       $branch_id = $_SESSION['branch_id'];
       $usersData = $this->eshanya_model->getcatdata1($branchname);
    
       // file creation 
       $file = fopen('php://output', 'w');
     
       $header = array("item_id","category_id","category_name","item_name","uom","closing_stk","branch_name"); 
       fputcsv($file, $header);
       foreach ($usersData as $key=>$line){
         fputcsv($file,$line); 
       }
       fclose($file); 
       exit;
	}
	
	public function exportPrStock(){
	    $branchname = $_SESSION['branch_name'];
		$branch_id = $_SESSION['branch_id'];
		
        $filename = 'Month_Stock_Update(FP)_'.$branchname.'_'.date('d-m-Y').'.csv';
       header("Content-Description: File Transfer"); 
       header("Content-Disposition: attachment; filename=$filename"); 
       header("Content-Type: application/csv; ");
       
       // get data 
       $branch_id = $_SESSION['branch_id'];
       $usersData = $this->eshanya_model->getProductDetail($branch_id);
    
       // file creation 
       $file = fopen('php://output', 'w');
     
       $header = array("recipe_id","pr_cat_id","pr_cat_name","product_name","uom","closing_stk","branch_name"); 
       fputcsv($file, $header);
       foreach ($usersData as $key=>$line){
         fputcsv($file,$line); 
       }
       fclose($file); 
       exit;
	}
	
	public function import_RawStock(){
		if(isset($_POST["upload"]))
		{
			$filename=$_FILES["stk_upload"]["tmp_name"];
			if($_FILES["stk_upload"]["size"] > 0)
			{
				$file = fopen($filename, "r");

				$branchname = $_SESSION['branch_name'];
				$branch_id = $_SESSION['branch_id'];
				$user = $_SESSION['full_name'];
				$stk_date = date("Y-m-d");
				$order_time = date("h:i A");
				$lm=date("Y-m-dH:i:s",time());
				$up_type = $this->input->post('up_type');
				
				if($branchname != '')
	            {
				    $rst = $this->db->query("SELECT * FROM stock_update where branchname='$branchname' and stk_date='$stk_date' and update_type='$up_type' and `stock_no` like 'S%'");
				    
				    if($rst->num_rows() > 0)
					{
					    $this->session->set_flashdata('message', 'The stock is aleready uploaded for the month');
				        redirect('Eshanya/stock_updateEsh/');
					}
					else
					{
						$result = $this->db->query("SELECT MAX(stk_no) as stk_no FROM stock_update where branch_id='$branch_id' and `stock_no` like 'S%'");
        				foreach($result->result_array() as $res)
        				$stk_no = $res['stk_no'];
        				if($stk_no == 0){
        					$stkno = 1;
        				}
        				else{
        					$stkno = $stk_no+1;
        				}
        				
        		    	$stock_no = "STKUP"."/".$branchname."/".$stkno;
        		    	$res2 = $this->db->query("insert into stock_update(stk_no,stock_no,stk_date,branchname,user_name,stk_time,branch_id,update_type)values('$stkno','$stock_no','$stk_date','$branchname','$user','$order_time','$branch_id','$up_type')");
        		    	$stck_id = $this->db->insert_id();
        		    	if($stck_id)
        		    	{
        		    	$i=0;
        		    	while (($data = fgetcsv($file, 10000, ",")) !== FALSE)
        				{
        					$res3=$this->db->query("select * from item_creation where item_id='$data[0]'");
        	        		if($res3->num_rows() > 0)
        	        		{
        	        			foreach($res3->result_array() as $res4)
        	        			$stk[$i] = $res4['stock_item'];
        	        			$unitm[$i] = $res4['uom'];
        	        			$itm_id[$i] = $res4['itm_id'];
        	        			$cat_id[$i] = $res4['category_id'];
        					 	
        						$pr=$this->db->query("select * from item_creation where itm_id='$itm_id[$i]' and branchname='ESH'");
        	        			foreach($pr->result_array() as $prs)
        	        			$tax = $prs['item_tax'];
        	        			$iprice = $prs['item_price'];
        	        			$tax_a = ($tax * $iprice)/100;
        	        			$rate = $iprice + $tax_a;
                				$this->db->query("insert into stock_update_item(item_type,item_name,uom,present_stk,closing_stk,stck_id,item_id,cat_id,itm_id,item_price,item_tax,rate)values('Raw Material','$data[3]','$data[4]','$stk[$i]','$data[5]','$stck_id','$data[0]','$cat_id[$i]','$itm_id[$i]','$iprice','$tax','$rate')");
                	
                				$res5 = $this->db->query("update item_creation set stock_item='$data[5]' where item_id='$data[0]'");
                				$this->db->query("insert into stock_detail(item_name,trans_ref_no,transaction_date,opening_stock,closing_stock,last_modified,branchname,item_id,itm_id,category_id,branch_id)values('$data[3]','$stock_no','$stk_date','$stk[$i]','$data[5]','$lm','$branchname','$data[0]','$itm_id[$i]','$cat_id[$i]','$branch_id')");				
        					
        					}
        				}
					}
					else
					{
					    $this->session->set_flashdata('error', 'Something went wrong, please do the entries again');
		                redirect('Eshanya/stock_updateEsh/');
					}
					}
	            }
				fclose($file);
				$this->session->set_flashdata('message', 'Data are imported successfully..');
				redirect('Eshanya/stock_RawPrReceipt/'.$stck_id);
			}else{
				$this->session->set_flashdata('message', 'Something went wrong..');
				redirect('Eshanya/stock_updateEsh');
			}
		}
	}
	
	public function import_PrStock(){
		if(isset($_POST["prupload"]))
		{
			$filename=$_FILES["prstk_upload"]["tmp_name"];
			if($_FILES["prstk_upload"]["size"] > 0)
			{
				$file = fopen($filename, "r");

				$branchname = $_SESSION['branch_name'];
				$branch_id = $_SESSION['branch_id'];
				$user = $_SESSION['full_name'];
				$stk_date = date("Y-m-d");
				$order_time = date("h:i A");
				$lm=date("Y-m-dH:i:s",time());
				$up_type = $this->input->post('upd_type');
				
				if($branchname != '')
	            {
	                $rst = $this->db->query("SELECT * FROM stock_update where branchname='$branchname' and stk_date='$stk_date' and update_type='$up_type' and `stock_no` like 'S%'");
				    
				    if($rst->num_rows() > 0)
					{
					    $this->session->set_flashdata('message', 'The stock is aleready uploaded for the month');
				        redirect('Eshanya/stock_updateEsh/');
					}
					else
					{
        				$result = $this->db->query("SELECT MAX(stk_no) as stk_no FROM stock_update where branch_id='$branch_id' and `stock_no` like 'S%'");
        				foreach($result->result_array() as $res)
        				$stk_no = $res['stk_no'];
        				if($stk_no == 0){
        					$stkno = 1;
        				}
        				else{
        					$stkno = $stk_no+1;
        				}
        				
        		    	$stock_no = "STKUP"."/".$branchname."/".$stkno;
        		    	$res2 = $this->db->query("insert into stock_update(stk_no,stock_no,stk_date,branchname,user_name,stk_time,branch_id,update_type)values('$stkno','$stock_no','$stk_date','$branchname','$user','$order_time','$branch_id','$up_type')");
        		    	$stck_id = $this->db->insert_id();
        		    	if($stck_id)
        		    	{
        		    	$i=0;
        				while (($data = fgetcsv($file, 10000, ",")) !== FALSE)
        				{
        					$res3=$this->db->query("select * from eshRecipe where recipe_id='$data[0]'");
        	        		if($res3->num_rows() > 0)
        	        		{
        	        			foreach($res3->result_array() as $res4)
        	        			$qty[$i] = $res4['production_stock'];//present stock
        						$qty1[$i] = $qty[$i] - $data[5];//consumed stock
        						$recipe_no[$i] = $res4['recipe_no'];
        					 		        			
                				$this->db->query("insert into stock_update_item(item_type,item_name,uom,present_stk,closing_stk,stck_id,item_id,cat_id,recipe_no)values('Finished Product','$data[3]','$data[4]','$qty[$i]','$data[5]','$stck_id','$data[0]','$data[1]','$recipe_no[$i]')");
                	
                				$res5=$this->db->query("UPDATE eshRecipe set production_stock='$data[5]' WHERE  recipe_id= '$data[0]'");
                				$this->db->query("insert into stock_detail(item_name,trans_ref_no,transaction_date,opening_stock,closing_stock,last_modified,branchname,item_id,recipe_no,category_id,branch_id)values('$data[3]','$stock_no','$stk_date','$qty[$i]','$data[5]','$lm','$branchname','$data[0]','$recipe_no[$i]','$data[1]','$branch_id')");				
        					
        					}
        				}
					}
					else
            		{
            		    $this->session->set_flashdata('error', 'Something went wrong, please do the entries again');
            		    redirect('Eshanya/stock_updateEsh/');
            		}
	                }
	            }
				fclose($file);
				$this->session->set_flashdata('message', 'Data are imported successfully..');
				redirect('Eshanya/stock_RawPrReceipt/'.$stck_id);
			}else{
				$this->session->set_flashdata('message', 'Something went wrong..');
				redirect('Eshanya/stock_updateEsh');
			}
		}
	}
	
	public function stock_RawPrReceipt($stck_id){
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['branch_name'] = $_SESSION['branch_name'];
		$data['moduleName'] = ' Stock Update';
		$data['sub_ModuleName'] = ' Stock Update Receipt';
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['stock_update'] = $this->eshanya_model->stock_update($stck_id);
		$data['stk_update_items'] = $this->eshanya_model->stk_update_items($stck_id);
		$this->load->view('Eshanya/Stock_update/stock_RawReceipt',$data);
	}
	
	public function DailyStockUpdate(){
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['moduleName'] = 'Daily Stock Update';
		$data['sub_ModuleName'] = 'Daily Stock Update Entry';
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$this->load->view('Eshanya/Stock_update/daily_stock_update',$data);
	}
	
	public function export_DStock(){
		$branchname = $_SESSION['branch_name'];
		$branch_id = $_SESSION['branch_id'];
		
        $filename = 'Daily_Stock_Update(RM)_'.$branchname.'_'.date('d-m-Y').'.csv';
       header("Content-Description: File Transfer"); 
       header("Content-Disposition: attachment; filename=$filename"); 
       header("Content-Type: application/csv; ");
       
       // get data 
       $branch_id = $_SESSION['branch_id'];
       $usersData = $this->eshanya_model->getcatdata1($branch_id);
    
       // file creation 
       $file = fopen('php://output', 'w');
     
       $header = array("item_id","category_id","category_name","item_name","uom","closing_stk","branch_name"); 
       fputcsv($file, $header);
       foreach ($usersData as $key=>$line){
         fputcsv($file,$line); 
       }
       fclose($file); 
       exit;
	}
	
	public function exportDPrStock(){
	    $branchname = $_SESSION['branch_name'];
		$branch_id = $_SESSION['branch_id'];
		
        $filename = 'Daily_Stock_Update(FP)_'.$branchname.'_'.date('d-m-Y').'.csv';
       header("Content-Description: File Transfer"); 
       header("Content-Disposition: attachment; filename=$filename"); 
       header("Content-Type: application/csv; ");
       
       // get data 
       $branch_id = $_SESSION['branch_id'];
       $usersData = $this->eshanya_model->getProductDetail($branch_id);
    
       // file creation 
       $file = fopen('php://output', 'w');
     
       $header = array("recipe_id","pr_cat_id","pr_cat_name","product_name","uom","closing_stk","branch_name"); 
       fputcsv($file, $header);
       foreach ($usersData as $key=>$line){
         fputcsv($file,$line); 
       }
       fclose($file); 
       exit;
	}
	
		public function importDailyStock(){
		if(isset($_POST["upload"]))
		{
			$filename=$_FILES["stk_upload"]["tmp_name"];
			if($_FILES["stk_upload"]["size"] > 0)
			{
				$file = fopen($filename, "r");

				$branchname = $_SESSION['branch_name'];
				$branch_id = $_SESSION['branch_id'];
				$user = $_SESSION['full_name'];
				$stk_date = date("Y-m-d");
				$order_time = date("h:i A");
				$lm=date("Y-m-dH:i:s",time());
				
				$result = $this->db->query("SELECT MAX(stk_no) as stk_no FROM stock_update where branch_id='$branch_id' and `stock_no` like 'D%'");
				foreach($result->result_array() as $res)
				$stk_no = $res['stk_no'];
				if($stk_no == 0){
					$stkno = 1;
				}
				else{
					$stkno = $stk_no+1;
				}
				
		    	$stock_no = "DSTKUP"."/".$branchname."/".$stk_no;
		    	$res2 = $this->db->query("insert into stock_update(stk_no,stock_no,stk_date,branchname,user_name,stk_time,branch_id)values('$stkno','$stock_no','$stk_date','$branchname','$user','$order_time','$branch_id')");
		    	$stck_id = $this->db->insert_id();
		    	if($stck_id)
		    	{
		    	$i=0;
				while (($data = fgetcsv($file, 10000, ",")) !== FALSE)
				{
					$res3=$this->db->query("select * from item_creation where item_id='$data[0]'");
	        		if($res3->num_rows() > 0)
	        		{
	        			foreach($res3->result_array() as $res4)
	        			$qty[$i] = $res4['stock_item'];//present stock
						$qty1[$i] = $qty[$i] - $data[5];//consumed stock
						$itm_id[$i] = $res4['itm_id'];
					 	$cat_id[$i] = $res4['category_id'];
						$pr=$this->db->query("select * from item_creation where itm_id='$itm_id[$i]' and branchname='ESH'");
	        			foreach($pr->result_array() as $prs)
	        			$tax = $prs['item_tax'];
	        			$iprice = $prs['item_price'];
	        			$iprice = $prs['item_price'];
	        			$tax_a = ($tax * $iprice)/100;
	        			$rate = $iprice + $tax_a;
        				$this->db->query("insert into stock_update_item(item_type,item_name,uom,present_stk,closing_stk,stck_id,item_id,cat_id,itm_id,item_price,item_tax,rate)values('Raw Material','$data[3]','$data[4]','$qty[$i]','$data[5]','$stck_id','$data[0]','$cat_id[$i]','$itm_id[$i]','$iprice','$tax','$rate')");
        	
        				$res5 = $this->db->query("update item_creation set stock_item='$data[5]' where item_id='$data[0]'");
        				$this->db->query("insert into stock_detail(item_name,trans_ref_no,transaction_date,opening_stock,closing_stock,last_modified,branchname,item_id,itm_id,category_id,branch_id)values('$data[3]','$stock_no','$stk_date','$qty[$i]','$data[5]','$lm','$branchname','$data[0]','$itm_id[$i]','$cat_id[$i]','$branch_id')");				
					
					}
				}
			}
			else
			{
    		    $this->session->set_flashdata('error', 'Something went wrong, please do the entries again');
    		    redirect('Eshanya/daily_stock_update');
			}
				fclose($file);
				$this->session->set_flashdata('message', 'Data are imported successfully..');
				redirect('Eshanya/dstkstock_receipt/'.$stck_id);
			}else{
				$this->session->set_flashdata('message', 'Something went wrong..');
				redirect('Eshanya/daily_stock_update');
			}
		}
	}
	
	public function importDailyPrStock(){
		if(isset($_POST["prupload"]))
		{
			$filename=$_FILES["prstk_upload"]["tmp_name"];
			if($_FILES["prstk_upload"]["size"] > 0)
			{
				$file = fopen($filename, "r");

				$branchname = $_SESSION['branch_name'];
				$branch_id = $_SESSION['branch_id'];
				$user = $_SESSION['full_name'];
				$stk_date = date("Y-m-d");
				$order_time = date("h:i A");
				$lm=date("Y-m-dH:i:s",time());
				
				$result = $this->db->query("SELECT MAX(stk_no) as stk_no FROM stock_update where branch_id='$branch_id' and `stock_no` like 'D%'");
				foreach($result->result_array() as $res)
				$stk_no = $res['stk_no'];
				if($stk_no == 0){
					$stkno = 1;
				}
				else{
					$stkno = $stk_no+1;
				}
				//echo $stkno;
		    	$stock_no = "DSTKUP"."/".$branchname."/".$stk_no;
		    	$res2 = $this->db->query("insert into stock_update(stk_no,stock_no,stk_date,branchname,user_name,stk_time,branch_id)values('$stkno','$stock_no','$stk_date','$branchname','$user','$order_time','$branch_id')");
		    	$stck_id = $this->db->insert_id();
		    	if($stck_id)
		    	{
		    	$i=0;
				while (($data = fgetcsv($file, 10000, ",")) !== FALSE)
				{
					$res3=$this->db->query("select * from eshRecipe where recipe_id='$data[0]'");
	        		if($res3->num_rows() > 0)
	        		{
	        			foreach($res3->result_array() as $res4)
	        			$qty[$i] = $res4['production_stock'];//present stock
						$qty1[$i] = $qty[$i] - $data[5];//consumed stock
						$recipe_no[$i] = $res4['recipe_no'];
					 		        			
        				$this->db->query("insert into stock_update_item(item_type,item_name,uom,present_stk,closing_stk,stck_id,item_id,cat_id,recipe_no)values('Finished Product','$data[3]','$data[4]','$qty[$i]','$data[5]','$stck_id','$data[0]','$data[1]','$recipe_no[$i]')");
        	
        				$res5=$this->db->query("UPDATE eshRecipe set production_stock='$data[5]' WHERE  recipe_id= '$data[0]'");
        				$this->db->query("insert into stock_detail(item_name,trans_ref_no,transaction_date,opening_stock,closing_stock,last_modified,branchname,item_id,recipe_no,category_id,branch_id)values('$data[3]','$stock_no','$stk_date','$qty[$i]','$data[5]','$lm','$branchname','$data[0]','$recipe_no[$i]','$data[1]','$branch_id')");				
					
					}
				}
			}
			else
			{
			    $this->session->set_flashdata('error', 'Something went wrong, please do the entries again');
    		    redirect('Eshanya/daily_stock_update');
			}
				fclose($file);
				$this->session->set_flashdata('message', 'Data are imported successfully..');
				redirect('Eshanya/dstkstock_receipt/'.$stck_id);
			}else{
				$this->session->set_flashdata('message', 'Something went wrong..');
				redirect('Eshanya/daily_stock_update');
			}
		}
	}
	
	public function dstkstock_receipt($stck_id){
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['branch_name'] = $_SESSION['branch_name'];
		$data['moduleName'] = ' Stock Update';
		$data['sub_ModuleName'] = ' Stock Update Receipt';
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['stock_update'] = $this->eshanya_model->stock_update($stck_id);
		$data['stk_update_items'] = $this->eshanya_model->stk_update_items($stck_id);
		$this->load->view('Eshanya/Stock_update/dstk_receipt',$data);
		
	}
	
	public function stockUpdateESH(){
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['moduleName']='Stock Update';
		$data['sub_ModuleName']='Stock Update Entry';
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$this->load->view('Eshanya/Stock_update/stockUpdateESH',$data);
	}
	
	public function export_Stock1(){
		// file name 
	   $branchname = $_SESSION['branch_name'];
       $filename = 'Stock_Update(RM)_'.$branchname.'_'.date('d-m-Y').'.csv';
       header("Content-Description: File Transfer"); 
       header("Content-Disposition: attachment; filename=$filename"); 
       header("Content-Type: application/csv; ");
       
       // get data 
       $branch_id = $_SESSION['branch_id'];
       $usersData = $this->eshanya_model->getcatdata1($branch_id);
    
       // file creation 
       $file = fopen('php://output', 'w');
     
       $header = array("item_id","category_id","category_name","item_name","uom","closing_stk","branch_name"); 
       fputcsv($file, $header);
       foreach ($usersData as $key=>$line){
         fputcsv($file,$line); 
       }
       fclose($file); 
       exit; 
	}

/*	public function import_StockESH(){
		if(isset($_POST["upload"]))
		{
			$filename=$_FILES["stk_upload"]["tmp_name"];
			if($_FILES["stk_upload"]["size"] > 0)
			{
				$file = fopen($filename, "r");

				$branchname = $_SESSION['branch_name'];
				$branch_id = $_SESSION['branch_id'];
				$user = $_SESSION['full_name'];
				$stk_date = date("Y-m-d");
				$order_time = date("h:i A");
				$lm=date("Y-m-dH:i:s",time());
				
				$result = $this->db->query("SELECT MAX(stk_no) as stk_no FROM stock_update where branch_id='$branch_id' and `stock_no` like 'S%'");
				foreach($result->result_array() as $res)
				$stk_no = $res['stk_no'];
				if($stk_no == 0){
					$stkno = 1;
				}
				else{
					$stkno = $stk_no+1;
				}
				
		    	$stock_no = "STKUP"."/".$branchname."/".$stkno;
		    	$res2 = $this->db->query("insert into stock_update(stk_no,stock_no,stk_date,branchname,user_name,stk_time,branch_id)values('$stkno','$stock_no','$stk_date','$branchname','$user','$order_time','$branch_id')");
		    	$stck_id = $this->db->insert_id();
		    	if($stck_id)
		    	{
		    	$i=0;
				while (($data = fgetcsv($file, 10000, ",")) !== FALSE)
				{
					$res3=$this->db->query("select * from item_creation where item_id='$data[0]'");
	        		if($res3->num_rows() > 0)
	        		{
	        			foreach($res3->result_array() as $res4)
	        			$stk[$i] = $res4['stock_item'];
	        			$unitm[$i] = $res4['uom'];
	        			$itm_id[$i] = $res4['itm_id'];
	        			$cat_id[$i] = $res4['category_id'];
					 	
						$pr=$this->db->query("select * from item_creation where itm_id='$itm_id[$i]' and branchname='ESH'");
	        			foreach($pr->result_array() as $prs)
	        			$tax = $prs['item_tax'];
	        			$iprice = $prs['item_price'];
	        			$tax_a = ($tax * $iprice)/100;
	        			$rate = $iprice + $tax_a;
        				$this->db->query("insert into stock_update_item(item_type,item_name,uom,present_stk,closing_stk,stck_id,item_id,cat_id,itm_id,item_price,item_tax,rate)values('Raw Material','$data[3]','$data[4]','$stk[$i]','$data[5]','$stck_id','$data[0]','$cat_id[$i]','$itm_id[$i]','$iprice','$tax','$rate')");
        	
        				$res5 = $this->db->query("update item_creation set stock_item='$data[5]' where item_id='$data[0]'");
        				$this->db->query("insert into stock_detail(item_name,trans_ref_no,transaction_date,opening_stock,closing_stock,last_modified,branchname,item_id,itm_id,category_id,branch_id)values('$data[3]','$stock_no','$stk_date','$stk[$i]','$data[5]','$lm','$branchname','$data[0]','$itm_id[$i]','$cat_id[$i]','$branch_id')");				
					
					}
				}
			}
			else
    		{
    		    $this->session->set_flashdata('error', 'Something went wrong, please do the entries again');
    		   redirect('Eshanya/stockUpdateESH');
    		}
				fclose($file);
				$this->session->set_flashdata('message', 'Data are imported successfully..');
				redirect('Eshanya/stock_receipt/'.$stck_id);
			}else{
				$this->session->set_flashdata('message', 'Something went wrong..');
				redirect('Eshanya/stockUpdateESH');
			}
		}
	} */
	
	public function import_StockESH(){
		if(isset($_POST["upload"]))
		{
			$filename=$_FILES["stk_upload"]["tmp_name"];
			if($_FILES["stk_upload"]["size"] > 0)
			{
				$file = fopen($filename, "r");

				$branchname = $_SESSION['branch_name'];
				$branch_id = $_SESSION['branch_id'];
				$user = $_SESSION['full_name'];
				$stk_date = date("Y-m-d");
				$order_time = date("h:i A");
				$lm=date("Y-m-dH:i:s",time());
				
				$result = $this->db->query("SELECT MAX(stk_no) as stk_no FROM stock_update where branch_id='$branch_id' and `stock_no` like 'S%'");
				foreach($result->result_array() as $res)
				$stk_no = $res['stk_no'];
				if($stk_no == 0){
					$stkno = 1;
				}
				else{
					$stkno = $stk_no+1;
				}
				
		    	$stock_no = "STKUP"."/".$branchname."/".$stkno;
		    	$res2 = $this->db->query("insert into stock_update(stk_no,stock_no,stk_date,branchname,user_name,stk_time,branch_id)values('$stkno','$stock_no','$stk_date','$branchname','$user','$order_time','$branch_id')");
		    	$stck_id = $this->db->insert_id();
		    	if($stck_id)
		    	{
		    	if($branchname == 'ESH-GDW')
		    	{
		    		$i=0;
    				while (($data = fgetcsv($file, 10000, ",")) !== FALSE)
    				{
    				    if($data[5] != '')
    				    {
    					$res3=$this->db->query("select * from item_creation where item_id='$data[0]'");
    	        		if($res3->num_rows() > 0)
    	        		{
    	        			foreach($res3->result_array() as $res4)
    	        			$stk[$i] = $res4['stock_item'];
    	        			$unitm[$i] = $res4['uom'];
    	        			$itm_id[$i] = $res4['itm_id'];
    	        			$cat_id[$i] = $res4['category_id'];
    					 	$tax = $res4['item_tax'];
    	        			$iprice = $res4['item_price'];
    	        			$tax_a = ($tax * $iprice)/100;
    	        			$rate = $iprice + $tax_a;
    						$pr=$this->db->query("select stock from esh_godown where itm_id='$itm_id[$i]'");
    						if($pr->num_rows() > 0){
        	        			foreach($pr->result_array() as $prs)
        	        			
        	        			$gdw_stk[$i] = $prs['stock'];
                				$this->db->query("insert into stock_update_item(item_type,item_name,uom,present_stk,closing_stk,stck_id,item_id,cat_id,itm_id,item_price,item_tax,rate)values('Raw Material','$data[3]','$data[4]','$gdw_stk[$i]','$data[5]','$stck_id','$data[0]','$cat_id[$i]','$itm_id[$i]','$iprice','$tax','$rate')");
                	
                				$res5 = $this->db->query("update esh_godown set stock='$data[5]' where item_id='$data[0]'");
                				
                				$this->db->query("insert into stock_detail(item_name,trans_ref_no,transaction_date,opening_stock,closing_stock,last_modified,branchname,item_id,itm_id,category_id,branch_id)values('$data[3]','$stock_no','$stk_date','$gdw_stk[$i]','$data[5]','$lm','$branchname','$data[0]','$itm_id[$i]','$cat_id[$i]','$branch_id')");
    						}
    						else{
    						   	$this->db->query("insert into stock_update_item(item_name,uom,present_stk,closing_stk,stck_id,item_id,itm_id,cat_id,item_price,item_tax,rate) values ('$data[3]','$data[4]','0','$data[5]','$stck_id','$data[0]','$itm_id[$i]','$cat_id[$i]','$iprice','$tax','$rate')");
                			
                				$this->db->query("insert into esh_godown(item_name,uom,price,stock,from_branchname,branchname,item_id,itm_id,category_id)values('$data[3]','$data[4]','$price[$i]','$data[5]','CW','$branchname','$data[0]','$itm_id[$i]','$cat_id[$i]')");
                				
                				$this->db->query("insert into stock_detail(item_name,trans_ref_no,transaction_date,opening_stock,closing_stock,last_modified,branchname,item_id,itm_id,category_id,branch_id)values('$data[3]','$stock_no','$stk_date','0','$data[5]','$lm','$branchname','$data[0]','$itm_id[$i]','$cat_id[$i]','$branch_id')");
		
    						}
    					
    					}
    				}
    				}
		    	}
		    	else
		    	{
		    	$i=0;
				while (($data = fgetcsv($file, 10000, ",")) !== FALSE)
				{
					$res3=$this->db->query("select * from item_creation where item_id='$data[0]'");
	        		if($res3->num_rows() > 0)
	        		{
	        			foreach($res3->result_array() as $res4)
	        			$stk[$i] = $res4['stock_item'];
	        			$unitm[$i] = $res4['uom'];
	        			$itm_id[$i] = $res4['itm_id'];
	        			$cat_id[$i] = $res4['category_id'];
					 	
						$pr=$this->db->query("select * from item_creation where itm_id='$itm_id[$i]' and branchname='ESH'");
	        			foreach($pr->result_array() as $prs)
	        			$tax = $prs['item_tax'];
	        			$iprice = $prs['item_price'];
	        			$tax_a = ($tax * $iprice)/100;
	        			$rate = $iprice + $tax_a;
        				$this->db->query("insert into stock_update_item(item_type,item_name,uom,present_stk,closing_stk,stck_id,item_id,cat_id,itm_id,item_price,item_tax,rate)values('Raw Material','$data[3]','$data[4]','$stk[$i]','$data[5]','$stck_id','$data[0]','$cat_id[$i]','$itm_id[$i]','$iprice','$tax','$rate')");
        	
        				$res5 = $this->db->query("update item_creation set stock_item='$data[5]' where item_id='$data[0]'");
        				$this->db->query("insert into stock_detail(item_name,trans_ref_no,transaction_date,opening_stock,closing_stock,last_modified,branchname,item_id,itm_id,category_id,branch_id)values('$data[3]','$stock_no','$stk_date','$stk[$i]','$data[5]','$lm','$branchname','$data[0]','$itm_id[$i]','$cat_id[$i]','$branch_id')");				
					
					}
				}
				}
			}
			else
    		{
    		    $this->session->set_flashdata('error', 'Something went wrong, please do the entries again');
    		   redirect('Eshanya/stockUpdateESH');
    		}
				fclose($file);
				$this->session->set_flashdata('message', 'Data are imported successfully..');
				redirect('Eshanya/stock_receipt/'.$stck_id);
			}else{
				$this->session->set_flashdata('message', 'Something went wrong..');
				redirect('Eshanya/stockUpdateESH');
			}
		}
	}
	
	public function stock_receipt($stck_id){
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['branch_name'] = $_SESSION['branch_name'];
		$data['moduleName'] = ' Stock Update';
		$data['sub_ModuleName'] = ' Stock Update Receipt';
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['stock_update'] = $this->eshanya_model->stock_update($stck_id);
		$data['stk_update_items'] = $this->eshanya_model->stk_update_items($stck_id);
		$this->load->view('Eshanya/Stock_update/stock_receipt',$data);
	}
	
	public function stock_update_list($sub_mod_id)
	{
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['moduleName'] = ' Stock Update';
		$data['sub_ModuleName'] = ' Stock Update List';
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['thead_permission'] = $this->user_model->get_thead_permission($user_id,$sub_mod_id);
		$data['submod_id']=$sub_mod_id;
		//$data['stock_update'] = $this->stockupdate_model->stock_update_list($branch_id);
		$this->load->view('Eshanya/Stock_update/stock_update_list',$data);
	}
	public function getStockUpdate($sub_mod_id){
		
		$branch_id = $_SESSION['branch_id'];
		$data = $this->eshanya_model->stock_update_list($branch_id);
        $count=1;
        $test = array();
        foreach($data as $row)
    	{
    	    
    	    $view = "<a href='$this->master_url/index.php/Eshanya/viewStockUp/$row->stck_id/$sub_mod_id' class=''><i class='ft-eye'></i></a>";
    	    
    	    
    	    $test[] = array(
    	        $count,
    	        $row->stock_no,
    	        $row->stk_date,
                $view
    	   );
    	        
    	        $count++;
    	}
    	$datas = array(
    	    "data" =>$test
    	);
    	
    	echo json_encode($datas);
	}
	
	public function search_stock_update(){
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['branch_name'] = $_SESSION['branch_name'];
		
		
		$from_date = $this->input->post('from_date');
		$to_date = $this->input->post('to_date');
		$sub_mod_id=$this->input->post('sub_mod_id');
		
		$data1 = array(
		'from_date' => $from_date,
		'to_date' => $to_date,
		'branch_id' =>$branch_id
		);
		if ($from_date == "" && $to_date == "") {
			$data['date_range_error_message'] = "Both feilds are required";
			} else {
			$result = $this->eshanya_model->stock_update_by_branch($data1);
			if ($result != false) {
				$data['result_display'] = $result;
				} else {
				$data['result_display'] = "No record found !";
			}
		}
		$data['submod_id']=$sub_mod_id;
		$data['moduleName'] = ' Stock Update';
		$data['sub_ModuleName'] = ' Stock Update List';
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['thead_permission'] = $this->user_model->get_thead_permission($user_id,$sub_mod_id);
		$this->load->view('Eshanya/Stock_update/stock_update_list',$data);
	}
	
	public function viewStockUp($stck_id,$sub_mod_id){
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['branch_name'] = $_SESSION['branch_name'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['thead_permission'] = $this->user_model->get_thead_permission($user_id,$sub_mod_id);
		$data['submod_id']=$sub_mod_id;
		$data['moduleName'] = ' Stock Update';
		$data['sub_ModuleName'] = ' Stock Update Receipt';
		$data['stock_update'] = $this->eshanya_model->stock_update($stck_id);
		$data['stk_update_items'] = $this->eshanya_model->stk_update_items($stck_id);
		$this->load->view('Eshanya/Stock_update/viewStockUp',$data);
	}
	
	public function dailyStockUpdateList()
	{
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['moduleName'] = ' Stock Update';
		$data['sub_ModuleName'] = 'Daily Stock Update List';
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['stock_update'] = $this->eshanya_model->daily_stock_update_list($branch_id);
		$this->load->view('Eshanya/Stock_update/daily_stock_update_list',$data);
	}
	
	public function getDStockUpdate($sub_mod_id){
		
		$branch_id = $_SESSION['branch_id'];
		$data = $this->eshanya_model->daily_stock_update_list($branch_id);
        $count=1;
        $test = array();
        foreach($data as $row)
    	{
    	    
    	    $view = "<a href='$this->master_url/index.php/Eshanya/viewDStockUp/$row->stck_id/$sub_mod_id' class=''><i class='ft-eye'></i></a>";
    	    
    	    
    	    $test[] = array(
    	        $count,
    	        $row->stock_no,
    	        $row->stk_date,
                $view
    	   );
    	        
    	        $count++;
    	}
    	$datas = array(
    	    "data" =>$test
    	);
    	
    	echo json_encode($datas);
	}
	
	public function viewDStockUp($stck_id,$sub_mod_id){
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['branch_name'] = $_SESSION['branch_name'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['thead_permission'] = $this->user_model->get_thead_permission($user_id,$sub_mod_id);
		$data['submod_id']=$sub_mod_id;
		$data['moduleName'] = ' Stock Update';
		$data['sub_ModuleName'] = ' Stock Update Receipt';
		$data['stock_update'] = $this->eshanya_model->stock_update($stck_id);
		$data['stk_update_items'] = $this->eshanya_model->stk_update_items($stck_id);
		$this->load->view('Eshanya/Stock_update/viewDStockUp',$data);
	}
	
	public function search_Dailystock_update(){
	    $user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['branch_name'] = $_SESSION['branch_name'];
		$from_date = $this->input->post('from_date');
		$to_date = $this->input->post('to_date');
		$sub_mod_id=$this->input->post('sub_mod_id');
		
		$data1 = array(
		'from_date' => $from_date,
		'to_date' => $to_date,
		'branch_id' =>$branch_id
		);
		if ($from_date == "" && $to_date == "") {
			$data['date_range_error_message'] = "Both feilds are required";
			} else {
			$result = $this->eshanya_model->dailyStock_update_by_branch($data1);
			if ($result != false) {
				$data['result_display'] = $result;
				} else {
				$data['result_display'] = "No record found !";
			}
		}
		$data['submod_id']=$sub_mod_id;
		$data['moduleName'] = ' Stock Update';
		$data['sub_ModuleName'] = 'Daily Stock Update List';
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['thead_permission'] = $this->user_model->get_thead_permission($user_id,$sub_mod_id);
		$this->load->view('Eshanya/Stock_update/daily_stock_update_list',$data);
	}
	
	/*** DAMAGE ***/
	public function dmgEntry()
	{
		//file_put_contents('item_list.json', "");
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['moduleName']='Damage';
		$data['sub_ModuleName']='Damage Entry';
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['items'] = $this->eshanya_model->get_Items($branch_id);
		$this->load->view('Eshanya/Damage/damage',$data);
	}
	
	public function itemDetails(){
		$branch_id = $this->input->post('branch_id');
				
		$query1 = $this->db->query("SELECT category_id,category_name from category order by category_name");
		//foreach ($query1 as $key => $cat) {
		foreach($query1->result() as $cat){
			//while ($cat = mysqli_fetch_array($query1)) {
			$results = $this->db->query("SELECT T.item_name,T.uom,T.stock_item,T.item_id,T.itm_id,T.category_id FROM item_creation T inner join category C on C.category_id=T.category_id where C.category_id='".$cat->category_id."' and T.branch_id='$branch_id' order by T.item_name");
			
			unset($items);
			//foreach ($results as $key => $result) {
			foreach($results->result() as $result){
				//while ($result= mysqli_fetch_array($results)) {
				$items[] = array(
				'item_name' => $result->item_name,
				'uom' => $result->uom,
				'prsnt_stk' => $result->stock_item,
				'item_id' => $result->item_id,
				'itm_id' => $result->itm_id,
				'cat_id' => $result->category_id
				);
			}
			$category = $cat->category_name;
			$category_id = $cat->category_id;
			
			if(isset($items))
			{
    			$json[] = array(
    			'category' => $category,
    			'category_id' => $category_id,
    			'items' => $items
    			);
			}
		}
		
		$itemarray = array(
		'products' => $json
		);
		echo json_encode($itemarray);
		file_put_contents('item_lists.json', json_encode($itemarray));
		
		//Finished product
		$query2 = $this->db->query("SELECT pr_cat_id,pr_cat_name from EshProduct_category order by pr_cat_name");
		//foreach ($query1 as $key => $cat) {
		foreach($query2->result() as $pr_cat){
			//while ($cat = mysqli_fetch_array($query1)) {
			
			$results1 = $this->db->query("SELECT R.rname,R.uom,R.production_stock,R.daily_stk_update,R.recipe_id,R.recipe_no,R.pr_cat_id FROM eshRecipe R inner join EshProduct_category PC on PC.pr_cat_id=R.pr_cat_id where PC.pr_cat_id='".$pr_cat->pr_cat_id."' and R.branch_id='".$branch_id."' and R.status='Enabled' order by R.rname");
			
			unset($product);
			
			//foreach ($results as $key => $result) {
			foreach($results1->result() as $prod){
				//while ($result= mysqli_fetch_array($results)) {
				$product[] = array(
				'product_name' => $prod->rname,
				'uom' => $prod->uom,
				'prsnt_stk' => $prod->production_stock,
				'cls_stk' => $prod->daily_stk_update,
				'recipe_id' => $prod->recipe_id,
				'recipe_no' => $prod->recipe_no,
				'cat_id' => $prod->pr_cat_id
				);
			}
						
			$prod_cat = $pr_cat->pr_cat_name;
			$pr_cat_id = $pr_cat->pr_cat_id;
		
		    if(isset($product))
			{
    			$json1[] = array(
    			'prod_cat' => $prod_cat,
    			'pr_cat_id' => $pr_cat_id,
    			'product' => $product
    			);
			}
		}
				
		$finished_prod = array(
		'finished_products' => $json1
		);
		
		echo json_encode($finished_prod);
		file_put_contents('product_lists.json', json_encode($finished_prod));
	}
	
	public function insertDamageItem(){
		$cur_date = date("Y-m-d");
		$cur_time = date("h:i A");
		$lm=date("Y-m-dH:i:s",time());
		$branch_name = $this->input->post('branch');
		$branch_id =  $this->input->post('branch_id');
		$damage_type = $this->input->post('ret_type');
		$query = $this->db->query("SELECT MAX(dm_no) as dm_no FROM damage_order_creation where branch_id='$branch_id'");
		
		foreach($query->result() as $row)
		$dm_no = $row->dm_no;
		if($dm_no == 0){
			$dm_no = 1;
		}
		else{
			$dm_no = $dm_no+1;
		}
		$damage_no = "DMG"."/".$branch_name."/".$dm_no;
		
		
		$item_type=explode(',', $this->input->post('item_type'));
		$item_name=explode(',', $this->input->post('item_name'));
		$uom=explode(',', $this->input->post('uom'));
		$prsnt_stk=explode(',', $this->input->post('prsnt_stk'));
		$dmg_qty=explode(',', $this->input->post('dmg_qty'));
		$item_id=explode(',', $this->input->post('item_id'));
		$itm_id=explode(',', $this->input->post('itm_id'));
		$cat_id=explode(',', $this->input->post('cat_id'));
		$remarks=explode(',', $this->input->post('remarks'));
		
		$k=0;
		for($j=0;$j<count($dmg_qty);$j++)
		{
			if($dmg_qty[$j]!='0' && $dmg_qty[$j]!='')
			{
				$k=$k+1;
			}
		}
		if($k>0)
		{
		    $sql = $this->db->query("INSERT INTO damage_order_creation(dm_no,damage_no,damage_date,return_type,branchname,dtime,branch_id) values ('$dm_no','$damage_no','$cur_date','$damage_type','$branch_name','$cur_time','$branch_id')");
		    $did = $this->db->insert_id();
		}
		if($did)
		{
		for($i=0;$i<count($item_type),$i<count($item_name),$i<count($item_id),$i<count($uom),$i<count($prsnt_stk),$i<count($dmg_qty);$i++) {
			if($dmg_qty[$i] != '0' and $dmg_qty[$i] != '')
			{				
				if($item_type[$i] == 'Raw Material')
				{
					$sql3=$this->db->query("select * from item_creation where item_id='$item_id[$i]'");
					if($sql3->num_rows() > 0)
					{						
						foreach($sql3->result() as $row)
						$qty[$i] = $row->stock_item;//opening stock
						$qty1[$i] = $qty[$i] - $dmg_qty[$i];//closing stock
						
						$sql3 =  $this->db->query("UPDATE item_creation set stock_item='$qty1[$i]' WHERE  item_id='$item_id[$i]'");
					}
					$sql2 =  $this->db->query("INSERT INTO damage_order_item (item_type,damage_item_name,damage_uom,damage_qty,damage_id,item_id,category_id,itm_id,damage_remarks) values ('$item_type[$i]','$item_name[$i]','$uom[$i]','$dmg_qty[$i]','$did','$item_id[$i]','$cat_id[$i]','$itm_id[$i]','$remarks[$i]')");
					$sql5 = $this->db->query("insert into stock_detail(item_name,trans_ref_no,transaction_date,opening_stock,out_qty,closing_stock,last_modified,branchname,item_id,itm_id,category_id,branch_id,trans_type)values('$item_name[$i]','$damage_no','$cur_date','$qty[$i]','$dmg_qty[$i]','$qty1[$i]','$lm','$branch_name','$item_id[$i]','$itm_id[$i]','$cat_id[$i]','$branch_id','Damage')");
				}
				else
				{
					$sql3=$this->db->query("select * from eshRecipe where recipe_id='$item_id[$i]'");
					if($sql3->num_rows() > 0)
					{
						foreach($sql3->result() as $row)
						$qty[$i] = $row->production_stock;//opening stock
						$qty1[$i] = $qty[$i] - $dmg_qty[$i];//closing stock
										
						$sql3 =  $this->db->query("UPDATE eshRecipe set production_stock='$qty1[$i]' WHERE recipe_id='$item_id[$i]'");
					}
					$sql2 =  $this->db->query("INSERT INTO  damage_order_item (item_type,damage_item_name,damage_uom,damage_qty,damage_id,item_id,category_id,recipe_no,damage_remarks) values ('$item_type[$i]','$item_name[$i]','$uom[$i]','$dmg_qty[$i]','$did','$item_id[$i]','$cat_id[$i]','$itm_id[$i]','$remarks[$i]')");
					$sql5 = $this->db->query("insert into stock_detail(item_name,trans_ref_no,transaction_date,opening_stock,out_qty,closing_stock,last_modified,branchname,item_id,recipe_no,category_id,branch_id,trans_type)values('$item_name[$i]','$damage_no','$cur_date','$qty[$i]','$dmg_qty[$i]','$qty1[$i]','$lm','$branch_name','$item_id[$i]','$itm_id[$i]','$cat_id[$i]','$branch_id','Damage')");
				}
			}
		}
		}
		file_put_contents('item_lists.json', '');
		file_put_contents('product_lists.json', '');
		if($did)
		//echo "success";
		echo $did;
		
		else
		//echo json_encode(array('reslt' => 'error', 'did' => $did));
		echo "error";
	}

	public function damageWasteReceipt($did){
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['branch_name'] = $_SESSION['branch_name'];
		$data['moduleName']='Damage';
		$data['sub_ModuleName']='Damage Receipt';
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['getDamage'] = $this->eshanya_model->getDamage($did);
		$data['get_damage_item'] = $this->eshanya_model->get_damage_item($did);
		$this->load->view('Eshanya/Damage/damageWasteReceipt',$data);
	}
	
	public function damageList()
	{
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['moduleName']='Damage';
		$data['sub_ModuleName']='Damage List';
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['damage'] = $this->eshanya_model->get_damage_list($branch_id);
		$this->load->view('Eshanya/Damage/damage_list',$data);
	}
	
	public function getDamage($sub_mod_id){
		
		$branch_id = $_SESSION['branch_id'];
		$data = $this->eshanya_model->get_damage_list($branch_id);
        $count=1;
        $test = array();
        foreach($data as $row)
    	{
    	    
    	    $view = "<a href='$this->master_url/index.php/Eshanya/viewDamage/$row->damage_id/$sub_mod_id' class=''><i class='ft-eye'></i></a>";
    	    
    	    
    	    $test[] = array(
    	        $count,
    	        $row->damage_no,
    	        $row->damage_date,
                $view
    	   );
    	        
    	        $count++;
    	}
    	$datas = array(
    	    "data" =>$test
    	);
    	
    	echo json_encode($datas);
	}
	
	public function viewDamage($did,$sub_mod_id){
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['branch_name'] = $_SESSION['branch_name'];
		$data['moduleName']='Damage';
		$data['sub_ModuleName']='Damage Receipt';
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['thead_permission'] = $this->user_model->get_thead_permission($user_id,$sub_mod_id);
		$data['submod_id']=$sub_mod_id;
		$data['getDamage'] = $this->eshanya_model->getDamage($did);
		$data['get_damage_item'] = $this->eshanya_model->get_damage_item($did);
		$this->load->view('Eshanya/Damage/viewDamage',$data);
	}
	
	/*** PRODUCTION ***/
	
	public function production()
	{
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['moduleName']='Production';
		$data['sub_ModuleName']='Production Entry';
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['chef'] = $this->master_model->get_Chef();
		$data['category'] = $this->eshanya_model->get_Category();
		$data['recipe'] = $this->eshanya_model->getCatRecipe($branch_id);
		$this->load->view('Eshanya/Production/production',$data);
	}
	
	public function addProduction()
	{
		$bid=$this->eshanya_model->addProduction($this->input->post());
		if($bid)
		{
		    redirect('Eshanya/production_view/'.$bid);
		}
		else
		{
		    $this->session->set_flashdata('error', 'Something went wrong, please do the entries again');
		    redirect('Eshanya/production/');
		}
	}
	
	public function production_view($bid)
	{
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['moduleName']='Production';
		$data['sub_ModuleName']='Production Invoice';
		$data['branch_name'] = $_SESSION['branch_name'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['prd'] = $this->eshanya_model->getProduction($bid);
		$data['prd_item'] = $this->eshanya_model->getProductionItem($bid);
		$this->load->view('Eshanya/Production/production_view',$data);
	}
	
	public function productionList()
	{
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['moduleName']='Production';
		$data['sub_ModuleName']='Production List';
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['production_list'] = $this->eshanya_model->getProductionList($branch_id);
		$this->load->view('Eshanya/Production/production_list',$data);
	}
	
	public function productionData()
	{
	    $branch_id = $_SESSION['branch_id'];
        $data = $this->eshanya_model->getProductionList($branch_id);
        $count=1;
        $test = array();
        foreach($data as $row)
    	{
    	    
    	    $view = "<a href='$this->master_url/index.php/Eshanya/production_view/$row->billno' class=''><i class='ft-eye'></i></a>";
    	    
    	    $test[] = array(
    	        $count,
    	        date('d-m-Y',strtotime($row->orderdate)),
    	        $row->bill_id,
    	        $row->chef,
    	        $view
    	        
    	   );
    	        
    	        $count++;
    	}
    	$datas = array(
    	    "data" =>$test
    	);
    	
    	echo json_encode($datas);
        
	}
	
	public function get_RcpDetails()
	{
		$iname = $this->input->post('iname');
		$br_id = $this->input->post('br_id');
		$this->eshanya_model->get_RcpDetails($iname,$br_id);
	}
	
	public function get_RecipeDetails()
	{
		$iname = $this->input->post('iname');
		$br_id = $this->input->post('br_id');
		$this->eshanya_model->get_RecipeDetails($iname,$br_id);
	}
	
	public function get_ItemDetails()
	{
		$iname = $this->input->post('iname');
		$br_id = $this->input->post('br_id');
		$this->eshanya_model->get_ItemDetails($iname,$br_id);
	}
	
	/****Stock Management*****/
	public function Gpresent_stock()
	{
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$this->load->view('Eshanya/StockManagement/Gpresent_stock',$data);
	}
	
	public function getGPrsentStk(){
		
		$branch_id = $_SESSION['branch_id'];
		$data = $this->eshanya_model->getGPresentStock();
        $count=1;
        $test = array();
        foreach($data as $row)
    	{
    	    $tax_a = ($row->price * $row->tax)/100;
    	    $total_amt = round(($row->price + $tax_a),2);
    	    $test[] = array(
    	        $count,
    	        $row->item_name,
    	        $row->uom,
    	        $row->price,
    	        $row->tax,
    	        $total_amt,
    	        $row->stock
    	   );
    	        
    	        $count++;
    	}
    	$datas = array(
    	    "data" =>$test
    	);
    	
    	echo json_encode($datas);
	}
	
	/******* Stock Transfer **********/
	public function stock_GDWtransfer()
	{
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$branch_name = $_SESSION['branch_name'];
		$smod_id = $this->uri->segment(3);
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		if($branch_name=='ESH-GDW'){
		    $data['items'] = $this->eshanya_model->get_GDWItems();
		}
		else{
		    $data['items'] = $this->eshanya_model->get_Items($branch_id);
		}
		$data['tr_user'] = $this->eshanya_model->get_users($branch_id,$smod_id);
		$this->load->view('Eshanya/StockTransfer/gdw_stk_transfer',$data);
	}
	
	public function get_GDWItemDetails()
	{
		$iname = $this->input->post('iname');
		$br_id = $this->input->post('br_id');
		$this->eshanya_model->get_GDWItemDetails($iname,$br_id);
	}
	
	public function addGDWStkTransfer()
	{
		$sid=$this->eshanya_model->addGdwStkTransfer($this->input->post());
		if($sid)
		{
		    redirect('Eshanya/stk_GDWtransfer_inv/'.$sid);
		}
		else
		{
		    $this->session->set_flashdata('error', 'Something went wrong, please do the entries again');
		    redirect('Eshanya/stock_GDWtransfer/');
		}
	}
	
	public function stk_GDWtransfer_inv($sid)
	{
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['branch_name'] = $_SESSION['branch_name'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['stk_transfer'] = $this->eshanya_model->getStkTransfer($sid);
		$data['stk_transfer_item'] = $this->eshanya_model->getStkTransferItem($sid);
		$this->load->view('Eshanya/StockTransfer/preview_GDWstk_transfer',$data);
	}
	
	public function gdw_stk_trans_list()
	{
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$sub_mod_id = $this->uri->segment(3);
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['thead_permission'] = $this->user_model->get_thead_permission($user_id,$sub_mod_id);
		$data['submod_id']=$sub_mod_id;
		$data['items'] = $this->eshanya_model->get_GDWItems();
	//	$data['stk_transfer'] = $this->transfer_model->getStkTransferList($branch_id);
		$this->load->view('Eshanya/StockTransfer/gdw_stk_trans_list',$data);
	}
	
	public function getGDWStkTransfer()
	{
		$branch_id = $_SESSION['branch_id'];
		$branch_name = $_SESSION['branch_name'];
		$data = $this->eshanya_model->get_godown_stk_transfer_list($branch_name);
        $count=1;
        $test = array();
        foreach($data as $row)
    	{
    	    $view = "<a href='$this->master_url/index.php/Eshanya/stk_transfer_inv/$row->stk_tr_id' class=''><i class='ft-eye'></i></a>";
    	    $stk_tr_date=date('d-m-Y',strtotime($row->stk_tr_date));
    	    
    	    $test[] = array(
    	        $count,
    	        $row->stk_tr_no,
    	        $stk_tr_date,
    	        $row->to_branchname,
    	        $row->total,
                $view
    	   );
    	        
    	   $count++;
    	}
    	$datas = array(
    	    "data" =>$test
    	);
    	
    	echo json_encode($datas);
	}
	
	public function stk_transfer_inv($sid)
	{
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['branch_name'] = $_SESSION['branch_name'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['stk_transfer'] = $this->eshanya_model->getStkTransfer($sid);
		$data['stk_transfer_item'] = $this->eshanya_model->getStkTransferItem($sid);
		$this->load->view('Eshanya/StockTransfer/preview_stk_transfer',$data);
	}
	
	public function searchGDWStkTransfer()
	{
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['branch_name'] = $_SESSION['branch_name'];
				
		$from_date = $this->input->post('from_date');
		$to_date = $this->input->post('to_date');
		$item_name = $this->input->post('item_name');
		$sub_mod_id=$this->input->post('sub_mod_id');
		
		$data1 = array(
		'from_date' => $from_date,
		'to_date' => $to_date,
		'item_name' => $item_name,
		'branch_id' =>$branch_id
		);
		if ($from_date == "" && $to_date == "") {
			$data['date_range_error_message'] = "All feilds are required";
			} else {
			$result = $this->eshanya_model->getGDWStkTransferResult($data1);
			if ($result != false) {
				$data['result_display'] = $result;
				} else {
				$data['result_display'] = "No record found !";
			}
		}
		$data['items'] = $this->eshanya_model->get_GDWItems();
		$data['submod_id']=$sub_mod_id;
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['thead_permission'] = $this->user_model->get_thead_permission($user_id,$sub_mod_id);
		$this->load->view('Eshanya/StockTransfer/gdw_stk_trans_list',$data);
	}
	
	public function gdw_trans_recipt(){
		$sid = $_POST['sid'];
		
		$data['stk_transfer'] = $this->eshanya_model->getStkTransfer($sid);
		$data['stk_transfer_item'] = $this->eshanya_model->getStkTransferItem($sid);
		$this->load->view('Eshanya/StockTransfer/gdw_trans_recipt', $data);
	}
}