<?php

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

class Glsetting extends CI_Controller {

	/**
	 * Constructor
	 */
	public function __construct() {
		parent::__construct();
		if (!$this->session->userdata('companyID')) redirect(base_url().'company','refresh');
	    $this->load->model('general_model');
		$companyId = $this->session->userdata('companyID');
		$rs = $this->db->query('select ifnull(count(ID),0)as bilRekod from comp_chart_of_acct where companyID='.$companyId);
		if ($rs->num_rows() > 0) $rsCount = $rs->result();
		if ($rsCount[0]->bilRekod == 0)		
				$this->db->query('INSERT INTO `comp_chart_of_acct` ( companyID, `acctGroupID`, `acctCode`, `acctName`) select '.$companyId.', `acctGroupID`, `acctCode`, `acctName` from _ref_chart_of_acct where businessTypeID = 2');
/*		$this->load->model('Useraccess');
		$query = $this->Useraccess->useraccess_id_module2('2', 'transaction');
		if(! $query) {
			echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
		}
		$this->load->model('menu');
*/	}

	/**
	 * Check financial year closing date
	 * @author Sayem
	 */
	public function financialYearCloseChk() {
		$date = $this->input->post('date');
		
		if($date == '')
			exit('Failed');
		$this->load->model('Compfinancialyear');
		$status = $this->Compfinancialyear->closeingChk(date('Y-m-d', strtotime($date)));
		echo $status;
		exit();
	}

	/**
	 * Check financial year calendar
	 * @author Sayem
	 */
	public function financialCalendarCheck_yearperiod() {
		$this->load->model('Compfinancialyear');
		$query = $this->Compfinancialyear->financialYear_yearperiod($this->input->post('financialYear'), $this->input->post('period'));
		$startdate = date("d-m-Y", strtotime($query[0]->startDate));
		$enddate = date("d-m-Y", strtotime($query[0]->endDate));
		$ID = $query[0]->ID;
		
		if($query > 0) {
			print json_encode(array(
				"status" => "false", "message1" => $query, "startDate" => $startdate, "endDate" => $enddate, "ID" => $ID
			));
		}
		else {
			print json_encode(array(
				"status" => "success", "message2" => $query
			));
		}
	}

	public function calendar() {
		$this->load->model('UseraccessDetails');
		$query = $this->UseraccessDetails->UseraccessDetails_id_code('GLMCAL');
		if(! $query) {
			echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
		}
		if($this->input->post('submit')) {
			$this->load->model('Compfinancialyear');
			// var_dump($this->input->post('fcID'));
			if($this->input->post('fcID') == NULL) {
				$query = $this->Compfinancialyear->startEndDateCheck_startDateEndDate();
				if(! $query) {
					$financialCalendar = array(
						'ID' => $this->input->post('ID'), 'companyID' => element('compID', $this->session->userdata('logged_in')), 'financialYear' => $this->input->post('financialYear'), 'period' => $this->input->post('period'), 'startDate' => date('Y-m-d', strtotime($this->input->post('startDate'))), 'endDate' => date('Y-m-d', strtotime($this->input->post('endDate')))
					);
					// 'createdID' => element('userid', $this->session->userdata('logged_in')),
					
					$insert_calendar = $this->Compfinancialyear->financialCalendarInsert($financialCalendar);
					if($insert_calendar) {
						echo '<script>alert("Insert Data Success..");
						window.location.replace("financialCalendarList");
						</script>';
					}
					else {
						echo '<script>alert("Insert Data Failed.");
						history.go(-1);</script>';
					}
				}
				else {
					echo '<script>alert("You enter the wrong period of date.");
						history.go(-1);</script>';
				} // if !$query
			}
			else {
				$ID = $this->input->post('fcID');
				$financialCalendar = array(
					'financialYear' => $this->input->post('financialYear'), 'period' => $this->input->post('period'), 'startDate' => date('Y-m-d', strtotime($this->input->post('startDate'))), 'endDate' => date('Y-m-d', strtotime($this->input->post('endDate'))), 'status' => $this->input->post('status')
				);
				// 'createdID' => element('userid', $this->session->userdata('logged_in')),
				
				// $this->load->model(company/Company_info_model);
				$this->load->model('Compfinancialyear');
				$update_calendar = $this->Compfinancialyear->financialCalendar_edit($financialCalendar, $ID);
				if($update_calendar) {
					echo '<script>alert("Update Success..");
						window.location.replace("financialCalendarList");
						</script>';
				}
				else {
					echo '<script>alert("Update Failed.");
						history.go(-1);</script>';
				}
			}
		}
		else {
			$id = isset($_REQUEST['id']) ? $_REQUEST['id'] : "";
			$this->load->library('layouts');
			$this->lang->load("companyFinancialCalendar", $this->session->userdata('language'));
			$this->load->model('Compfinancialyear');
			if($id) {
				$dataum = $this->Compfinancialyear->financialCalendar_id($id);
				$data['fycmaster'] = $dataum[0];
			}
			else {
				$data['fycmaster'] = NULL;
			}
			$this->layouts->add_includes('js/validationengine/languages/jquery.validationEngine-' . $this->session->userdata('language') . '.js')
				->add_includes('js/validationengine/jquery.validationEngine.js');
			
			$this->layouts->view('gl/setups/companyFinancialCalendar', array(
				'latest' => 'sidebar/latest'
			), $data);
		}
	}

	public function dateSearch() {
		$this->load->model('Compfinancialyear');
		
		$period = $this->input->post('period');
		$financialYear = $this->input->post('financialYear');
		$startDate = $this->input->post('startDate');
		$endDate = $this->input->post('endDate');
		$startPeriod = $this->input->post('startPeriod');
		
		$addmonth = $period - 1;
		$startPeriod = 1;
		$startDate = date('Y-m-01', strtotime($startDate));
		$endDate = date('Y-m-t', strtotime($startDate . '+' . $addmonth . ' month'));
		print json_encode(array(
			"status" => "success", "startDate" => date('d-m-Y', strtotime($startDate)), "endDate" => date('d-m-Y', strtotime($endDate)), "startPeriod" => $startPeriod, "period" => $period
		));
	}

	public function checkYear() {
		$this->load->model('Compfinancialyear');
		
		$financialYear = $this->input->post('financialYear');
		$period = $this->input->post('period');
		
		$query = $this->Compfinancialyear->financialCalendarCheckYear($financialYear);
		// var_dump($query);
		// exit();
		
		if($query > 0) {
			$query1 = $this->Compfinancialyear->financialYear_checkperiod($financialYear);
			if($query1->period > 0) {
				$startPeriod = $query1->period + 1;
				$startDate = date('Y-m-01', strtotime($query1->startDate . ' +1 months'));
				$endDate = date('Y-m-t', strtotime($query1->startDate . ' +' . $period . ' months'));
			}
			print json_encode(array(
				"status" => "success", "message" => $query, "financialYear" => $financialYear, "startDate" => date('d-m-Y', strtotime($startDate)), "endDate" => date('d-m-Y', strtotime($endDate)), "startPeriod" => $startPeriod
                            /* "period"=>$period,
                              "startDate"=>$startDate,
                              "endDate"=>$endDate, */
            ));
		}
		else {
			$startPeriod = 1;
			$startDate = date('Y-m-01');
			$endDate = date('Y-m-t');
			print json_encode(array(
				"status" => "failed", "message2" => "Wrong Year", "startDate" => date('d-m-Y', strtotime($startDate)), "endDate" => date('d-m-Y', strtotime($endDate)), "startPeriod" => $startPeriod
			));
		}
	}

	public function checkYearPeriodStartEndDate() {
		$this->load->model('Compfinancialyear');
		
		$financialYear = $this->input->post('financialYear');
		$period = $this->input->post('period');
		$startDate = $this->input->post('startDate');
		$endDate = $this->input->post('endDate');
		$check = FALSE;
		
		$check = $this->Compfinancialyear->financialYear_yearperioddate($financialYear, $period, $startDate, $endDate, $check);
		// var_dump($query);
		
		if($check == true) {
			print json_encode(array(
				"status" => "success", "message" => $check, "startDate" => $startDate, "endDate" => $endDate, "period" => $period
			));
		}
		else {
			print json_encode(array(
				"status" => "fail", "message2" => "false"
			));
		}
	}

