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

class Inventory extends CI_Controller {
	
	public function __construct(){
		parent::__construct();
		$this->load->library('layouts');
		$this->load->helper('form');
		$this->load->helper('menu');
		$this->layouts->set_title('iAccount');		
		
		$this->load->model('master/masterCode_model');
		$this->load->model('Menu');
		$this->load->model('inventory_report/Inventory_list');
		$this->lang->load("inventory",$this->session->userdata('language'));	
	}
	public function home(){
		header("HTTP/1.1 301 Moved Permanently"); 
		header("Location: ".base_url()); 
	}
	public function index(){
		header("HTTP/1.1 301 Moved Permanently"); 
		header("Location: ".base_url());
	}	
	
	
	/*********************************************************
	*														 *
	*						Reporting						 *
	*														 *
	**********************************************************/
	
	//Inventory report by locaiton
	public function rptByLocation($locID = ''){
		$data['datatbls'] = $this->Inventory_list->getInventoryByLoc($locID);
		
		//Loading location information
		$this->load->model('Location_transfer');
		$data['location'] = $this->Location_transfer->location_byCompany(element('compID', $this->session->userdata('logged_in')));
		$data['locID'] = $locID?$locID:'';
		
		//Configuration for table header
		$data['tbHdr'] = array(
				'itemName' => 'itemName',
				'category' => 'category',
				'description' => 'description',
				'stockValue' => 'stockValue',
			);
		//right aligned columns
		$data['alignRight'] = array();
		
		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js')
					->add_includes('js/validationengine/jquery.validationEngine.js');
		$this->layouts->view('inventory/bylocation', array('latest' => 'sidebar/latest'), $data);
	}
	
	//Printing report
	public function rptbylocationprint($locID = '',$mode=false){
		 
        
           // $this->load->model('company/company_info_model');
           	$this->load->model('company/company_info_model');
            $data['company'] = $this->company_info_model->companyById(element('compID', $this->session->userdata('logged_in'))); 
		   
            $this->lang->load("inventory",$this->session->userdata('language'));
            $this->load->model('Location');
			$data['location'] = $this->Location->location_id($locID);
			//Gather report data
			$data['datatbls'] = $this->Inventory_list->getInventoryByLoc($locID);
			
			//Configuration for table header
			$data['tbHdr'] = array(
					'itemName' => 'itemName',
					'category' => 'category',
					'description' => 'description',
					'stockValue' => 'stockValue',	
				);
             
             
             
             
             //$headerData['rightContentHeader'] = "Name supplier/ ot";
             $headerData['rptTitle'] = $this->lang->line("inventoryByLocation");
             $headerData['rightContent'] = array("As at: ".date("d-m-Y"));
			 if(!empty($data['location']))
             	$headerData['leftContent'] = array("Location : ".$data['location'][0]->code." (".$data['location'][0]->address.")");
             else
			 	$headerData['leftContent'] = array("Location : All");
          //   $headerData['company'] = $this->company_info_model->companyById(element('compID', $this->session->userdata('logged_in')));
              
			$bodyData['rptDataDetail'] = $data['datatbls'];
			$bodyData['tableHeader'] = array($this->lang->line("itemName"), $this->lang->line("category"), $this->lang->line("description"),$this->lang->line("stockValue")); 
			$bodyData['selectFields'] = array("itemName", "category", "description","stockValue");
			$bodyData['tdAmount'] = array("stockValue");
			//$bodyData['tableFooter'] = array ("footer : value");
        	$bodyData['excelTitle'] = $this->lang->line("inventoryByLocation");    
		if(!$mode){
			//print 
			$this->load->view('layouts/report/header', $headerData);
			$this->load->view('layouts/report/body', $bodyData);
			$this->load->view('layouts/report/footer','');
		}else{
			//download excell
			$this->load->helper('excel');			
			excel($bodyData);
		}	
	}
	 
