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

class Stock_update extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->database();
		$this->load->library('session');
		$this->load->model('user_model');
		$this->load->model('master_model');
		$this->load->model('report_model');
		$this->load->model('stockupdate_model');
		$this->load->model('stockupdate_model');
		$this->load->model('damage_model');
		$this->load->model('stockmanage_model');
		if(!isset($_SESSION['user_logged'])) {
			$this->session->set_flashdata("error", "please login first to view dashboard");
			redirect("Login/login");
		}
	}
	//var $master_url='https://gsrgroup.biz/inv_final_test';
    var $master_url='https://bigcashew.com/inventory';
    
	public function stock_update(){
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		
		$this->load->view('Stock_update/stock_update',$data);
	}
	
	public function stockUpdate(){
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$this->load->view('Stock_update/stockUpdate',$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->stockupdate_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;
		
       /* $this->load->library('Excel');
        $listInfo = $this->stockupdate_model->getcatdata($branch_id);
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->SetCellValue('A1', 'item_id');
        $objPHPExcel->getActiveSheet()->SetCellValue('B1', 'category_id');
        $objPHPExcel->getActiveSheet()->SetCellValue('C1', 'category name');
        $objPHPExcel->getActiveSheet()->SetCellValue('D1', 'item_name');
        $objPHPExcel->getActiveSheet()->SetCellValue('E1', 'uom');
        $objPHPExcel->getActiveSheet()->SetCellValue('F1', 'Closing Stock');
        $objPHPExcel->getActiveSheet()->SetCellValue('G1', 'branch');
       
        // set Row
        $rowCount = 2;
        foreach ($listInfo as $list) {
           //if($list->itm_id != '') {
                $objPHPExcel->getActiveSheet()->SetCellValue('A' . $rowCount, $list->item_id);
                $objPHPExcel->getActiveSheet()->SetCellValue('B' . $rowCount, $list->category_id);
                $objPHPExcel->getActiveSheet()->SetCellValue('C' . $rowCount, $list->category_name);
                $objPHPExcel->getActiveSheet()->SetCellValue('D' . $rowCount, $list->item_name);
                $objPHPExcel->getActiveSheet()->SetCellValue('E' . $rowCount, $list->uom);
                $objPHPExcel->getActiveSheet()->SetCellValue('F' . $rowCount, '0');
                $objPHPExcel->getActiveSheet()->SetCellValue('G' . $rowCount, $branchname);
                $rowCount++;
           //}
        }
        //$filename = "Stock_update". date("d-m-Y").".csv";
        $filename = "Stock_Update(RM)_".$branchname."_".date("d-m-Y").".csv";
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');  
        $objWriter->save('php://output');*/
		
	}
	
	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->stockupdate_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 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->stockupdate_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_Stock(){
		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');
				        if($branchname == 'STR')
        				{
        				    redirect('Stock_update/stockUpdateCw');
        				}
        				else
        				{
        				    redirect('Stock_update/stockUpdate');
        				}
					}
					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($branchname == '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 godown_stock 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 godown_stock 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 godown_stock(item_name,uom,price,stock,from_branchname,branchname,item_id,itm_id,category_id)values('$data[3]','$data[4]','$price[$i]','$data[5]','STR','$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)
            				{
            				    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'];
            					 	
            						$pr=$this->db->query("select * from item_creation where itm_id='$itm_id[$i]' and branchname='STR'");
            	        			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')");				
            					
            					}
            				}
            				}
        		    	
        		    	}
        		    	
					}
	            }
				fclose($file);
				$this->session->set_flashdata('message', 'Data are imported successfully..');
				redirect('Stock_update/stock_receipt/'.$stck_id);
			}else{
				$this->session->set_flashdata('message', 'Something went wrong..');
				redirect('Stock_update/stock_update');
			}
		}
	}
	
	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->stockupdate_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 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->stockupdate_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 importPrStock(){
		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 '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();
		    	$i=0;
				while (($data = fgetcsv($file, 10000, ",")) !== FALSE)
				{
				    if($data[5] != '')
				    {
					$res3=$this->db->query("select * from recipe 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 recipe 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')");				
					
					}
				}
				}                   
				fclose($file);
				$this->session->set_flashdata('message', 'Data are imported successfully..');
				redirect('Stock_update/stock_receipt/'.$stck_id);
			}else{
				$this->session->set_flashdata('message', 'Something went wrong..');
				redirect('Stock_update/stock_update');
			}
		}
	}
	
	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();
		    	$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)
	        			$qty[$i] = $res4['stock_item'];//present stock
						$qty1[$i] = (int)$qty[$i] - (int)$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='STR'");
	        			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')");				
					
					}
				}
				}                   
				fclose($file);
				$this->session->set_flashdata('message', 'Data are imported successfully..');
				redirect('Stock_update/dstkstock_receipt/'.$stck_id);
			}else{
				$this->session->set_flashdata('message', 'Something went wrong..');
				redirect('Stock_update/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;
				}
				
		    	$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();
		    	$i=0;
				while (($data = fgetcsv($file, 10000, ",")) !== FALSE)
				{
				    if($data[5] != '')
				    {
					$res3=$this->db->query("select * from recipe 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] = (int)$qty[$i] - (int)$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 recipe 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')");				
					
					}
				}
				}                   
				fclose($file);
				$this->session->set_flashdata('message', 'Data are imported successfully..');
				redirect('Stock_update/dstkstock_receipt/'.$stck_id);
			}else{
				$this->session->set_flashdata('message', 'Something went wrong..');
				redirect('Stock_update/daily_stock_update');
			}
		}
	}
	
	public function DailyStockUpdate(){
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$this->load->view('Stock_update/daily_stock_update',$data);
	}

		
	public function stock_receipt($stck_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['stock_update'] = $this->stockupdate_model->stock_update($stck_id);
		$data['stk_update_items'] = $this->stockupdate_model->stk_update_items($stck_id);
		$this->load->view('Stock_update/stock_receipt',$data);
		
	}

	public function dstkstock_receipt($stck_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['stock_update'] = $this->stockupdate_model->stock_update($stck_id);
		$data['stk_update_items'] = $this->stockupdate_model->stk_update_items($stck_id);
		$this->load->view('Stock_update/dstk_receipt',$data);
		
	}

	public function stock_update_list($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['submod_id']=$sub_mod_id;
		//$data['stock_update'] = $this->stockupdate_model->stock_update_list($branch_id);
		$this->load->view('Stock_update/stock_update_list',$data);
	}
	
	public function getStockUpdate($sub_mod_id){
		
		$branch_id = $_SESSION['branch_id'];
		$data = $this->stockupdate_model->stock_update_list($branch_id);
        $count=1;
        $test = array();
        foreach($data as $row)
    	{
    	    
    	    $view = "<a href='$this->master_url/index.php/Stock_update/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 dailyStockUpdateList()
	{
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['stock_update'] = $this->stockupdate_model->daily_stock_update_list($branch_id);
		$this->load->view('Stock_update/daily_stock_update_list',$data);
	}
	
	public function getDStockUpdate($sub_mod_id){
		
		$branch_id = $_SESSION['branch_id'];
		$data = $this->stockupdate_model->daily_stock_update_list($branch_id);
        $count=1;
        $test = array();
        foreach($data as $row)
    	{
    	    
    	    $view = "<a href='$this->master_url/index.php/Stock_update/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 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->stockupdate_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['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('Stock_update/daily_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['stock_update'] = $this->stockupdate_model->stock_update($stck_id);
		$data['stk_update_items'] = $this->stockupdate_model->stk_update_items($stck_id);
		$this->load->view('Stock_update/viewStockUp',$data);
	}

	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['stock_update'] = $this->stockupdate_model->stock_update($stck_id);
		$data['stk_update_items'] = $this->stockupdate_model->stk_update_items($stck_id);
		$this->load->view('Stock_update/viewDStockUp',$data);
	}

	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->stockupdate_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['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('Stock_update/stock_update_list',$data);
	}

	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('error', 'The stock is aleready uploaded for the month');
				        redirect('Stock_update/stockUpdate/');
					}
					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();
        		    	$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'];
        					 	
        						$pr=$this->db->query("select * from item_creation where itm_id='$itm_id[$i]' and branchname='STR'");
        	        			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')");				
        					
        					}
        				}
        				}    
					}
	            }
				fclose($file);
				$this->session->set_flashdata('message', 'Data are imported successfully..');
				redirect('Stock_update/stock_RawPrReceipt/'.$stck_id);
			}else{
				$this->session->set_flashdata('message', 'Something went wrong..');
				redirect('Stock_update/stock_update');
			}
		}
	}

	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('Stock_update/stockUpdate/');
					}
					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();
        		    	$i=0;
        				while (($data = fgetcsv($file, 10000, ",")) !== FALSE)
        				{
        				    if($data[5] != '')
        				    {
        					$res3=$this->db->query("select * from recipe 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 recipe 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')");				
        					
        					}
        				}
        				}
	                }
	            }
				fclose($file);
				$this->session->set_flashdata('message', 'Data are imported successfully..');
				redirect('Stock_update/stock_RawPrReceipt/'.$stck_id);
			}else{
				$this->session->set_flashdata('message', 'Something went wrong..');
				redirect('Stock_update/stock_update');
			}
		}
	}

	public function stock_RawPrReceipt($stck_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['stock_update'] = $this->stockupdate_model->stock_update($stck_id);
		$data['stk_update_items'] = $this->stockupdate_model->stk_update_items($stck_id);
		$this->load->view('Stock_update/stock_RawReceipt',$data);
	}
	
	public function stSttockUpdate()
	{
		$sub_mod_id = $this->uri->segment(3);
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['cdept'] = $this->stockupdate_model->getCounter($sub_mod_id,$branch_id);
		$this->load->view('Stock_update/st_stock_update',$data);
	}
	
	public function fetchProduct()
	{
		$postdata = file_get_contents("php://input");
		$request = json_decode($postdata);
		$branch_id = $request->branch_id;
		$item_data = $this->stockupdate_model->fetchProduct($branch_id);
		foreach ($item_data as $item) 
		{ 
			$data[] = array(
			"iname"          => $item->rname,
			"uom"  			=> $item->uom,
			"cat_id"          => $item->pr_cat_id,
			"flavour"  			=> $item->flavour,
			"f_code"          => $item->f_code,
			"id"  			=> $item->recipe_id,
			"qty"          => 0,
			"rno"  			=> $item->recipe_no,
			"pr_stk"    => $item->production_stock
			);
		} 
		echo json_encode($data);
	}
	
	public function addStStock()
	{
		$stck_id=$this->stockupdate_model->addStStock($this->input->post());
		//redirect('Stock_update/stk_transfer_inv/'.$sid);
		redirect('Stock_update/stock_RawPrReceipt/'.$stck_id);
	}
	
	public function allStock_update_list($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['branch'] = $this->user_model->get_branch();
		$data['branch'] = $this->stockmanage_model->get_Abranch();
		$data['stock_update'] = $this->stockupdate_model->allstock_update_list();
		$this->load->view('Stock_update/Allstock_up_list',$data);
		
	}
    
    public function getAllStockUpdate($sub_mod_id){
		
		$branch_id = $_SESSION['branch_id'];
		$data = $this->stockupdate_model->allstock_update_list();
        $count=1;
        $test = array();
        foreach($data as $row)
    	{
    	    
    	    $view = "<a href='$this->master_url/index.php/Stock_update/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 searchCStockUpdate()
	{
		$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');
		$branch = $this->input->post('branch');
		
		$data1 = array(
		'from_date' => $from_date,
		'to_date' => $to_date,
		'branch' =>$branch
		);
		if ($from_date == "" && $to_date == "") {
			$data['date_range_error_message'] = "All feilds are required";
			} else {
			$result = $this->stockupdate_model->getCStockUpdate($data1);
			if ($result != false) {
				$data['result_display'] = $result;
				} else {
				$data['result_display'] = "No record found !";
			}
		}
		//$data['branch'] = $this->user_model->get_branch();
		$data['branch'] = $this->stockmanage_model->get_Abranch();
		$data['items'] = $this->master_model->get_Items($branch_id);
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$this->load->view('Stock_update/Allstock_up_list',$data);
	}

	public function export_stkUpdate(){
	
		$from_date = date('Y-m-d',strtotime($this->input->post('from_date1')));;
		$to_date = date('Y-m-d',strtotime($this->input->post('to_date1')));
		$branchn = $this->input->post('branchn');
		$this->load->dbutil();
		$this->load->helper('file');
		$this->load->helper('download');
		$delimiter = ",";
		$newline = "\r\n";
		
		$filename = "Stock_Update_Report.csv";
		$query = "SELECT stock_no,DATE_FORMAT(stk_date, '%d-%m-%Y') as stk_date,branchname FROM stock_update where stk_date between '$from_date' and '$to_date' and branchname='$branchn' and stock_no LIKE 'S%'";
		$result = $this->db->query($query);
		$data = $this->dbutil->csv_from_result($result, $delimiter, $newline);
		force_download($filename, $data);
		
	}

	public function allDailyStock_update_list($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['branch'] = $this->user_model->get_branch();
		$data['branch'] = $this->stockmanage_model->get_Abranch();
		
		$data['stock_update'] = $this->stockupdate_model->alldailystock_update_list();
		$this->load->view('Stock_update/AllDailystock_up_list',$data);
		
	}
	
	public function getADStockUpdate($sub_mod_id){
		
		$branch_id = $_SESSION['branch_id'];
		$data = $this->stockupdate_model->alldailystock_update_list();
        $count=1;
        $test = array();
        foreach($data as $row)
    	{
    	    
    	    $view = "<a href='$this->master_url/index.php/Stock_update/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 searchCDailyStockUpdate()
	{
		$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');
		$branch = $this->input->post('branch');
		
		$data1 = array(
		'from_date' => $from_date,
		'to_date' => $to_date,
		'branch' =>$branch
		);
		if ($from_date == "" && $to_date == "") {
			$data['date_range_error_message'] = "All feilds are required";
			} else {
			$result = $this->stockupdate_model->getCDailyStockUpdate($data1);
			if ($result != false) {
				$data['result_display'] = $result;
				} else {
				$data['result_display'] = "No record found !";
			}
		}
		$data['branch'] = $this->user_model->get_branch();
		$data['items'] = $this->master_model->get_Items($branch_id);
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$this->load->view('Stock_update/AllDailystock_up_list',$data);
	}
	
	public function export_dstkUpdate(){
	
		$from_date = date('Y-m-d',strtotime($this->input->post('from_date')));;
		$to_date = date('Y-m-d',strtotime($this->input->post('to_date')));
		$branchn = $this->input->post('branchn');
		$this->load->dbutil();
		$this->load->helper('file');
		$this->load->helper('download');
		$delimiter = ",";
		$newline = "\r\n";
		
		$filename = "DailyStock_Update_Report.csv";
		$query = "SELECT stock_no,DATE_FORMAT(stk_date, '%d-%m-%Y') as stk_date,branchname FROM stock_update where stk_date between '$from_date' and '$to_date' and branchname='$branchn' and stock_no LIKE 'D%'";
		$result = $this->db->query($query);
		$data = $this->dbutil->csv_from_result($result, $delimiter, $newline);
		force_download($filename, $data);
		
	}


	public function stockUpdateCw(){
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$this->load->view('Stock_update/stockUpdateCw',$data);
	}

	public function import_StockCW(){
		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();
		    	$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'];
					 	
						$pr=$this->db->query("select * from item_creation where itm_id='$itm_id[$i]' and branchname='STR'");
	        			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')");				
					
					}
				}
				}                   
				fclose($file);
				$this->session->set_flashdata('message', 'Data are imported successfully..');
				redirect('Stock_update/stock_receipt/'.$stck_id);
			}else{
				$this->session->set_flashdata('message', 'Something went wrong..');
				redirect('Stock_update/stockUpdateCw');
			}
		}
	}
	
	
	public function dailyStkUpdate(){
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		
		$data['items'] = $this->master_model->get_Items($branch_id);
		$data['rcat'] = $this->stockupdate_model->get_rwCategory();
		$data['pcat'] = $this->stockupdate_model->get_fpCategory();
		$this->load->view('Stock_update/dailyStkUpdate',$data);
	}

    
	public function insertDstkItem(){
	    $stk_date = date("Y-m-d");
		$order_time = date("h:i A");
		$lm=date("Y-m-dH:i:s",time());
		$branchname = $_SESSION['branch_name'];
		$branch_id = $_SESSION['branch_id'];
		$user = $_SESSION['full_name'];
				
		$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."/".$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','Finished Product')");
    	$stck_id = $this->db->insert_id();
    	$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'));
		$stk_qty=explode(',', $this->input->post('stk_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'));
		
		if($stck_id)
		{
    		for($i=0;$i<count($item_type),$i<count($item_name),$i<count($item_id),$i<count($uom),$i<count($prsnt_stk),$i<count($stk_qty);$i++) {
    			if($stk_qty[$i] != '0' and $stk_qty[$i] != '')
    			{				
        			$res3=$this->db->query("select * from recipe where recipe_id='$item_id[$i]'");
	        		if($res3->num_rows() > 0)
	        		{
	        			foreach($res3->result_array() as $res4)
	        			$qty[$i] = $res4['production_stock'];//present stock
						$qty1[$i] = (int)$qty[$i] - (int)$stk_qty[$i];//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,remarks)values('Finished Product','$item_name[$i]','$uom[$i]','$qty[$i]','$stk_qty[$i]','$stck_id','$item_id[$i]','$cat_id[$i]','$recipe_no[$i]','$remarks[$i]')");
        	
        				$res5=$this->db->query("UPDATE recipe set production_stock='$stk_qty[$i]' WHERE  recipe_id= '$item_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,recipe_no,category_id,branch_id)values('$item_name[$i]','$stock_no','$stk_date','$qty[$i]','$stk_qty[$i]','$lm','$branchname','$item_id[$i]','$recipe_no[$i]','$cat_id[$i]','$branch_id')");				
					
					}
    			}
    		}
		}
		if($stck_id)
		//echo "success";
		echo $stck_id;
		
		else
		//echo json_encode(array('reslt' => 'error', 'did' => $did));
		echo "error";
		//$this->session->set_flashdata('message', 'Data are updated successfully..');
		//redirect('Stock_update/dstkstock_receipt/'.$stck_id);
	}
	
}
?>