	public function createCalendar() {
/*		$this->load->model('UseraccessDetails');
		$query = $this->UseraccessDetails->UseraccessDetails_id_code('GLMCAL');
		if(! $query) {
			echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
		}
*/		if($this->input->post('submit')) {
			$this->load->model('Compfinancialyear');
			
			$startDate = $this->input->post('startDate');
			$endDate = $this->input->post('endDate');
			// echo $startDate;
			// echo $endDate;
			
			$check = $this->Compfinancialyear->financialCalendarCheckDate($startDate, $endDate);
			
			$period = $this->input->post('period');
			$startPeriod = $this->input->post('startPeriod');
			$financialYear = $this->input->post('financialYear');
			
			$check2 = count($this->Compfinancialyear->financialCalendarperiodAndStartPeriod($financialYear));
			
			$totalperiod = 0;
			
			if($check2 == 1) {
				$totalperiod = ($check2 + $period) - 1;
			}
			else {
				$totalperiod = $check2 + $period;
			}
			
			$totalStartPeriod = ($startPeriod + $period) - 1;
			
			//$checkOpeningBalance = $this->Compfinancialyear->financialCalendarCheckOpeningBalance($financialYear);
			if($this->Compfinancialyear->checkOpeningBalance($financialYear)) {
				
				if(! $check && ($totalperiod < 19) && ($totalStartPeriod < 19)) {
					$i = $startPeriod;
					$m = 0;
					$insert_calendar = 0;
					while($i < $startPeriod + $period) {
						$financialCalendar = array(
							'ID' => $this->input->post('ID'), 'companyID' => element('compID', $this->session->userdata('logged_in')), 'financialYear' => $this->input->post('financialYear'), 'period' => $startPeriod + $m, 'startDate' => date('Y-m-01', strtotime($this->input->post('startDate') . '+' . $m . ' month')), 'endDate' => date('Y-m-t', strtotime($this->input->post('startDate') . '+' . $m . ' month')), 'createdBy' => element('role', $this->session->userdata('logged_in'))
						);
						// check ada dlm db atau tidak
						// select * from where companyid=? and financial_year =? and period=?
						$query = $this->db->query('select * from comp_financial_year where companyid=' . element('compID', $this->session->userdata('logged_in')) . ' and financialYear =' . $this->input->post('financialYear') . ' and period=' . $financialCalendar['period']);
						if($query->num_rows() > 0)
							$this->db->query('update comp_financial_year set is_delete = 0 where companyid=' . element('compID', $this->session->userdata('logged_in')) . ' and financialYear = ' . $this->input->post('financialYear') . ' and period=' . $financialCalendar['period']);
							// jika ada update is_delete to 0
							// else insert dlm db
						else
							$insert_calendar = $this->Compfinancialyear->financialCalendarInsert($financialCalendar);
						$i ++;
						$m ++;
					} // end while
					echo '<script>alert("Insert Data Success..");
								window.location.replace("financialCalendarList");
								</script>';
				}
				else {
					echo '<script>alert("You enter the wrong period of date.");
								history.go(-1);</script>';
				} // if $check
			
			}
			else {
				echo '<script>alert("Invalid year. This system does not allow user to insert financial year before year of opening balance");
						history.go(-1);</script>';
			}
		
		} // if submit
		else {
			// $id = isset($_REQUEST['id'])?$_REQUEST['id']:"";
			$this->load->library('layouts');
			$this->lang->load("companyFinancialCalendar", $this->session->userdata('language'));
			$this->load->model('Compfinancialyear');
			$data['datatbls'] = $this->Compfinancialyear->financialCalendarCheckYear(date("Y"));
			if($data['datatbls']) {
				$data['fycmaster'] = $this->Compfinancialyear->financialYear_checkperiod(date("Y"));
			}
			else {
				$data['fycmaster'] = NULL;
			}
			$this->layouts->add_includes('js/validationengine/languages/jquery.validationEngine-' . $this->session->userdata('language') . '.js')
				->add_includes('js/accounting.js')
				->add_includes('js/validationengine/jquery.validationEngine.js')
				->add_includes('js/datatables/jquery.dataTables.min.js');
			
			$this->layouts->view('gl/setups/createCompanyFinancialCalendar', array(
				'latest' => 'sidebar/latest'
			), $data);
		}
	}

	/* Create financial calendar one by one */
	
	public function addCalendar() {
		$this->load->model('UseraccessDetails');
		$query = $this->UseraccessDetails->UseraccessDetails_id_code('GLMCAL');
		if(! $query) {
			echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
		}
		if($this->input->post('submit')) {
			$this->load->model('Compfinancialyear');
			
			$startDate = $this->input->post('startDate');
			$endDate = $this->input->post('endDate');
			$check = FALSE;
			$check = $this->Compfinancialyear->financialCalendarCheckDate($startDate, $endDate, $check);
			
			$period = $this->input->post('period');
			// $query=$this->Compfinancialyear->startEndDateCheck_startDateEndDate();
			
			if($check == true) {
				$financialCalendar = array(
					'ID' => $this->input->post('ID'), 'companyID' => element('compID', $this->session->userdata('logged_in')), 'financialYear' => $this->input->post('financialYear'), 'period' => $i + 1, 'startDate' => date('Y-m-01', strtotime($this->input->post('startDate') . '+' . $i . ' months')), 'endDate' => date('Y-m-t', strtotime($this->input->post('startDate') . '+' . $i . ' months'))
				);
				// 'createdID' => element('userid', $this->session->userdata('logged_in')),
				
				$insert_calendar = $this->Compfinancialyear->financialCalendarInsert($financialCalendar);
				if($insert_calendar) {
					echo '<script>alert("Insert Data Success..");
						window.location.replace("financialCalendarList");
						</script>';
				}
				else {
					echo '<script>alert("Insert Data Failed.");
						history.go(-1);</script>';
				}
			}
			else {
				echo '<script>alert("You enter the wrong period of date.");
						history.go(-1);</script>';
			} // if $check
		} // if submit
		else {
			$id = isset($_REQUEST['id']) ? $_REQUEST['id'] : "";
			$this->load->library('layouts');
			$this->lang->load("companyFinancialCalendar", $this->session->userdata('language'));
			$this->load->model('Compfinancialyear');
			$data['datatbls'] = $this->Compfinancialyear->financialCalendar_all();
			if($id) {
				$dataum = $this->Compfinancialyear->financialCalendar_id($id);
				$data['fycmaster'] = $dataum[0];
			}
			else {
				$data['fycmaster'] = NULL;
			}
			$this->layouts->add_includes('js/validationengine/languages/jquery.validationEngine-' . $this->session->userdata('language') . '.js')
				->add_includes('js/validationengine/jquery.validationEngine.js');
			
			$this->layouts->view('gl/setups/addCompanyFinancialCalendar', array(
				'latest' => 'sidebar/latest'
			), $data);
		}
	}

	public function financialCalendarDelete() {
		$this->load->model('Compfinancialyear');
		// $deleteuser = array('is_delete' => '1');
		$ID = isset($_REQUEST['ID']) ? $_REQUEST['ID'] : "";
		
		$journal_delete = $this->Compfinancialyear->financialCalendar_checkyearperiod($ID);
		
		$companyID = $journal_delete[0]->companyID;
		$year = $journal_delete[0]->financialYear;
		$period = $journal_delete[0]->period;
		
		// var_dump($companyID);
		
		$checkjournal_delete = $this->Compfinancialyear->companyJournal_checkyearperiod($companyID, $year, $period);
		
		if(! $checkjournal_delete) {
			// $delete_user = $this->Compfinancialyear->financialCalendar_delete($deleteuser, $ID);
			$delete_user = $this->Compfinancialyear->financialCalendar_delete($ID);
			if($delete_user) {
				echo '<script>alert("Delete Success..");
					window.location.replace("createCalendar");
					</script>';
			}
			else {
				return FALSE;
			}
		}
		else {
			echo '<script>alert("Operation denied. Related data exist...");
				window.location.replace("createCalendar");
				</script>';
		}
	}

	public function financialCalendarList() {
		$this->load->model('UseraccessDetails');
		$query = $this->UseraccessDetails->UseraccessDetails_id_code('GLMCALL');
		if(! $query) {
			echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
		}
		$this->load->library('layouts');
		$this->lang->load("companyFinancialCalendar", $this->session->userdata('language'));
		$this->load->model('Compfinancialyear');
		$data['datatbls'] = $this->Compfinancialyear->financialCalendar_all();
		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
		$this->layouts->view('gl/setups/companyFinancialCalendarlist', array(
			'latest' => 'sidebar/latest'
		), $data);
	}
	