	//Inventory subtotal detail information
	public function rptSubtotalDetail($itemID = '',$locID = '',$mode=false){
		// $this->load->model('company/company_info_model');
		$this->load->model('company/company_info_model');
		$data['company'] = $this->company_info_model->companyById(element('compID', $this->session->userdata('logged_in')));
		
		//location information
		$this->load->model('Location');
		$data['location'] = $this->Location->location_id($locID);
		
		//Gather report data
		$data['datatbls'] = $this->Inventory_list->rptSubtotalDetail($itemID,$locID);
		$balance = 0;
		if(!empty($data['datatbls'])){
			foreach($data['datatbls'] as &$row){
				$balance += $row->total;
			}
			$balance = number_format($balance, 2,'.',',');
		}
		
		
		//$headerData['rightContentHeader'] = "Name supplier/ ot";
		$headerData['rptTitle'] = $this->lang->line("inventoryByLocation");
		$headerData['rightContent'] = array("As at: ".date("d-m-Y"));
		if(!empty($data['location']))
			$headerData['leftContent'] = array("Location : ".$data['location'][0]->code." (".$data['location'][0]->address.")");
		else
			$headerData['leftContent'] = array("Location : All");
		
		//   $headerData['company'] = $this->company_info_model->companyById(element('compID', $this->session->userdata('logged_in')));
		
		$bodyData['rptDataDetail'] = $data['datatbls'];
		$bodyData['tableHeader'] = array($this->lang->line("itemCode"), $this->lang->line("itemName"),$this->lang->line("category"), $this->lang->line("unitOfMeasure"),$this->lang->line("balanceItem"), $this->lang->line("purchasePrice"),$this->lang->line("value"));
		$bodyData['selectFields'] = array( "itemCode", "itemName","Category", "unit","balanceItem","unitPrice","total");
		$bodyData ['tdAmount'] = array("unit","balanceItem","unitPrice","total");
		$bodyData ['tdNoFormat'] = array("unit","balanceItem");
		$bodyData['tableFooter'] = array ("Total : ".$balance);
		$bodyData['excelTitle'] = $this->lang->line("inventoryMovement");
		
		if(!$mode){
			//print
			$this->load->view('layouts/report/header', $headerData);
			$this->load->view('layouts/report/body', $bodyData);
			$this->load->view('layouts/report/footer','');
		}else{
			//download excell
			$this->load->helper('excel');
			excel($bodyData);
		}
	}
	/****************************************************
	
			Inventory movement report
			
	*****************************************************/
	
