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

/**
* MODEL FOR REQUEST
* @author : akmal
* @last-update : akmal (25/08/2016)
*/
class financial_model extends CI_Model {

	public function get_profit_n_los($param='') {
		if ($param == '') return null; 

		$this->db->select(' distinct b.companyID, '.$param['year'].' as year, b.acctGroupID, c.acctGroupName, c.orderNo',false)
			->select('(select sum(coalesce(debit,0) - coalesce(credit,0)) from comp_opening_balance ob, comp_chart_of_acct coa where ob.companyID = b.companyID and ob.year='.$param['year'].' and ob.accountID = coa.id and coa.acctGroupID = c.ID) as currentYear',false)
			->select('(select sum(coalesce(debit,0) - coalesce(credit,0)) from comp_opening_balance where companyID = b.companyID and year='.$param['year'].'-1 and acctGroupID = c.ID) as previousYear',false)
			->join('_ref_acct_group c','c.ID = b.acctGroupID','left',false)
			->where('b.companyID',$param['companyID'],false)
			->order_by('orderNo',false);
		$query = $this->db->get('comp_chart_of_acct b');
echo $this->db->last_query(); 
		$rs = (array)($query->num_rows() > 0)?$query->result():null; 
		
		if($rs) foreach($rs as $row) {
			$row['variance'] = $row['currentYear'] - $row['previousYear'];
			$row['ratio'] = $row['variance'] / (($row['previousYear']==0)?1:$row['previousYear']==0);
		}
//var_dump($rs); 
		
		return ($rs);
	}

	public function getMain($id) {
		$this->db->where('companyID', $id);
		$query = $this->db->get('apply_main');
		
		if ($query && $query->num_rows() >= 1) {
			$rs = $query->result();
			return ($rs[0]) ? $rs[0] : NULL;
		} else {
			return NULL;
		}
	}

	public function updateMain($id, $data) {
		$this->db->where('companyID', $id);
		$query = $this->db->update('apply_main', $data);
		
		return ($query === TRUE) ? TRUE : FALSE;
	}
	

}