	// Chart of accounts
	public function chartOfAcct() {
		$this->load->model('UseraccessDetails');
		$query = $this->UseraccessDetails->UseraccessDetails_id_code('GLSTCOA');
		if(! $query) {
			echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
		}
		
		// $data['fad'] = $this->uri->segment(3);
		
		if($this->input->post('submit')) {
			$this->load->model('CompanyChartAcct');
			$post = $this->input->post('acctGroupID');
			if(!empty($post)){
				if($this->input->post('acctCodeID') == NULL) {
					$accountCode = array(
						'ID' => $this->input->post('ID'), 
						'companyID' => element('compID', $this->session->userdata('logged_in')), 
						'acctGroupID' => $this->input->post('acctGroupID'), 
						'acctCode' => preg_replace('/-|:/', null, $this->input->post('acctCode')), 
						'acctName' => $this->input->post('acctName'), 
						'createdBy' => element('userid', $this->session->userdata('logged_in')), 
						'createdTS' => $this->input->post('order_time')
					);
					
					$insert_acctCode = $this->CompanyChartAcct->chartAcctInsert($accountCode);
					if($insert_acctCode) {
						echo '<script>alert("Insert Data Success..");
						window.location = "'.base_url().'glsetting/chartOfAcctList";
						</script>';
					}
					else {
						echo '<script>alert("Insert Data Failed.");
						history.go(-1);</script>';
					}
				}
				else {
					$ID = $this->input->post('acctCodeID');
					$accountCode = array(
						'companyID' => element('compID', $this->session->userdata('logged_in')), 
						'acctGroupID' => $this->input->post('acctGroupID'), 
						'acctCode' => preg_replace('/-|:/', null, $this->input->post('acctCode')), 
						'acctName' => $this->input->post('acctName'), 
						'updatedBy' => element('userid', $this->session->userdata('logged_in'))
					);
					// $this->load->model(company/Company_info_model);
					$this->load->model('CompanyChartAcct');
					$update_acctCode = $this->CompanyChartAcct->chartAcct_edit($accountCode, $ID);
					if($update_acctCode) {
						echo '<script>alert("Update Success..");
						window.location = "'.base_url().'glsetting/chartOfAcctList";
						</script>';
					}
					else {
						echo '<script>alert("Update Failed.");
						history.go(-1);</script>';
					}
				}
			}
			else{
				echo '<script>alert("Please select account group.");
						history.go(-1);</script>';
			}
			
		}
		else {
			$id = isset($_REQUEST['id']) ? $_REQUEST['id'] : ($this->uri->segment(3) ? $this->uri->segment(3) : "");
			$this->load->library('layouts');
			$this->lang->load("chartofaccount", $this->session->userdata('language'));
			$this->lang->load("pnl", $this->session->userdata('language'));
			$this->lang->load("bs", $this->session->userdata('language'));
			$this->load->model('CompAcctGroup_model');
			$data['accGroup'] = $this->CompAcctGroup_model->companyacctgroup_all2();
			$this->load->model('companyChartAcct');
			$data['chargeAccount'] = $this->companyChartAcct->chartAcct_all();
			
			$data['acctID'] = $this->uri->segment(3);
			$data['checkUpdateable'] = $this->companyChartAcct->chartOfAcctUpdateable($data['acctID']);
			
			// var_dump($data['accGroup']);
			$this->load->model('CompanyChartAcct');
			if($id) {
				$dataum = $this->CompanyChartAcct->chartAcct_id($id);
				// var_dump($dataum[0]);
				$data['acmaster'] = $dataum[0];
			}
			else {
				$data['acmaster'] = NULL;
			}
//			 echo $this->db->last_query();
//			 var_dump($data['acmaster']);
			$this->layouts->add_includes('js/validationengine/languages/jquery.validationEngine-' . $this->session->userdata('language') . '.js')
				->add_includes('js/validationengine/jquery.validationEngine.js');
			$this->layouts->view('gl/setups/companyChartAcct', array(
				'latest' => 'sidebar/latest'
			), $data);
		}
	}

	public function chartOfAcctCustomer() {
		$this->load->model('UseraccessDetails');
		$query = $this->UseraccessDetails->UseraccessDetails_id_code('GLSTCOA');
		if(! $query) {
			echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
		}
		
		if($this->input->post('submit')) {
			$this->load->model('CompanyChartAcct');
			if($this->input->post('acctCodeID') == NULL) {
				$accountCode = array(
					'ID' => $this->input->post('ID'), 'companyID' => element('compID', $this->session->userdata('logged_in')), 'acctGroupID' => $this->input->post('acctGroupID'), 'acctCode' => preg_replace('/-|:/', null, $this->input->post('acctCode')), 'acctName' => $this->input->post('acctName'), 'createdBy' => element('userid', $this->session->userdata('logged_in')), 'createdTS' => $this->input->post('order_time')
				);
				
				$insert_acctCode = $this->CompanyChartAcct->chartAcctInsert($accountCode);
				if($insert_acctCode) {
					echo '<script>alert("Insert Data Success..");
					window.location.replace("chartOfAcctList");
					</script>';
				}
				else {
					echo '<script>alert("Insert Data Failed.");
					history.go(-1);</script>';
				}
			}
			else {
				$ID = $this->input->post('acctCodeID');
				$accountCode = array(
					'companyID' => element('compID', $this->session->userdata('logged_in')), 'acctGroupID' => $this->input->post('acctGroupID'), 'acctCode' => preg_replace('/-|:/', null, $this->input->post('acctCode')), 'acctName' => $this->input->post('acctName'), 'updatedBy' => element('userid', $this->session->userdata('logged_in'))
				);
				// $this->load->model(company/Company_info_model);
				$this->load->model('CompanyChartAcct');
				$update_acctCode = $this->CompanyChartAcct->chartAcct_edit($accountCode, $ID);
				if($update_acctCode) {
					echo '<script>alert("Update Success..");
					window.location.replace("chartOfAcctList");
					</script>';
				}
				else {
					echo '<script>alert("Update Failed.");
					history.go(-1);</script>';
				}
			}
		}
		else {
			$id = isset($_REQUEST['id']) ? $_REQUEST['id'] : ($this->uri->segment(3) ? $this->uri->segment(3) : "");
			$this->load->library('layouts');
			$this->lang->load("chartofaccount", $this->session->userdata('language'));
			$this->lang->load("pnl", $this->session->userdata('language'));
			$this->lang->load("bs", $this->session->userdata('language'));
			$this->load->model('CompAcctGroup_model');
			$data['accGroup'] = $this->CompAcctGroup_model->companyacctgroup_all2();
			$this->load->model('companyChartAcct');
			$data['chargeAccount'] = $this->companyChartAcct->chartAcct_all();
			
			$data['acctID'] = $this->uri->segment(3);
			$data['checkUpdateable'] = $this->companyChartAcct->chartOfAcctUpdateable($data['acctID']);
			
			// var_dump($data['accGroup']);
			$this->load->model('CompanyChartAcct');
			if($id) {
				$dataum = $this->CompanyChartAcct->chartAcct_id($id);
				// var_dump($dataum[0]);
				$data['acmaster'] = $dataum[0];
			}
			else {
				$data['acmaster'] = NULL;
			}
			// echo $this->db->last_query();
			// var_dump($data);
			$this->layouts->add_includes('js/validationengine/languages/jquery.validationEngine-' . $this->session->userdata('language') . '.js')
				->add_includes('js/validationengine/jquery.validationEngine.js');
			$this->layouts->view('gl/setups/companyChartAcctCustomer', array(
				'latest' => 'sidebar/latest'
			), $data);
		}
	}