	//Inventory movement report
	public function rptmovement($dateFrom = '',$dateTo = '',$locID = '',$itemID = ''){		
		if($dateFrom == '')  $dateFrom= date('Y-m-d', strtotime(date('Y-m-1')));
		if($dateTo == '')	 $dateTo= date('Y-m-d', time());
		
		$data['dateFrom'] = $dateFrom;
		$data['dateTo'] = $dateTo;
		if($dateFrom != '' && $dateTo != '' && $locID != '' && $itemID != '')
			$data['datatbls'] = $this->Inventory_list->getInventoryByMovement($dateFrom,$dateTo,$locID,$itemID);
		else	$data['datatbls'] = '';
		
		//print_r($data['datatbls']);
		//exit();
		//Loading location information
		$this->load->model('Location_transfer');
		$data['location'] = $this->Location_transfer->location_byCompany(element('compID', $this->session->userdata('logged_in')));
		$data['locID'] = $locID?$locID:'';
		
		//define in/out information
		$balance = 0;
		if(!empty($data['datatbls'])){
			foreach($data['datatbls'] as &$row){
				$row->balance = $balance += $row->quantityIn + $row->quantityOut; 
			}
		}
		//Configuration for table header
		$data['tbHdr'] = array(
				'formNo'	=> 'formNo',
				'supplierCustomer' => 'supplierCustomer',
				'TransactionDate' => 'TransactionDate',
				'unitOfMeasure' => 'unitOfMeasure',
				'transactionType' => 'transactionType',
				'quantityIn' => 'quantityIn',
				'quantityOut' => 'quantityOut',
				'balance'	=>	'balance',
			);
		//right aligned columns
		$data['alignRight'] = array("quantityIn","quantityOut","balance");
		
		//get item list
		$data['itemList'] = $this->Inventory_list->getItemsbyLoc($locID);
		$data['itemID'] = $itemID;
		
		
		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js')
					->add_includes('js/validationengine/jquery.validationEngine.js');
		$this->layouts->view('inventory/rptmovement', array('latest' => 'sidebar/latest'), $data);
	}
	//Get item list according to location
	public function getItemByLoc(){
		$locID = $this->input->post('locID');
		$data['items'] = $this->Inventory_list->getItemsbyLoc($locID);
		echo '<option value="">--Select Item--</option>';
		
		if(!empty($data['items'])):
			foreach($data['items'] as $row){
				echo '<option value="'.$row->ID.'">'.$row->name.'</option>';
			}
		endif;
		exit();
	}
	//Inventory movement report
	public function rptmovementprint($dateFrom = '',$dateTo = '',$locID = '',$itemID = '',$mode=false){
		
		//Loading company information
		$this->load->model('company/company_info_model');
		$data['company'] = $this->company_info_model->companyById(element('compID', $this->session->userdata('logged_in'))); 
	   
		$this->lang->load("inventory",$this->session->userdata('language'));
		$this->load->model('Location');
		$data['location'] = $this->Location->location_id($locID);
		
		//Gather report data
		if($dateFrom != '' && $dateTo != '' && $locID != '' && $itemID != '')
			$data['datatbls'] = $this->Inventory_list->getInventoryByMovement($dateFrom,$dateTo,$locID,$itemID);
		else	$data['datatbls'] = '';		
		//define in/out information
		$balance = 0;
		if(!empty($data['datatbls'])){
			foreach($data['datatbls'] as &$row){						
				$row->balance = $balance += $row->quantityIn + $row->quantityOut; 
			}
		}
		
		//Configuration for table header
		$data['tbHdr'] = array(
				'formNo' => 'formNo',
				'supplierCustomer' => 'supplierCustomer',
				'TransactionDate' => 'TransactionDate',
				'unitOfMeasure' => 'unitOfMeasure',
				'transactionType' => 'transactionType',
				'quantityIn' => 'quantityIn',
				'quantityOut' => 'quantityOut',
				'balance'	=> 'balance'
			);
		 
		 
		 
		 
		 $headerData['rightContentHeader'] = "Name supplier/ ot";
		 $headerData['rptTitle'] = $this->lang->line("inventoryMovement");
		 $headerData['rightContent'] = array("Date: from ".$dateFrom." to ".$dateTo);
		 if(!empty($data['location']))
			$headerData['leftContent'] = array("Item Name: ".$data['datatbls'][0]->name,"Location : ".$data['location'][0]->code." (".$data['location'][0]->address.")");
		 else
			$headerData['leftContent'] = array("Location : All");
	  //   $headerData['company'] = $this->company_info_model->companyById(element('compID', $this->session->userdata('logged_in')));
		  
		$bodyData['rptDataDetail'] = $data['datatbls'];
		$bodyData['tableHeader'] = array($this->lang->line("formNo"), $this->lang->line("supplierCustomer"),$this->lang->line("TransactionDate"), $this->lang->line("unitOfMeasure"),$this->lang->line("transactionType"), $this->lang->line("quantityIn"),$this->lang->line("quantityOut"),$this->lang->line("balance")); 
		$bodyData['selectFields'] = array( "formNo", "supplierCustomer","TransactionDate", "unitOfMeasure","transactionType","quantityIn","quantityOut","balance");
		$bodyData ['tdAmount'] = array("balance","quantityIn","quantityOut");
		$bodyData['tableFooter'] = array ("Balance : ".$balance);
		$bodyData['excelTitle'] = $this->lang->line("inventoryMovement");
		
		if(!$mode){
			//print 
			$this->load->view('layouts/report/header', $headerData);
			$this->load->view('layouts/report/body', $bodyData);
			$this->load->view('layouts/report/footer','');
		}else{
			//download excell
			$this->load->helper('excel');			
			excel($bodyData);
		}
	}
	
