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

class LocationTransfer 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('Location_transfer');
		$this->lang->load("loctransfer",$this->session->userdata('language'));	
	}
	public function home(){
		header("HTTP/1.1 301 Moved Permanently"); 
		header("Location: ".base_url()."locationtransfer"); 
	}
	public function index(){
		//Retrive location transfer informations
		$this->load->model('Location_transfer');
		$data['datatbls'] = $this->Location_transfer->get_loc_transfer_all(element('compID', $this->session->userdata('logged_in')));
		
		
		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js')
					->add_includes('js/validationengine/jquery.validationEngine.js');
		$this->layouts->view('locationtransfer/loctranslist', array('latest' => 'sidebar/latest'), $data);
	}
    
	//Confirm transaction
	public function confirm(){
		$locTrasList = explode(',',$this->input->post('locID'));
		
		foreach($locTrasList as $v){
			$this->Location_transfer->confirm($v,element('compID', $this->session->userdata('logged_in')));
		}
		$this->session->set_flashdata('msg','Transfer Location confirmed');
		echo 'success';
		exit();
	}
	
	//Get items
	public function get_items(){
		$this->load->model('item/ItemSetup_model');
		
		// URL structure = locationtransfer/get_items/item_ids/1-2-4-7
		$itemIds = explode('-',$this->uri->segment(4));
		$itemDetails = array();
		foreach($itemIds as $item){
			$temp = $this->ItemSetup_model->get_byID($item);
			$itemDetails[] =(array) $temp[0];
		}
		echo json_encode($itemDetails);
	}
	
	//Gather item information based on the location
	public function ajax_get_itembyLoc(){
		$items = $this->Location_transfer->itemByLoc($this->input->post('loc'));
		echo $this->getItemCodes($items);
		exit();
	}
	
	//Add location transfer
	public function add(){
		if($this->input->post('postloctrans')){
			//Insert Location Transfer informations
			$newloctrans = array(
				'companyID'			=> element('compID', $this->session->userdata('logged_in')), 
				'fromLocationID'	   => $this->input->post('fromLocationID'), 
				'toLocationID'		 => $this->input->post('toLocationID'),
				'formNo'			   => $this->input->post('formNo'),
				'movementTypeID'	   => $this->input->post('movementTypeID'),
				'dateTransfer'		 => date('Y-m-d',strtotime($this->input->post('dateTransfer'))),
				'memo'	   			 => $this->input->post('memo')			
			);
		  	$loctransId = $this->Location_transfer->insert($newloctrans);
			
			
			if($loctransId){
				//Insert items for location transfer
				$i = 0;
				if(is_array($this->input->post('itemList'))){
					foreach($this->input->post('itemList') as $item){
						$newloctransdetail = array(
							'locationTransferID'	=> $loctransId, 
							'itemID'	  	 	   => $item, 
							'quantity'		     => $_POST['quantity'][$i],
							'fromStock'			=> $_POST['stock'][$i],
							'createdTS'	   		=> date('Y-m-d G:i:s',time())				
						);
					
						$loctransDetailId = $this->Location_transfer->insertDetail($newloctransdetail);
						$i++;
					}
				}
				echo '<script>alert("Insert Data Success..");
				window.location.replace("'.base_url().'/locationtransfer");
				</script>';
			}else{
				
				echo '<script>alert("Insert Data Failed.");
					history.go(-1); </script>';
			}
		}else{
			$this->load->library('layouts');
			$this->load->helper('form');
			$this->load->helper('menu');
			$this->load->model('master/masterCode_model');
			$this->lang->load("loctransfer",$this->session->userdata('language'));	
			
			//Form setup
			$this->load->model('company/formSetup_Model');
			$filter['companyID']=element('compID', $this->session->userdata('logged_in'));
			$filter['formID']=46;
			$data['formNo']= $this->formSetup_Model->getFormNo($filter);
			
			// Gather predefined values of form
			$data['itemCategory'] = $this->masterCode_model->get_all(array('masterID'=>20));
			$data['fromLocation'] = $this->Location_transfer->location_byCompany(1);
			
			// Gather Item according to location
			$this->load->model('item/ItemSetup_model');
			
			
			//Gather all items		
			$data['items'] = $this->ItemSetup_model->get_all();
			$data['itemCodes'] = $this->getItemCodes($data['items']);
			
			$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js')
						->add_includes('js/validationengine/languages/jquery.validationEngine-'.$this->session->userdata('language').'.js')
						->add_includes('js/validationengine/jquery.validationEngine.js');
			$this->layouts->view('locationtransfer/addloctrans', array('latest' => 'sidebar/latest'), $data);
		}
	}
	//Edit location transfer
	
	public function edit(){
		if($this->input->post('update')){
			$this->output->enable_profiler(TRUE);
			
			//Insert Location Transfer informations
			$newloctrans = array(
				'companyID'			=> element('compID', $this->session->userdata('logged_in')), 
				'fromLocationID'	=> $this->input->post('fromLocationID'), 
				'toLocationID'		=> $this->input->post('toLocationID'),
				'formNo'			=> $this->input->post('formNo'),
				'movementTypeID'	=> $this->input->post('movementTypeID'),
				'dateTransfer'		=> date('Y-m-d',strtotime($this->input->post('dateTransfer'))),
				'memo'	   			=> $this->input->post('memo'),
			);
			
		  	$loctransId = $this->Location_transfer->update($this->input->post('ID'),$newloctrans);
			if($loctransId >= 1){
				echo "success";
			}else{
				echo false;
			}
			exit();
		}else{
			$data['datatbls'] = $this->Location_transfer->get_loc_trans_by_id($this->uri->segment(3));
			
					
			$this->load->library('layouts');
			$this->load->helper('form');
			$this->load->helper('menu');
			$this->load->model('master/masterCode_model');
			$this->lang->load("loctransfer",$this->session->userdata('language'));	
			
			//Form setup
			$this->load->model('company/formSetup_Model');
			$filter['companyID']=element('compID', $this->session->userdata('logged_in'));
			$filter['formID']=46;
			$data['formNo']= $this->formSetup_Model->getFormNo($filter);
			
			// Gather predefined values of form
			$data['itemCategory'] = $this->masterCode_model->get_all(array('masterID'=>20));
			$data['fromLocation'] = $this->Location_transfer->location_byCompany(1);
			
			
			// Gather Item according to location
			$this->load->model('item/ItemSetup_model');
			
			
			//Gather all items		
			$data['items'] = $this->ItemSetup_model->get_all();
			$data['itemCodes'] = $this->getItemCodes($data['items']);
			
			
			$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js')
						->add_includes('js/validationengine/languages/jquery.validationEngine-'.$this->session->userdata('language').'.js')
						->add_includes('js/validationengine/jquery.validationEngine.js');
			$this->layouts->view('locationtransfer/editloctrans', array('latest' => 'sidebar/latest'), $data);
		}
	}
	
	//Update Row values
	public function updaterow(){
		$newloctrans = array( 
			'quantity'			=> $this->input->post('quantity'),
			'fromStock'			=> $this->input->post('stock')
		);
		
		$loctransId = $this->Location_transfer->updaterow($this->input->post('ID'),$newloctrans);
		if($loctransId >= 1){
			echo "success";
		}else{
			echo false;
		}
		exit();
	}
	
	//Location Transfer List
	public function loctrans_list()
	{
		$this->load->library('layouts');
		$this->load->helper('form');
		$this->load->helper('menu');
		$this->lang->load("loctransfer",$this->session->userdata('language'));
	    $this->load->model('Location_transfer');
		$data['datatbls'] = $this->Location_transfer->location_transfer_all();
		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
		$this->layouts->view('locationtransfer/list', array('latest' => 'sidebar/latest'), $data);
	}
	
	//Delete location transfer items entry
	public function removeitem(){
		if($this->input->post('delete')){
			$delete = $this->Location_transfer->removeItem($this->input->post('ID'));	
		}
		if($delete >= 1){
			echo "success";
		}
		exit();
	}
	
	//Remove location transfer
	public function delete(){
		$remove = $this->Location_transfer->remove($this->uri->segment(3));
		if($remove >=1){
			header('Location: '.base_url().'/locationtransfer');
		}
		exit();
	}
	
	//New design functions
	
	
	/******************************/
	//Ajax get items
	public function ajax_get_items(){
		if($this->input->post('itemCode')){
			$itemName = explode('-',$this->input->post('itemCode'));
			$items = $this->Location_transfer->get_byID($itemName[0],$this->input->post('locID'));
			echo json_encode($items);
		}else{
			echo 'No Data';
		}
		
		exit();
	}
	
	public function getItemCodes($items){
		if(!empty($items)){
			$JsonRecords = '[';
			$i= 0;
			 foreach($items as $row){
				if(!$i){
					$JsonRecords .= '&quot;'.$row->itemCode.'-'.$row->name.'&quot;';
				}else{
					$JsonRecords .= ', &quot;'.$row->itemCode.'-'.$row->name.'&quot;';
				}
				$i++;
			}
			 $JsonRecords .= ']';
			return $JsonRecords;
		}else{
			return '';
		}
	}
	//Add items as transfer location
	public function ajax_save_item(){
		if($this->input->post('postloctrans')){
			if($this->input->post('ID') == ''){
				//Insert Location Transfer informations
				$newloctrans = array(
					'companyID'			=> element('compID', $this->session->userdata('logged_in')), 
					'fromLocationID'	=> $this->input->post('fromLocationID'), 
					'toLocationID'		=> $this->input->post('toLocationID'),
					'formNo'			=> $this->input->post('formNo'),
					'movementTypeID'	=> $this->input->post('movementTypeID'),
					'dateTransfer'		=> date('Y-m-d',strtotime($this->input->post('dateTransfer'))),
					'memo'	   			=> $this->input->post('memo'),			
					'createdBy'			=>	element('role',$this->session->userdata('logged_in'))
				);
				$loctransId = $this->Location_transfer->insert($newloctrans);
			}else{
				$loctransId = $this->input->post('ID');
			}
			$return[] = $loctransId;
			if($loctransId){
				$newloctransdetail = array( 
					'locationTransferID'=> $loctransId,
					'itemID'			=> $this->input->post('itemID'),
					'quantity'		    => $this->input->post('quantity'),
					'fromStock'			=> $this->input->post('stock'),			
					'createdBy'			=>	element('role',$this->session->userdata('logged_in'))
				);
				$return[] = $this->Location_transfer->insertDetail($newloctransdetail);
			}
			echo json_encode($return);
		}
		exit();
	}
	
	
	/*********************************************************
	*														 *
	*						Reporting						 *
	*														 *
	**********************************************************/
	
	public function report($srtDate = '',$endDate = ''){
		//including company information
		$this->load->model('company/company_info_model');
		$data['company'] = $this->company_info_model->companyById(element('compID', $this->session->userdata('logged_in')));
		
		
		//Report Listing
		if($srtDate == '') 	$srtDate = date('Y-m-d', strtotime(date('Y-m-1')));
		if($endDate == '') 	$endDate = date('Y-m-d', time());
		$data['dateFrom'] = $srtDate;
		$data['dateTo'] = $endDate;
		//Gather report data
		$data['datatbls'] = $this->Location_transfer->rptList(date('Y-m-d', strtotime($srtDate)),date('Y-m-d', strtotime($endDate)));
		if(!empty($data['datatbls'])) foreach($data['datatbls'] as &$v){ $v->updateable == 0?$v->updateable = "Yes":$v->updateable = "No"; }
		//Configuration for table header
		$data['tbHdr'] = array(
				'formNo' => 'formNo',
				'fromLoc' => 'fromLoc',
				'toLoc' => 'toLoc',
				'movType' => 'movType',
				'memo' => 'memo',
				'dateTransfer' => 'dateTransfer',
				'updateable' => 'updateable',
			);
		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
		$this->layouts->view('locationtransfer/loctransrpt', array('latest' => 'sidebar/latest'), $data);
	}
	
	//Printing report
	public function printReport($srtDate = '',$endDate = '', $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->load->model('purchase/purchase_model');
            $this->lang->load("loctransfer",$this->session->userdata('language'));
            
            //Report Listing
			if($srtDate == '') 	$srtDate = date('Y-m-d', strtotime(date('Y-m-1')));
			if($endDate == '') 	$endDate = date('Y-m-d', time());
			$data['dateFrom'] = $srtDate;
			$data['dateTo'] = $endDate;
			//Gather report data
			$data['datatbls'] = $this->Location_transfer->rptList(date('Y-m-d', strtotime($srtDate)),date('Y-m-d', strtotime($endDate)));
			if(!empty($data['datatbls'])) foreach($data['datatbls'] as &$v){ $v->updateable == 0?$v->updateable = "Yes":$v->updateable = "No"; }
			//Configuration for table header
			$data['tbHdr'] = array(
					'formNo' => 'formNo',
					'fromLoc' => 'fromLoc',
					'toLoc' => 'toLoc',
					'movType' => 'movType',
					'memo' => 'memo',
					'dateTransfer' => 'dateTransfer',
					'updateable'   => 'updateable'	
				);
             
             
             
             
             //$headerData['rightContentHeader'] = "Name supplier/ ot";
             $headerData['rptTitle'] = "Location Transfer Report";
             $headerData['rightContent'] = array("From: ".date('d-m-Y', strtotime($srtDate))." To: ".date('d-m-Y', strtotime($endDate)));
             //$headerData['leftContent'] = array("Left : value", "Left: value");
             
          //   $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("fromLoc"), $this->lang->line("toLoc"),$this->lang->line("movType"),$this->lang->line("memo"),$this->lang->line("dateTransfer"),$this->lang->line("updateable")); 
			$bodyData['selectFields'] = array("formNo", "fromLoc", "toLoc","movType","memo","dateTransfer","updateable");
			$bodyData ['tdAmount'] = array("amountApplied");
			//$bodyData['tableFooter'] = array ("footer : value");
			$bodyData['excelTitle'] = "Location Transfer Report";
			
			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);
			}
	}
	
	//Printing report detail
	public function reportdetail($locTransID,$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("loctransfer",$this->session->userdata('language'));
            
			//Gather report data
			$data['datatbls'] = $this->Location_transfer->rptDetail($locTransID);
			$data['transInfo'] = $this->Location_transfer->transDirect($locTransID);
			
			//Configuration for table header
			$data['tbHdr'] = array(
					'itemName' => 'itemName',
					'qtyOnHand' => 'qtyOnHand',
					'quantity' => 'quantity'
				);
             
             
             
             //$headerData['rightContentHeader'] = "Name supplier/ ot";
             $headerData['rptTitle'] = "Location Transfer Detail";
             $headerData['leftContent'] = array(
												"Location Transfer : ".$data['transInfo'][0]->locationTransfer,
												"Form No: ".$data['transInfo'][0]->formNo
											);
			 $headerData['rightContent'] = array(
												"Movement Type: ".$data['transInfo'][0]->movType,
												"Transfer Date: ".date('d-m-Y', strtotime($data['transInfo'][0]->dateTransfer))
											);
             
          //   $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("description"), $this->lang->line("qtyOnHand"), $this->lang->line("quantity")); 
			$bodyData['selectFields'] = array("itemName","description","qtyOnHand","quantity");
			$bodyData ['tdAmount'] = array("qtyOnHand","quantity");
			//$bodyData['tableFooter'] = array ("footer : value");
			$bodyData['excelTitle'] = "Location Transfer Detail";
				
		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);
		}	
	}
	
	
}