	public function chartOfAcctSupplier() {
		$this->load->model('UseraccessDetails');
		$query = $this->UseraccessDetails->UseraccessDetails_id_code('GLSTCOA');
		if(! $query) {
			echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
		}
		
		if($this->input->post('submit')) {
			$this->load->model('CompanyChartAcct');
			if($this->input->post('acctCodeID') == NULL) {
				$accountCode = array(
					'ID' => $this->input->post('ID'), 'companyID' => element('compID', $this->session->userdata('logged_in')), 'acctGroupID' => $this->input->post('acctGroupID'), 'acctCode' => preg_replace('/-|:/', null, $this->input->post('acctCode')), 'acctName' => $this->input->post('acctName'), 'createdBy' => element('userid', $this->session->userdata('logged_in')), 'createdTS' => $this->input->post('order_time')
				);
				
				$insert_acctCode = $this->CompanyChartAcct->chartAcctInsert($accountCode);
				if($insert_acctCode) {
					echo '<script>alert("Insert Data Success..");
					window.location.replace("chartOfAcctList");
					</script>';
				}
				else {
					echo '<script>alert("Insert Data Failed.");
					history.go(-1);</script>';
				}
			}
			else {
				$ID = $this->input->post('acctCodeID');
				$accountCode = array(
					'companyID' => element('compID', $this->session->userdata('logged_in')), 'acctGroupID' => $this->input->post('acctGroupID'), 'acctCode' => preg_replace('/-|:/', null, $this->input->post('acctCode')), 'acctName' => $this->input->post('acctName'), 'updatedBy' => element('userid', $this->session->userdata('logged_in'))
				);
				// $this->load->model(company/Company_info_model);
				$this->load->model('CompanyChartAcct');
				$update_acctCode = $this->CompanyChartAcct->chartAcct_edit($accountCode, $ID);
				if($update_acctCode) {
					echo '<script>alert("Update Success..");
					window.location.replace("chartOfAcctList");
					</script>';
				}
				else {
					echo '<script>alert("Update Failed.");
					history.go(-1);</script>';
				}
			}
		}
		else {
			$id = isset($_REQUEST['id']) ? $_REQUEST['id'] : ($this->uri->segment(3) ? $this->uri->segment(3) : "");
			$this->load->library('layouts');
			$this->lang->load("chartofaccount", $this->session->userdata('language'));
			$this->lang->load("pnl", $this->session->userdata('language'));
			$this->lang->load("bs", $this->session->userdata('language'));
			$this->load->model('CompAcctGroup_model');
			$data['accGroup'] = $this->CompAcctGroup_model->companyacctgroup_all2();
			$this->load->model('companyChartAcct');
			$data['chargeAccount'] = $this->companyChartAcct->chartAcct_all();
			
			$data['acctID'] = $this->uri->segment(3);
			$data['checkUpdateable'] = $this->companyChartAcct->chartOfAcctUpdateable($data['acctID']);
			
			// var_dump($data['accGroup']);
			$this->load->model('CompanyChartAcct');
			if($id) {
				$dataum = $this->CompanyChartAcct->chartAcct_id($id);
				// var_dump($dataum[0]);
				$data['acmaster'] = $dataum[0];
			}
			else {
				$data['acmaster'] = NULL;
			}
			// echo $this->db->last_query();
			// var_dump($data);
			$this->layouts->add_includes('js/validationengine/languages/jquery.validationEngine-' . $this->session->userdata('language') . '.js')
				->add_includes('js/validationengine/jquery.validationEngine.js');
			$this->layouts->view('gl/setups/companyChartAcctSupplier', array(
				'latest' => 'sidebar/latest'
			), $data);
		}
	}

	public function chartDelete() {
		$ID = $this->uri->segment(3);
		$this->load->model('companyChartAcct');
		$query = $this->companyChartAcct->chartToDelete($ID);
		if(! $query) {
			echo '<script>alert("Cannot Delete")</script>';
		}
		else {
			echo '<script>
						alert("Delete Success..");
						window.location.replace("' . base_url() . 'glsetting/chartOfAcctList");
				  </script>';
		}
	}

	public function checkIfAcctExist() {
		$this->load->model('companyChartAcct');
		echo $this->companyChartAcct->getChartOfAcctByCode(str_replace("-", "", $this->input->post("acctCode"), $count), $this->input->post("target"));
	}

	public function chartOfAcctList() {
		$this->load->model('UseraccessDetails');
		$query = $this->UseraccessDetails->UseraccessDetails_id_code('GLSTCOA');
		if(! $query) {
			echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
		}
		$this->load->library('layouts');
		$this->load->helper('form');
		$this->load->helper('menu');
		$this->load->model('Chartofaccount');
		$this->load->model('company/company_info_model');
		$companyID = element('compID', $this->session->userdata('logged_in'));
		$companyName = element('compName', $this->session->userdata('logged_in'));
		// $companyName = $this->company_info_model->companymaster_id($companyID);
		// $industry = $this->company_info_model->industry_id($companyID);
		// var_dump($companyName[0]);
		$data['companyName'] = $companyName;
		// Check wheather show dropdown or not
		$data['companyID'] = $companyID;
		$data['isShowDropdown'] = $this->Chartofaccount->isShowDropdown($companyID);
		// $data['isShowDropdown'] = $this->company_info_model->company_groupChartOfAccount_byCompanyID($companyID);
		$data['balance'] = $this->Chartofaccount->getInfo($companyID, 0);
		$data['profitNloss'] = $this->Chartofaccount->getInfo($companyID, 1);
		// echo $this->db->last_query();
		if($data['isShowDropdown']) {
			// Gether data for industry in business selector
			$data['industryInfo'] = $this->Chartofaccount->getdata($companyID);
		}
		$this->lang->load("comp_chartofaccount", $this->session->userdata('language'));
		$this->lang->load("acctGroup", $this->session->userdata('language'));
		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
		$this->layouts->view('masterfile/chartofaccount', array(
			'latest' => 'sidebar/latest'
		), $data);
	}

	public function balancesheetList_print($mode = false) {
		$this->load->model('Chartofaccount');
		$this->load->model('company/company_info_model');
		
		$this->lang->load("comp_chartofaccount", $this->session->userdata('language'));
		$this->lang->load("acctGroup", $this->session->userdata('language'));
		$companyID = element('compID', $this->session->userdata('logged_in'));
		$companyName = element('compName', $this->session->userdata('logged_in'));
		
		$data['companyName'] = $companyName;
		$data['companyID'] = $companyID;
		
		$data['balance'] = $this->Chartofaccount->getInfo($companyID, 0);
		// $supplierInfo = $this->Supplier_model->suppliermaster_id($data['transInfo'][0]->supplierID);
		// echo $this->db->last_query();
		// var_dump($data['datatbls2'][0]);
		// $headerData['rightContentHeader'] = "Name supplier/ ot";
		$headerData['rptTitle'] = $this->lang->line("balanceSheet");
		/*
		 * $headerData['leftContent'] = array(
		 * "<b>".$data['transInfo'][0]->customerName."</b>",
		 * $data['transInfo'][0]->customerCompanyNo,
		 * $data['transInfo'][0]->line1,
		 * $data['transInfo'][0]->line2,
		 * $data['transInfo'][0]->line3,
		 * $data['transInfo'][0]->customerPostCode.' '.$data['transInfo'][0]->city
		 * );
		 */
		/*
		 * $headerData['rightContent'] = array(
		 * //"<b>".$this->lang->line("formNo").":".$data['transInfo'][0]->creditNoteNo."</b>",
		 * $this->lang->line("from")." ".date('d-m-Y', strtotime($dateFrom))." ".$this->lang->line("to")." ".date('d-m-Y', strtotime($dateTo)),
		 * //$this->lang->line("currency").":".$data['transInfo'][0]->fldcurr_code,
		 * //$this->lang->line("terms").":".$data['transInfo'][0]->termName
		 * );
		 */
		
		// $headerData['company'] = $this->company_info_model->companyById(element('compID', $this->session->userdata('logged_in')));
		$bodyData['rptDataDetail'] = $data['balance'];
		$bodyData['tableHeader'] = array(
			$this->lang->line("accountno"), $this->lang->line("accountName"), $this->lang->line("accountGroup"), $this->lang->line("accountType")
		);
		$bodyData['selectFields'] = array(
			"acctCode", "acctName", "acctGroupName", "acctTypeName"
		);
		// $bodyData ['tdAmount'] = array("totalPayable","totalTaxAmount");
		// $bodyData['tableFooter'] = array ("footer : value");
		$bodyData['tableFooter'] = array(
			""
		);
		$bodyData['excelTitle'] = "Location Transfer Detail";
		
		if(! $mode) {
			// print
			$this->load->view('layouts/report/header', $headerData);
			$this->load->view('layouts/report/body', $bodyData);
			// var_dump($bodyData2['selectFields']);
			$this->load->view('layouts/report/footer', '');
		}
		else {
			// download excell
			$this->load->helper('excel');
			excel($headerData, array(
				$bodyData
			), $footerData);
		}
	}