	/*********************************************************
	*														 *
	*				Inventory Status						 *
	*														 *
	**********************************************************/
	
	public function rptstatus($locID = ''){		
		//Loading location information
		$this->load->model('Location_transfer');
		$data['location'] = $this->Location_transfer->location_byCompany(element('compID', $this->session->userdata('logged_in')));
		$data['locID'] = $locID?$locID:'';
		
		//gether item information
		if($locID != ''){
			$data['datatbls'] = $this->Inventory_list->getInventoryStatus($locID);
		}
		//Configuration for table header
		$data['tbHdr'] = array(
				'itemCode'	=> 'itemCode',
				'name' => 'name',
				'qtyOnHand' => 'qtyOnHand',
				'salesBalance' => 'salesBalance',
				'purchaseBalance' => 'purchaseBalance'
		);
		//right aligned columns
		$data['alignRight'] = array("qtyOnHand","salesBalance","purchaseBalance");
		
		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js')
						->add_includes('js/validationengine/jquery.validationEngine.js');
		$this->layouts->view('inventory/rptstatus', array('latest' => 'sidebar/latest'), $data);
	}
	
	//Inventory status report
	public function rptstatusprint($locID = '',$mode = false){
	
		//Loading company information
		$this->load->model('company/company_info_model');
		$data['company'] = $this->company_info_model->companyById(element('compID', $this->session->userdata('logged_in')));
	
		$this->lang->load("inventory",$this->session->userdata('language'));
		$this->load->model('Location');
		$data['location'] = $this->Location->location_id($locID);
	
		//gether item information
		if($locID != ''){
			$data['datatbls'] = $this->Inventory_list->getInventoryStatus($locID);
		}
		
		//Configuration for table header
		$data['tbHdr'] = array(
				'itemCode'	=> 'itemCode',
				'name' => 'name',
				'qtyOnHand' => 'qtyOnHand',
				'salesBalance' => 'salesBalance',
				'purchaseBalance' => 'purchaseBalance'
		);
			
			
			
			
		$headerData['rightContentHeader'] = "Name supplier/ ot";
		$headerData['rptTitle'] = $this->lang->line("inventoryStatus");
		$headerData['rightContent'] = array("As at: ".date("d-m-Y"));
		$headerData['leftContent'] = array("Location : ".$data['location'][0]->code." (".$data['location'][0]->address.")");
		
		//   $headerData['company'] = $this->company_info_model->companyById(element('compID', $this->session->userdata('logged_in')));
	
		$bodyData['rptDataDetail'] = $data['datatbls'];
		$bodyData['tableHeader'] = array($this->lang->line("itemCode"), $this->lang->line("name"), $this->lang->line("qtyOnHand"),$this->lang->line("salesBalance"), $this->lang->line("purchaseBalance"));
		$bodyData['selectFields'] = array( "itemCode", "name","qtyOnHand","salesBalance", "purchaseBalance");
		$bodyData ['tdAmount'] = array("qtyOnHand","salesBalance", "purchaseBalance");
		//$bodyData['tableFooter'] = array ("Balance : ".$balance);
		$bodyData['excelTitle'] = $this->lang->line("inventoryStatus");
		
		if(!$mode){
			//print 
			$this->load->view('layouts/report/header', $headerData);
			$this->load->view('layouts/report/body', $bodyData);
			$this->load->view('layouts/report/footer','');
		}else{
			//download excell
			$this->load->helper('excel');			
			excel($bodyData);
		}
	}
	
