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

class ItemCountAdjust extends CI_Controller{
	
	
	public function __construct(){
		parent::__construct();
		$this->load->model('Useraccess');
		$query = $this->Useraccess->useraccess_id_module2('4', 'transaction');
		if(!$query){
			echo '<script>alert("Not authorised..");
				window.location.replace("'.base_url().'Error");
				</script>';
		}
		
		$this->load->library('layouts');
		
		//loading number to word language pack
		/*$this->lang->load("num_to_word",$this->session->userdata('language'));
		$this->load->helper('num_to_word');*/
		
		$this->layouts->set_title('iAccount::Item Count and Adjust Pricing');
		
		$this->load->model('master/masterCode_model');
		$this->load->model('Menu');
		$this->load->model('Item_count_adjust');		
		$this->load->library('layouts');
		$this->layouts->add_includes('js/validationengine/languages/jquery.validationEngine-'.$this->session->userdata('language').'.js')
			 		  ->add_includes('js/validationengine/jquery.validationEngine.js');
		$this->lang->load("itemcountadjust",$this->session->userdata('language'));	
	}
	
	public function index($locID = ''){
		//Gether location list
		$this->load->model('Location');
		$data['location'] = $this->Location->location_byCompanyAll(element('compID', $this->session->userdata('logged_in')));
		$data['locID']	  = "";		
		
		//Form setup
		$this->load->model('company/formSetup_Model');
		$filter['companyID']=element('compID', $this->session->userdata('logged_in'));
		$filter['formID']=58;
		$data['formNo'] = $this->formSetup_Model->getFormNo($filter);
		
		//Fetching dictionary for number to word conversiont.
		//$data['dictionary'] = $this->lang->line("dictionary");
		
		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
		$this->layouts->view('item/count-adjust', array('latest' => 'sidebar/latest'),$data);
	}
	
	//Item count listing
	public function listing($locID = ''){
		//Retrive from predata
		$data = $this->Item_count_adjust->getData($locID);
		
		//Gether location list
		$this->load->model('Location');
		$data['location'] = $this->Location->location_byCompanyAll(element('compID', $this->session->userdata('logged_in')));
		$locID?$data['locID'] = $locID:$data['locID'] = "";		
		
		//Form setup
		$this->load->model('company/formSetup_Model');
		$filter['companyID']=element('compID', $this->session->userdata('logged_in'));
		$filter['formID']=58;
		$data['formNo'] = $this->formSetup_Model->getFormNo($filter);
		
		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
		$this->layouts->view('item/count-adjust', array('latest' => 'sidebar/latest'),$data);
	}
	
	//Item adjustment Save
	public function save(){
		$flag = true;
		$data = json_decode($this->input->post("data"));
		$adjustmentID = '';
		$i = 1;
		foreach($data as $row){
			if($adjustmentID == ''){
				//Form setup
				$this->load->model('company/formSetup_Model');
				$filter['companyID']=element('compID', $this->session->userdata('logged_in'));
				$filter['formID']=58;
				$formNo = $this->formSetup_Model->getFormNo($filter);	
				
				//Save item count adjustment transaction.
				$data = array(
					'companyID' 		=> element('compID', $this->session->userdata('logged_in')),
					'locationID'		=> $row[2],
					'formNo'			=> $formNo,
					'adjustmentDate'	=> date('Y-m-d G:i:s',time()),
					'createdBy'			=> element('role',$this->session->userdata('logged_in'))
				);
				$adjustmentID = $this->Item_count_adjust->save($data);
			}
			
			//Gather item info
			$item = $this->Item_count_adjust->getItem($row[0],$row[2]);
			
			$dataDetail = array(
				'adjustmentID'		=> $adjustmentID,
				'itemID'			=> $row[0],
				'lineNo'			=> $i++,
				'unitOfMeasureID'	=> $item[0]->umID,
				'qtyOnHand'			=> $item[0]->onHandQty,
				'counted'			=> $row[1],
				'onDatePrice'		=> $item[0]->supplierPrice,
				'adjustmentDate'	=> date('Y-m-d G:i:s',time()),
			
			);
			$adjstDtl = $this->Item_count_adjust->saveDetail($dataDetail);		
		}
		if($flag){
			$this->session->set_flashdata('msg', 'Successfully Saved the transaction');
			echo 'Success';	
		}else{
			$this->session->set_flashdata('danger-msg', 'Unsuccessfull');
			echo 'unsuccessfull';	
		}
		exit();
	}
	
	//Listing for adjustment confirm
	public function confirm(){
		//Retrive transaction info from database
		$data['datatbls'] = $this->Item_count_adjust->getTransaction();
		
		
		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
		$this->layouts->view('item/count-adjust-confirm', array('latest' => 'sidebar/latest'),$data);
	}
	
	//Confirm adjust
	public function confirmAdjust(){
		$idList = explode(',',$this->input->post('adjstID'));
		foreach($idList as $v){
			$itemList = $this->Item_count_adjust->getItemsAsAdjust($v);
			$this->adjust($itemList);
			$this->Item_count_adjust->cngUpdateAble($v);
		}
		
		exit();
	}
	