	// public function profitnlossList_print($mode = false) {
	// 	$this->load->model('Chartofaccount');
	// 	$this->load->model('company/company_info_model');
		
	// 	$this->lang->load("comp_chartofaccount", $this->session->userdata('language'));
	// 	$this->lang->load("acctGroup", $this->session->userdata('language'));
	// 	$companyID = element('compID', $this->session->userdata('logged_in'));
	// 	$companyName = element('compName', $this->session->userdata('logged_in'));
		
	// 	$data['companyName'] = $companyName;
	// 	$data['companyID'] = $companyID;
		
	// 	$data['profitNloss'] = $this->Chartofaccount->getInfo($companyID, 1);
	// 	// $supplierInfo = $this->Supplier_model->suppliermaster_id($data['transInfo'][0]->supplierID);
	// 	// echo $this->db->last_query();
	// 	// var_dump($data['datatbls2'][0]);
	// 	// $headerData['rightContentHeader'] = "Name supplier/ ot";
	// 	$headerData['rptTitle'] = $this->lang->line("profitnloss");
	// 	/*
	// 	 * $headerData['leftContent'] = array(
	// 	 * "<b>".$data['transInfo'][0]->customerName."</b>",
	// 	 * $data['transInfo'][0]->customerCompanyNo,
	// 	 * $data['transInfo'][0]->line1,
	// 	 * $data['transInfo'][0]->line2,
	// 	 * $data['transInfo'][0]->line3,
	// 	 * $data['transInfo'][0]->customerPostCode.' '.$data['transInfo'][0]->city
	// 	 * );
	// 	 */
		
	// 	 * $headerData['rightContent'] = array(
	// 	 * //"<b>".$this->lang->line("formNo").":".$data['transInfo'][0]->creditNoteNo."</b>",
	// 	 * $this->lang->line("from")." ".date('d-m-Y', strtotime($dateFrom))." ".$this->lang->line("to")." ".date('d-m-Y', strtotime($dateTo)),
	// 	 * //$this->lang->line("currency").":".$data['transInfo'][0]->fldcurr_code,
	// 	 * //$this->lang->line("terms").":".$data['transInfo'][0]->termName
	// 	 * );
		 
		
	// 	// $headerData['company'] = $this->company_info_model->companyById(element('compID', $this->session->userdata('logged_in')));
	// 	$bodyData['rptDataDetail'] = $data['profitNloss'];
	// 	$bodyData['tableHeader'] = array(
	// 		$this->lang->line("accountno"), $this->lang->line("accountName"), $this->lang->line("accountGroup"), $this->lang->line("accountType")
	// 	);
	// 	$bodyData['selectFields'] = array(
	// 		"acctCode", "acctName", "acctGroupName", "acctTypeName"
	// 	);
	// 	// $bodyData ['tdAmount'] = array("totalPayable","totalTaxAmount");
	// 	// $bodyData['tableFooter'] = array ("footer : value");
	// 	$bodyData['tableFooter'] = array(
	// 		""
	// 	);
	// 	$bodyData['excelTitle'] = "Location Transfer Detail";
		
	// 	if(! $mode) {
	// 		// print
	// 		$this->load->view('layouts/report/header', $headerData);
	// 		$this->load->view('layouts/report/body', $bodyData);
	// 		// var_dump($bodyData2['selectFields']);
	// 		$this->load->view('layouts/report/footer', '');
	// 	}
	// 	else {
	// 		// download excell
	// 		$this->load->helper('excel');
	// 		excel($headerData, array(
	// 			$bodyData
	// 		), $footerData);
	// 	}
	// }

	public function acctCodeDelete() {
		$this->load->model('CompanyChartAcct');
		$deleteuser = array(
			'is_delete' => '1'
		);
		$ID = isset($_REQUEST['ID']) ? $_REQUEST['ID'] : "";
		
		$delete_user = $this->CompanyChartAcct->chartAcctDelete($deleteuser, $ID);
		if($delete_user) {
			echo '<script>alert("Delete Success..");
						window.location.replace("chartOfAcctList");
						</script>';
		}
		else {
			return FALSE;
		}
	}
	
	// Budget Entry
	
	public function budgetEntry() {
		$this->load->model('UseraccessDetails');
		$queryBudgetEntry = $this->UseraccessDetails->UseraccessDetails_id_code('GLSTBDGT');
		if(! $queryBudgetEntry) {
			echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
		}
		if($this->input->post('submit')) {

		}
		else {
			$add_year = $this->uri->segment(3);
			$this->load->model('CompanyChartAcct');
			$this->load->model('Budget');
			$this->load->library('layouts');
			$this->lang->load("budget", $this->session->userdata('language'));
			$this->layouts->add_includes('js/validationengine/languages/jquery.validationEngine-' . $this->session->userdata('language') . '.js')
				->add_includes('js/validationengine/jquery.validationEngine.js')
				->add_includes('js/datatables/jquery.dataTables.min.js');
			if(! $add_year) {
				$add_year = date("Y");
			}
			$data['selyear'] = $add_year;
			$query = $this->Budget->budget_all_year($add_year);
			if($query) {
				$data['budgetdetails'] = $query;
				$this->layouts->view('gl/setups/budgetEdit', array(
					'latest' => 'sidebar/latest'
				), $data);
			}
			else {
				$data['budgetdetails'] = '';
				$data['chartofaccount'] = $this->CompanyChartAcct->chartAcct_all_PNL();
				$this->layouts->view('gl/setups/budget', array(
					'latest' => 'sidebar/latest'
				), $data);
			}
		}
	
	}

	public function budgetEdit() {
		$this->load->library('layouts');
		$this->lang->load("budget", $this->session->userdata('language'));
		$this->load->model('Budget');
		$add_year = $this->uri->segment(3);
		if(! $add_year) {
			$add_year = date("Y");
		}
		$data['selyear'] = $add_year;
		$data['budgetdetails'] = $this->Budget->budget_all_year($add_year);
		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
		$this->layouts->view('gl/setups/budgetEdit', array(
			'latest' => 'sidebar/latest'
		), $data);
	}

	public function budget_insert() {
		$this->lang->load("budget", $this->session->userdata('language'));
		$this->load->model('Budget');
		$query = $this->Budget->budget_insert();
		print json_encode(array(
			"status" => "success", "message" => $this->lang->line('message7')
		));
	}

	public function budget_save() {
		$this->load->model('Budget');
		$query = $this->Budget->budget_update();
		if($query) {
			print json_encode(array(
				"status" => "success", "message" => $this->lang->line('message7')
			));
		}
		else {
			print json_encode(array(
				"status" => "failed", "message" => $this->lang->line('message8')
			));
		}
	}
	
	// new currency
	public function newCurrency() {
		$this->load->model('currency');
		if($this->input->post('submit')) {
			if($this->input->post('fldcurr_code') == NULL) {
				$currency_add = array(
					'fldid' => $this->input->post('fldid'), 'fldcurr_desc' => $this->input->post('acctCode')
				);
				
				$insert_currency = $this->currency->currency_insert($currency_add);
				if($insert_currency) {
					echo '<script>alert("Insert Data Success..");
						window.location.replace("chartOfAcctList");
						</script>';
				}
				else {
					echo '<script>alert("Insert Data Failed.");
						history.go(-1);</script>';
				}
			}
			else {
				$ID = $this->input->post('fldcurr_code');
				$currency_edit = array(
					'fldcurr_desc' => $this->input->post('acctCode')
				);
				// $this->load->model(company/Company_info_model);
				$this->load->model('CompanyChartAcct');
				$update_currency = $this->CompanyChartAcct->chartAcct_edit($currency_edit, $ID);
				if($update_currency) {
					echo '<script>alert("Update Success..");
						window.location.replace("chartOfAcctList");
						</script>';
				}
				else {
					echo '<script>alert("Update Failed.");
						history.go(-1);</script>';
				}
			}
		}
		else { // add default company id -akmal 20140605
			$fldid = isset($_REQUEST['fldid']) ? $_REQUEST['fldid'] : "";
			// $id = element('compID', $this->session->userdata('logged_in'));
			$this->load->library('layouts');
			$this->lang->load("chartofaccount", $this->session->userdata('language'));
			
			$addCurr = $this->currency->currency_all();
			$data['addCurrency'] = $addCurr[0];
			
			$this->layouts->add_includes('js/validationengine/languages/jquery.validationEngine-' . $this->session->userdata('language') . '.js')
				->add_includes('js/validationengine/jquery.validationEngine.js');
			$this->layouts->view('gl/setups/newCurrency', array(
				'latest' => 'sidebar/latest'
			), $data);
		}
	}
	