	/****************************************************
	
	GRN Valuation Report
		
	*****************************************************/
	
	//GRN Valuation report
	public function rptgrnvaluation($dateFrom = '',$dateTo = ''){		
		if($dateFrom == '')  $dateFrom= date('Y-m-d', strtotime(date('Y-m-1')));
		if($dateTo == '')	 $dateTo= date('Y-m-d', time());
		
		$data['dateFrom'] = $dateFrom;
		$data['dateTo'] = $dateTo;
		if($dateFrom != '' && $dateTo != '')
			$data['datatbls'] = $this->Inventory_list->getGrnValuation($dateFrom,$dateTo);
		else	$data['datatbls'] = '';
		
		
		//Configuration for table header
		$data['tbHdr'] = array(
				'itemCode'	=> 'itemCode',
				'itemName' => 'itemName',
				'poNo' => 'poNo',
				'PoDate' => 'PoDate',
				'unitPrice' => 'unitPrice',
				'quantityOrder' => 'quantityOrder',
				'Qty' => 'Qty',
				'total' => 'total',
			);
		//right aligned columns
		$data['alignRight'] = array("quantityOrder","unitPrice","Qty","total");
		//No number formating
		$data['noFormat'] = array("quantityOrder","Qty");
		
		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js')
					->add_includes('js/validationengine/jquery.validationEngine.js');
		$this->layouts->view('inventory/rptgrnvalue', array('latest' => 'sidebar/latest'), $data);
	}
	
	//GRN Valuation report print
	public function rptgrnvaluationprint($mode=false){
	
		//Loading company information
		$this->load->model('company/company_info_model');
		$data['company'] = $this->company_info_model->companyById(element('compID', $this->session->userdata('logged_in')));
	
		$this->lang->load("inventory",$this->session->userdata('language'));
			
		//Gather report data
		$data['datatbls'] = $this->Inventory_list->getGrnValuation();
		
	
		//Configuration for table header
		$data['tbHdr'] = array(
				'itemCode'	=> 'itemCode',
				'itemName' => 'itemName',
				'poNo' => 'poNo',
				'PoDate' => 'PoDate',
				'unitPrice' => 'unitPrice',
				'quantityOrder' => 'quantityOrder',
				'Qty' => 'Qty',
				'total' => 'total',
		);
			
			
		$headerData['rightContentHeader'] = "Name supplier/ ot";
		$headerData['rptTitle'] = $this->lang->line("grnvaluetitle");
		$headerData['rightContent'] = array("As at: ".date("d-m-Y"));
		//$headerData['leftContent'] = array("Item Name: ".$data['datatbls'][0]->name,"Location : ".$data['location'][0]->code." (".$data['location'][0]->address.")");
		//   $headerData['company'] = $this->company_info_model->companyById(element('compID', $this->session->userdata('logged_in')));
	
		$bodyData['rptDataDetail'] = $data['datatbls'];
		$bodyData['tableHeader'] = array(
										$this->lang->line("itemCode"), 
										$this->lang->line("itemName"),
										$this->lang->line("poNo"), 
										$this->lang->line("PoDate"), 
										$this->lang->line("unitPrice"),
										$this->lang->line("quantityOrder"), 
										$this->lang->line("Qty"), 
										$this->lang->line("total")
									);
		$bodyData['selectFields'] = array( "itemCode", "itemName","poNo","PoDate", "unitPrice","quantityOrder","Qty","total");
		$bodyData['tdAmount'] = array("quantityOrder","unitPrice","Qty","total");
		$bodyData['tdNoFormat'] = array("quantityOrder","Qty");
		$bodyData['excelTitle'] = $this->lang->line("grnvaluetitle");
		//$bodyData['tableFooter'] = array ("Balance : ".$balance);
	
		if(!$mode){
			//print
			$this->load->view('layouts/report/header', $headerData);
			$this->load->view('layouts/report/body', $bodyData);
			$this->load->view('layouts/report/footer','');
		}else{
			//download excell
			$this->load->helper('excel');			
			excel($bodyData);
		}
	}
	