	//Item adjust
	public function adjust($data){
		$flag = true;
		/*$data = json_decode($this->input->post("data"));*/
		foreach($data as $row){
			
			//Update balance Item in comp_receive_item_detail table
			$updtBlnc = $this->Item_count_adjust->updateBlnc($row->itemID,$row->counted,$row->qtyOnHand);
			
			//Update Item table quantity by the newly counted amount
			$newData = array(
				'itemID'	=> $row->itemID,
				'qtyOnHand'	=> $row->qtyOnHand,
				'counted'	=> $row->counted, 
				'locationID'=> $row->locationID,
				'companyID'	=> $row->companyID
			);
			$isUpdate = $this->Item_count_adjust->updateQty($newData);
			
			//if(!$isUpdate && $flag)	$flag = false;
		}
		
		if($flag){
			$this->session->set_flashdata('msg', 'Successfully Confirm the item adjustment transaction');
			echo 'Success';	
			return true;
		}else{
			$this->session->set_flashdata('danger-msg', 'Unsuccessfull');
			echo 'unsuccessfull';	
			return false;
		}
	}
	
	//Edit adjustment transaction
	public function edit($id){
		$data['datatbls'] = $this->Item_count_adjust->getItemEdit($id);
		
		//Gether location list
		$this->load->model('Location');
		$data['location'] = $this->Location->location_byCompanyAll(element('compID', $this->session->userdata('logged_in')));
		$data['locID'] = $data['datatbls'][0]->locationID;	
		
		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
		$this->layouts->view('item/count-adjust-edit', array('latest' => 'sidebar/latest'),$data);
	}
	
	//Update edit item adjustment
	public function editUpdate(){
		$data = array(
			'ID'		=> $this->input->post('tracID'),
			'counted'	=> $this->input->post('counted')
		);
		
		$updtItm = $this->Item_count_adjust->updateAdjustInfo($data);
		if($updtItm){
			echo "success";
		}else{
			echo "failed";
		}
	}
	
	/*********************************************************
	*														 *
	*						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->Item_count_adjust->rptList(date('Y-m-d', strtotime($srtDate)),date('Y-m-d', strtotime($endDate)));
		if($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',
				'Location' => 'Location',
				'adjustmentDate' => 'adjustmentDate',
				'updateable'	=> "updateable"
			);
		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
		$this->layouts->view('item/countadjustrpt', 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->lang->load("itemcountadjust",$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->Item_count_adjust->rptList(date('Y-m-d', strtotime($srtDate)),date('Y-m-d', strtotime($endDate)));
			foreach($data['datatbls'] as &$v){ $v->updateable == 0?$v->updateable = "Yes":$v->updateable = "No"; }
			//Configuration for table header
			$data['tbHdr'] = array(
				'formNo' => 'formNo',
				'Location' => 'Location',
				'adjustmentDate' => 'adjustmentDate',
			);
             
             $headerData['rightContentHeader'] = "Name supplier/ ot";
             $headerData['rptTitle'] = $this->lang->line("itemCountAdjustRpt");  
             $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("Location"), $this->lang->line("adjustmentDate"),$this->lang->line("updateable")); 
			$bodyData['selectFields'] = array("formNo", "Location", "adjustmentDate","updateable");
			$bodyData ['tdAmount'] = array("amountApplied");
			//$bodyData['tableFooter'] = array ("footer : value");
            
			$bodyData['excelTitle'] = $this->lang->line("itemCountAdjustRpt");    
		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($itemCntID,$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("itemcountadjust",$this->session->userdata('language'));
			//Gather report data
			$data['datatbls'] = $this->Item_count_adjust->rptDetail($itemCntID);
			
			$data['transInfo'] = $this->Item_count_adjust->adjustDetail($itemCntID);
			
			//Configuration for table header
			$data['tbHdr'] = array(
					'itemName' => 'itemName',
					'qtyOnHand' => 'qtyOnHand',
					'actualCount' => 'actualCount',
					'onDatePrice' => 'onDatePrice',
				);
             
             
             
             //$headerData['rightContentHeader'] = "Name supplier/ ot";
             $headerData['rptTitle'] = $this->lang->line("ItemAdjustmentDetail");
             $headerData['rightContent'] = array(
												$this->lang->line("formNo").": ".$data['transInfo'][0]->formNo,
												$this->lang->line("adjustmentDate").": ".$data['transInfo'][0]->adjustmentDate
											);
			 $headerData['leftContent'] = array(
			 									$this->lang->line("location").": ".$data['transInfo'][0]->location,
												$this->lang->line("adjustedBy").":".$data['transInfo'][0]->userInfo
											);
             
          //   $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("actualCount"), $this->lang->line("onDatePrice")); 
			$bodyData['selectFields'] = array("itemName","description","qtyOnHand","actualCount","onDatePrice");
			$bodyData ['tdAmount'] = array("qtyOnHand","actualCount","onDatePrice");
			//$bodyData['tableFooter'] = array ("footer : value");
            
			$bodyData['excelTitle'] = $this->lang->line("ItemAdjustmentDetail");
			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);
			}		
	}
}