	// Currency Conversion
	
	public function currencyConvertion() {
		$this->load->model('UseraccessDetails');
		$queryBudgetEntry = $this->UseraccessDetails->UseraccessDetails_id_code('GLSTCURC');
		if(! $queryBudgetEntry) {
			echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
		}
		if($this->input->post('submit')) {

		}
		else {
			$this->load->model('Currency');
			$this->load->library('layouts');
			$data['currency'] = $this->Currency->currency_all();
			$this->lang->load("currency", $this->session->userdata('language'));
			$this->layouts->add_includes('js/validationengine/languages/jquery.validationEngine-' . $this->session->userdata('language') . '.js')
				->add_includes('js/validationengine/jquery.validationEngine.js')
				->add_includes('js/accounting.js');
			$this->layouts->view('gl/setups/currencyConv', array(
				'latest' => 'sidebar/latest'
			), $data);
		}
	}

	public function currencyConv_update() {
		$this->load->model('Currency');
		$data = $this->input->post('eContent');
		switch($this->input->post('fieldname')) {
			case 'startDate':
				$data = date("Y-m-d", strtotime($data));
				break;
			case 'endDate':
				$data = date("Y-m-d", strtotime($data));
				break;
		}
		$updateData = array(
			$this->input->post('fieldname') => $data
		);
		$query = $this->Currency->currencyConv_save($this->input->post('fldid'), $updateData);
		if($query) {
			print json_encode(array(
				"status" => "success", "message" => $this->lang->line('message7')
			));
		}
		else {
			print json_encode(array(
				"status" => "failed", "message" => $this->lang->line('message8')
			));
		}
	}

	public function currencyConv_insert() {
		$this->lang->load("budget", $this->session->userdata('language'));
		$this->load->model('Currency');
		$query = $this->Currency->currencyConv_insert();
		if($query) {
			print json_encode(array(
				"status" => "success", "message" => $this->lang->line('message7'), "details" => $query
			));
		}
		else {
			print json_encode(array(
				"status" => "failed", "message" => $this->lang->line('message8')
			));
		}
	}

	public function currencyConvSearch() {
		$this->load->model('Currency');
		$query = $this->Currency->currencyConv_fromTo($this->input->post('currFrom'), $this->input->post('currTo'));
		if($query) {
			print json_encode(array(
				"status" => "success", "message" => $this->lang->line('message7'), "details" => $query
			));
		}
		else {
			print json_encode(array(
				"status" => "failed", "message" => $this->lang->line('message8')
			));
		}
	}

	public function getRelatedChartOfAcct() {
		$this->load->model('companyChartAcct');
		print json_encode(array(
			"recordSet" => $this->companyChartAcct->getRelatedChartOfAcct($this->input->post('grpID'))
		));
	}
	
	// update opening balance according to chartOfAccount
	public function updateOpeningBalByID() {
		$companyID = element('compID', $this->session->userdata('logged_in'));
		$queryDate = $this->db->query("Select financialYear  from comp_financial_year where companyID = $companyID order by financialYear LIMIT 1");
		$queryDateRes = $queryDate->result();
		$success = 0;
		$year = date("Y");
		
		if($queryDate->num_rows() > 0) {
			$year = $queryDateRes[0]->financialYear;
		}
		
		$data = array(
			'debit' => $this->input->post('debit'), 'credit' => $this->input->post('credit')
		);
		$this->load->model('Chartofaccount');
		$res = $this->Chartofaccount->updateOpenngBalance($data, $this->input->post('idAcct'), $year);
		if($res)
			echo json_encode(array(
				'msg' => 'success'
			));
		else
			echo json_encode(array(
				'msg' => 'error'
			));
	}

	public function updateOpenngBalance() {
		$companyID = element('compID', $this->session->userdata('logged_in'));
		$query = $this->db->query("Select distinct year  from comp_opening_balance where companyID = $companyID");
		// insert new acctid created into opening balance - akmal
		//
		//
		$queryDate = $this->db->query("Select financialYear  from comp_financial_year where companyID = $companyID order by financialYear LIMIT 1");
		$queryDateRes = $queryDate->result();
		$success = 0;
		$year = date("Y");
		
		if($queryDate->num_rows() > 0) {
			$year = $queryDateRes[0]->financialYear;
		}
		
		if($query->num_rows() == 1) {
			
			$this->load->model('Chartofaccount');
			
			$n = sizeof($this->input->post('amtDebit'));
			$db = $this->input->post('amtDebit');
			$cr = $this->input->post('amtCredit');
			// $id = $this->input->post('idAcct');
			$id = $this->input->post('openingBalanceID');
			
			for($i = 0; $i < $n; $i ++) {
				$data = array(
					'debit' => str_replace(array(
					' ', ','
				), '', $db[$i]), 'credit' => str_replace(array(
					' ', ','
				), '', $cr[$i])
				);
				$res = $this->Chartofaccount->updateOpenngBalance($data, $id[$i], $year);
				// echo $res." id ". $id[$i].'/'.$db[$i]."<br/>";
				if($res)
					$success ++;
			}
		}
		else {
			
			if($query->num_rows() == 0) {
				$this->load->model('Chartofaccount');
				
				$n = sizeof($this->input->post('amtDebit'));
				$db = $this->input->post('amtDebit');
				$cr = $this->input->post('amtCredit');
				$id = $this->input->post('idAcct');
				$success = 0;
				
				for($i = 0; $i < $n; $i ++) {
					$data = array(
						'companyID' => element('compID', $this->session->userdata('logged_in')),
						'year' => $year, 'accountID' => $id[$i],
						'debit' => str_replace(array(
						' ', ','
					), '', $db[$i]), 'credit' => str_replace(array(
						' ', ','
					), '', $cr[$i])
					);
					$res = $this->Chartofaccount->insertOpenngBalance($data);
					if($res)
						$success ++;
				}
			}
		}
		if($query->num_rows() > 1) {
			echo '<script>alert("Update Not allowed");
                    window.location.replace("' . base_url() . 'glsetting/openingBalance");
                    </script>';
			exit();
		}
		if($success > 0) {
			echo '<script>
					window.location.replace("' . base_url() . 'glsetting/openingBalance");
					</script>';
		}
		else {
			echo '<script>alert("Update Failed"); history.go(-1);</script>';
		}
	}

	/**
	 * DISPLAY CHART OF ACCOUNT FOR OPENING BALANCE
	 * IF USER HAVE EXISTING OPENING BALANCE AND IT'S ALREADY YEAR END
	 * USER WON'T BE ABLE TO EDIT ANYTHING
	 * IF USER DOESN'T HAVE ANY OPENING BALANCE RECORD
	 * CHECK FINANCIAL YEAR AND PERIOD
	 * LIST ACCOUNT BASED ON FIRST FINANCIAL YEAR AND CREATE OPENING BALANCE FOR THAT FINANCIAL YEAR
	 * IF FIRST PERIOD IS 1
	 * USER WONT BE ABLE TO EDIT PROFIT & LOSS
	 * IF FIRST PERIOD MORE THAN 1
	 * USER WILL HAVE ACCESS TO BOTH BALANCE SHEET AND PROFIT & LOSS
	 * 
	 * @author NurSalikeen
	 * @modified Zul Zolkaffly (18/08/2016)
	 *	- Modify so that this method can be called within "apply" controller, method "index"
	 *	- Record now are separated to two years: current and previous. Thus the data array should be expanded to matrix of 3 layers instead.
	 */
	public function openingBalance() {
		$this->load->library('layouts');
		$this->load->model('Chartofaccount');
		$this->load->model('Compfinancialyear');
		
		$companyID = $this->session->userdata('companyID');
		
		$years = $this->ObjToArray($this->Chartofaccount->getFinancialYears($companyID));
		$balance = $this->ObjToArray($this->Chartofaccount->listChartOfAccount($companyID, 0));			
		$profit = $this->ObjToArray($this->Chartofaccount->listChartOfAccount($companyID, 1));
		
		$data['years'] = ($years) ? $years : array(date("Y"), date("Y")-1);
		
		// GET BALANCE
		$data['balance'] = NULL;
		if($balance) {
			foreach($balance as $key=>$value) {
				$data['balance'][$key] = $value;
				$data['balance'][$key]['data'] = NULL;
				if($years) {
					foreach($years as $year) {
						$data['balance'][$key]['data'][$year] = $this->ObjToArray($this->Chartofaccount->getOpeningBalance($companyID, $value['ID'], $year),true);
					}
				}
			}
		}
		// GET PROFIT
		$data['profit'] = NULL;
		if($profit) {
			foreach($profit as $key=>$value) {
				$data['profit'][$key] = $value;
				$data['profit'][$key]['data'] = NULL;
				if($years) {
					foreach($years as $year) {
						$data['profit'][$key]['data'][$year] = $this->ObjToArray($this->Chartofaccount->getOpeningBalance($companyID, $value['ID'], $year),true);
					}
				}
			}
		}
		
		$this->lang->load('comp_chartofaccount', $this->session->userdata('language'));
		$this->lang->load('acctGroup', $this->session->userdata('language'));
		$this->load->view('gl/setups/openingBalance', $data);
	}
	