	public function stocklist(){
		$this->load->library('layouts');
		$this->load->helper('form');
		$this->load->helper('menu');
		$this->load->model('item/itemSetup_model');
		//$this->load->model('inventory_report/Inventory_list');
		$data['datatbls'] = $this->itemSetup_model->getItemListByLocation();
		//$data['datatbls'] = $this->itemSetup_model->get_all();
		$this->lang->load("item",$this->session->userdata('language'));
		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
		$this->layouts->view('inventory/stocklist', array('latest' => 'sidebar/latest'), $data);
	}
	
	//Inventory - Stock Check 
	public function StockCheckRpt($idLocation = '',$mode = false){
		
		     $this->load->library('layouts');
			 $this->load->model('item/itemSetup_model');
			 $this->load->model('inventory_report/Inventory_list');
			 $this->load->model('company/company_info_model');
			 $this->load->model('Location');
			 
			 $this->lang->load("item",$this->session->userdata('language'));
		
            // $headerData['id'] = $id;
             $headerData['rightContentHeader'] = "Location";
             $headerData['rptTitle'] = $this->lang->line("rptTitle");
             $headerData['rightContent'] = array("As at: ".date("d-m-Y"));
             $headerData['leftContent'] = array("Stock Check List : All");
             
            $headerData['company'] = $this->company_info_model->companyById(element('compID', $this->session->userdata('logged_in')));
             
             $bodyData['rptDataDetail'] =$this->itemSetup_model->getItemListByLocation($idLocation);
			 //var_dump($bodyData['rptDataDetail']);
             $bodyData['tableHeader'] = array("Item Name", "Description", "Available Balance", "ReOrder Level", "Status"); 
             $bodyData['selectFields'] = array("item","description","quantity","reorderLevel","itemStatusID",);
			 $bodyData['tdAmount'] = array("quantity","reorderLevel","itemStatusID");
			 $bodyData['tdNoFormat'] = array("quantity","reorderLevel","itemStatusID");
          
            
            $this->load->view('layouts/report/header', $headerData);
            $this->load->view('layouts/report/body', $bodyData);
            $this->load->view('layouts/report/footer','');
        }


	public function StockCheckDetails($idLocation = '',$mode = false){
		
		     $this->load->library('layouts');
			 $this->load->model('item/itemSetup_model');
			  $this->load->model('inventory_report/inventory_list');
			 $this->load->model('company/company_info_model');
			 $this->load->model('Location');
			 
			 $this->lang->load("item",$this->session->userdata('language'));
			 
			 $data['datatbls'] = $this->itemSetup_model->getItemListByLocation($idlocation);
		
            // $headerData['id'] = $id;
             $headerData['rightContentHeader'] = "Location";
             $headerData['rptTitle'] = $this->lang->line("rptTitle");
             $headerData['rightContent'] = array("As at: ".date("d-m-Y"));
             $headerData['leftContent'] = array("Stock Check List : All");
             
            $headerData['company'] = $this->company_info_model->companyById(element('compID', $this->session->userdata('logged_in')));
              
             $bodyData['rptDataDetail'] =$this->Inventory_list->getInventoryByLoc($locID);
             $bodyData['tableHeader'] = array("Item Category", "Item Name", "Available Balance", "Re Order Level", "Status"); 
             $bodyData['selectFields'] = array("itemCategoryID", "name","quantity","reorderLevel","itemStatusID",);
			 
			 $bodyData['tdAmount'] = array("quantity","reorderLevel","itemStatusID");
			 $bodyData['tdNoFormat'] = array("quantity","reorderLevel","itemStatusID");
          
            
            $this->load->view('layouts/report/header', $headerData);
            $this->load->view('layouts/report/body', $bodyData);
            $this->load->view('layouts/report/footer','');
        }
}