	/**
	* @modified Zul Zolkaffly (18/08/2016)
	*	- Same as opening balance above, to be called by ajax when user select year
	*/
	public function openingBalanceAjax() {		
		$y = $this->input->post('y');
		$p = $this->input->post('p');
		
		if(!$y) exit();
		if(!$p) exit();
		
		$this->load->model('Chartofaccount');
		$this->load->model('Compfinancialyear');
		
		$companyID = $this->session->userdata('companyID');
		
		$years = array($y, $p);
		$balance = $this->ObjToArray($this->Chartofaccount->listChartOfAccount($companyID, 0));			
		$profit = $this->ObjToArray($this->Chartofaccount->listChartOfAccount($companyID, 1));
		
		$data['years'] = $years;
		
		$data['balance'] = NULL;
		if($balance) {
			foreach($balance as $key=>$value) {
				$data['balance'][$value['ID']] = NULL;
				if($years) {
					foreach($years as $y=>$year) {
						$data['balance'][$value['ID']][$y] = $this->ObjToArray($this->Chartofaccount->getOpeningBalance($companyID, $value['ID'], $year),true);
					}
				}
			}
		}
		
		$data['profit'] = NULL;
		if($profit) {
			foreach($profit as $key=>$value) {
				$data['profit'][$value['ID']] = NULL;
				if($years) {
					foreach($years as $y=>$year) {
						$data['profit'][$value['ID']][$y] = $this->ObjToArray($this->Chartofaccount->getOpeningBalance($companyID, $value['ID'], $year),true);
					}
				}
			}
		}
		
		echo json_encode($data);
	}
	
	/**
	* @modified Zul Zolkaffly (18/08/2016)
	*	- Function to update balance after user changed input value, called by ajax
	*/
	public function updateBalance() {
		if (!$this->session->userdata('companyID')) exit();
		if (!$this->input->post('accountID')) exit();
	
		$this->load->model('Chartofaccount');
		
		$data = array(
			'openingBalanceId' => $this->input->post('openingBalanceId'),
			'companyID' => $this->session->userdata('companyID'),
			'accountID' => $this->input->post('accountID'),
			'debit' => $this->input->post('debit'),
			'credit' => $this->input->post('credit'),
			'year' => $this->input->post('year')
		);
		
		$result = NULL;
		if($data['companyID'] && $data['year']) {
			if($result = $this->Chartofaccount->createOpeningBalance($data)) {			
				$sql = "SELECT COUNT(*) CT FROM `comp_financial_year` WHERE `companyID` = ".$data['companyID']." AND `financialYear` = ".$data['year'];
				$rs = $this->db->query($sql);
				if(!($rs && ($res = $rs->result()) && $res[0]->CT)) {
					$sql2 = "INSERT INTO comp_financial_year (
										companyID, financialYear, startDate, endDate, period, status, yearEnd
									) VALUES (
										".$data['companyID'].", ".$data['year'].", STR_TO_DATE('".$data['year']."-01-01', '%Y-%m-%d'), STR_TO_DATE('".$data['year']."-12-31', '%Y-%m-%d'), 1, 0, 1
									)";
					$this->db->query($sql2);
				}
			}
		}
		
		echo ($result) ? json_encode($result) : NULL;
	}	
	
	/**
	* @modified Zul Zolkaffly (23/08/2016)
	*	- Get Financial Position based on data keyed in in Opening Balance
	*	- Copied from controller GLReports
	*/
	public function financialposition(){
		$this->lang->load("bs",$this->session->userdata('language'));
		$this->lang->load("pnl",$this->session->userdata('language'));
		
		$this->load->model('general_model');
		$this->load->model('Compfinancialyear');
		$this->load->model('CompAcctGroup_model');
		$this->load->model('CompAcctDet');
		$this->load->model('Journal');
		$this->load->model('Retainedearning');
		
		$companyID = $this->session->userdata('companyID');

		$years = $this->ObjToArray($this->Chartofaccount->getFinancialYears($companyID));
		$data['years'] = ($years) ? $years : array(date("Y"), date("Y")-1);
		
		$add_year = ($data['years'][0]) ? $data['years'][0] : date("Y"); //$this->uri->segment(3);
		$add_period = 1; //$this->uri->segment(4);
		/*
		if(!$add_year){
			$add_year = date("Y");
		}
		if(!$add_period){
			$query = $this->Compfinancialyear->currPeriod();
			$add_period = !empty($query[0]->period)?$query[0]->period:0;
		}
		*/
		
		$data['asat'] = $this->Compfinancialyear->financialYear_yearperiod($add_year,$add_period);
		$data['yrs'] = $this->Compfinancialyear->financialCalendar_all_array();
		$data['selyear'] = $add_year;
		$data['selperiod'] = $add_period;
		$data['period'] = $this->Compfinancialyear->financialYear_year($add_year);
		$data['accountGroup'] = $this->CompAcctGroup_model->companyacctgroup_parentID();
		$data['groupdetails'] = $this->CompAcctGroup_model->companyacctgroup_subID();
		$data['accountdetails'] = $this->CompAcctDet->AcctDet_allfy_period2($add_year,$add_period);
		
		$accountGroupPNL = $this->CompAcctGroup_model->companyacctgroup_parentID_PNL();
		$groupdetailsPNL = $this->CompAcctGroup_model->companyacctgroup_subID_PNL();

		$status = $this->Compfinancialyear->financialCalendarCheckYear($add_year-1);				
		if(!empty($status)){
			$data['accountdetailslastyear'] = $this->CompAcctDet->AcctDet_allfy_period2($add_year-1,$status[0]->period);
			$data['currentretained'] = $this->Retainedearning->earning($add_year,$add_period);
			$data['lastyearretained'] = $this->Retainedearning->earning($add_year-1,$add_period,false);
		}else{
			$data['currentretained'] = $this->Retainedearning->earning($add_year,$add_period);
			$data['lastyearretained'] = 0;
		}
		
		$data['lastRetained'] = $this->lastYearRetained($add_year-1);
		$data['currRetain'] = $this->lastYearRetained($add_year);

		$data['activeTab'] = 1;
		
		$this->load->view('gl/financialposition', $data);
	}	
	
	/**
	* @modified Zul Zolkaffly (23/08/2016)
	*	- Copied from controller GLReports
	*/
	public function profitNloss($dateFrom = '',$dateTo = ''){
		$this->lang->load("pnl",$this->session->userdata('language'));
		$this->load->model('Compfinancialyear');
		$this->load->model('CompAcctGroup_model');
		$this->load->model('CompAcctDet');
		$this->load->model('Journal');
		if(empty($dateFrom)){
			$dateFrom = date("Y-01-01");
		}
		if(empty($dateTo)){
			$dateTo = date("Y-12-31");
		}


		$data['dateFrom'] = $dateFrom;
		$data['dateTo'] = $dateTo;

		$add_year = date("Y",strtotime($dateFrom));
		$add_period = date("m",strtotime($dateFrom));
		if(!$add_year){
			$add_year = date("Y");
		}
		if(!$add_period){
			$add_period = date("m");
		}
		$data['yrs'] = $this->Compfinancialyear->financialCalendar_all_array();//range(date('Y', strtotime('+1 year')), 1900);


		$data['selyear'] = $add_year;
		$data['selper'] = $add_period;
		$query = $this->Compfinancialyear->financialYear_year($add_year);
		if($query){
			$data['period'] = $query;
		}else{
			$data['period'] = NULL;
		}

		$data['accountGroup'] = $this->CompAcctGroup_model->companyacctgroup_parentID_PNL();
		$data['groupdetails'] = $this->CompAcctGroup_model->companyacctgroup_subID_PNL();
		$data['accountdetails'] = $this->CompAcctDet->AcctDet_allfypnl($add_year,$add_period);
		
		//echo "<pre>";
		//print_r($data['accountdetails']);
		//echo "</pre>";
				
		$data['activeTab'] = 0;
		$this->layouts
					->add_includes('plugins/select2/select2.css')
					->add_includes('plugins/select2/select2.js');
		$this->load->view('gl/pnl', $data);
	}
	
	/**
	* @modified Zul Zolkaffly (23/08/2016)
	*	- Copied from controller GLReports
	*/
	public function lastYearRetained($year){
		$this->load->model('CompAcctDet');
		$lastClosedYear = $this->CompAcctDet->yearPeriodClosed($year);
		$lastClosedYear = (!empty($lastClosedYear))?($lastClosedYear):($year-1);
		if($year <= $lastClosedYear){
			$ID = $this->CompAcctDet->getAcctID(120000000);
			return $this->CompAcctDet->openingBalance($ID,$year-1);
		}
		//$this->lastYearRetained($year-1);



		$period1 = $this->Compfinancialyear->get_lastPeriod($year);
		$period2 = $this->Compfinancialyear->get_lastPeriod($year-1);

		$this->load->model('Retainedearning');

		//$curEarning = $this->Retainedearning->earning($year,$period1);
		$lastEarning = $this->Retainedearning->earning($year-1,$period2,false);

		return $this->lastYearRetained($year-1)+$lastEarning;
	}
	
	

	/**
	 * UPDATE OPENING BALANCE BY ACCOUNT ID
	 * 
	 * @author NurSalikeen
	 */
	public function updateOpeningBalance($accountId = NULL) {
		if ($accountId == NULL) {
			exit();
		}
		else {
			$this->load->model('Chartofaccount');
			
			$data = array(
				'openingBalanceId' => $this->input->post('balance'),
				'companyID' => element('compID', $this->session->userdata('logged_in')),
				'accountID' => $accountId,
				'debit' => $this->input->post('debit'),
				'credit' => $this->input->post('credit'),
				'year' => $this->input->post('year')
			);
			
			echo json_encode($this->Chartofaccount->createOpeningBalance($data));
		}
	}

	 //-------------------------------------------farid start 1/3/2016
 
 public function openingbalanceList_print($mode = false) {
        $this->load->model('Chartofaccount');
        $this->load->model('company/company_info_model');

        $this->lang->load("comp_chartofaccount", $this->session->userdata('language'));
        $this->lang->load("acctGroup", $this->session->userdata('language'));
        $companyID = element('compID', $this->session->userdata('logged_in'));
        $companyName = element('compName', $this->session->userdata('logged_in'));

        $data['companyName'] = $companyName;
        $data['companyID'] = $companyID;

        $queryDate = $this->db->query("Select financialYear,period   from comp_financial_year where companyID = $companyID order by ID");
        $queryDateRes = $queryDate->result();
        $year = date("Y");
        $period = 1;
        if ($queryDate->num_rows() > 0) {
            $year = $queryDateRes[0]->financialYear;
            $period = $queryDateRes[0]->period;
        }
        
        $queryCheck = $this->db->query("Select distinct year  from comp_opening_balance where companyID = $companyID");

        $data['balance'] = $this->Chartofaccount->getChartofAcct($companyID, 0, $year);
       
        $headerData['rptTitle'] = $this->lang->line("balanceSheet");


        $bodyData['rptDataDetail'] = $data['balance'];
        $bodyData['tableHeader'] = array($this->lang->line("accountno"), $this->lang->line("accountName"), $this->lang->line("amountdebit"), $this->lang->line("amountcredit"));
        $bodyData['selectFields'] = array("acctCode", "acctName", "openingBalanceDr", "openingBalanceCr");

        $bodyData['tdAmount'] = array("openingBalanceDr","openingBalanceCr");

        $totalDr = 0;
        $totalCr  = 0;

        if($bodyData['rptDataDetail'])
        {
										foreach($bodyData['rptDataDetail']  as $row){
											 $totalDr += $row->openingBalanceDr;
											 $totalCr += $row->openingBalanceCr;
											}
        $bodyData['tableFooter'] = array ("Total :",
										number_format($totalDr,2),
										number_format($totalCr,2)									
								);
        //$bodyData['excelTitle'] = "Location Transfer Detail";

$body[] = $bodyData;
        if (!$mode) {
            //print
            $this->load->view('layouts/report/header', $headerData);
            $this->load->view('layouts/report/body-gst', $bodyData);
            //var_dump($bodyData2['selectFields']);
            $this->load->view('layouts/report/footer');
        } else {
            //download excell
            $this->load->helper('excel');
            excelgst($headerData,array($body),'');

        }
    }
}

 public function profitnlossList_print($mode = false) {
        $this->load->model('Chartofaccount');
        $this->load->model('company/company_info_model');

        $this->lang->load("comp_chartofaccount", $this->session->userdata('language'));
        $this->lang->load("acctGroup", $this->session->userdata('language'));
        $companyID = element('compID', $this->session->userdata('logged_in'));
        $companyName = element('compName', $this->session->userdata('logged_in'));

        $data['companyName'] = $companyName;
        $data['companyID'] = $companyID;

        $queryDate = $this->db->query("Select financialYear,period   from comp_financial_year where companyID = $companyID order by ID");
        $queryDateRes = $queryDate->result();
        $year = date("Y");
        $period = 1;
        if ($queryDate->num_rows() > 0) {
            $year = $queryDateRes[0]->financialYear;
            $period = $queryDateRes[0]->period;
        }

        $data['profitNloss'] = $this->Chartofaccount->getChartofAcct($companyID, 1, $year);

        $headerData['rptTitle'] = $this->lang->line("profitnloss");
        
        $bodyData['rptDataDetail'] = $data['profitNloss'];

        $bodyData['tableHeader'] = array($this->lang->line("accountno"), $this->lang->line("accountName"), $this->lang->line("amountdebit"), $this->lang->line("amountcredit"));
        $bodyData['selectFields'] = array("acctCode", "acctName", "openingBalanceDr", "openingBalanceCr");

        $bodyData['tableFooter'] = array("");
        $bodyData['excelTitle'] = "Location Transfer Detail";


        $bodyData['tdAmount'] = array("openingBalanceDr","openingBalanceCr");

        $totalDr2 = 0;
        $totalCr2  = 0;

        if($bodyData['rptDataDetail'])
        {
										foreach($bodyData['rptDataDetail']  as $row){
											 $totalDr2 += $row->openingBalanceDr;
											 $totalCr2 += $row->openingBalanceCr;
											}
        $bodyData['tableFooter'] = array ("Total :",
										number_format($totalDr2,2),
										number_format($totalCr2,2)									
								);

		$body[] = $bodyData;
        if (!$mode) {
            //print
            $this->load->view('layouts/report/header', $headerData);
            $this->load->view('layouts/report/body-gst', $bodyData);
            //var_dump($bodyData2['selectFields']);
            $this->load->view('layouts/report/footer');
        } else {
            //download excell
            $this->load->helper('excel');
            excelgst($headerData,array($body),'');

        }
    }
   
    


	}//-----------------------------------------------------------------------------farid end 1/3/2016

	/**
	* @title : OBJTOARRAY
	* @description : CONVERT FROM STDCLASS OBJECT TO ARRAY
	* @author : ZUL ZOLKAFFLY
	*	@create : 15/08/2016 (ZUL ZOLKAFFLY)
	*/
	private function ObjToArray($obj,$single=false) {
		return (!empty($obj)) ? json_decode(json_encode(($single)?$obj[0]:$obj),true) : NULL;
	}
	
}