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

class Companies_table extends Base_table {

	function __construct()
	{
		parent::__construct(array(
			'tbl' => 'companies',
			'tbl_key' => 'id'
		));
	}

	function list_fields()
	{
		return array(
			'id', 'name', 'address1', 'address2', 'city', 'stateCode', 'stateId', 'stateName', 'zip', 'countryCode', 'country', 'email', 'phone', 'currency', 'fyStart', 'primUserid', 'dateFormat', 'logo', 'invsign', 'lockedTill', 'crdDate', 'isActive','addInfo','color','shortName'
		);
	}

	public function get_list($select='c.*', $userId=0, $where=null)
	{
		$this->CI->db->select($select);
		$this->CI->db->from($this->tbl . ' AS c');
		$this->CI->db->join('compusers AS cu', 'c.id=cu.cId');
		$this->CI->db->where('cu.userId', $userId);

		if (!empty($where) && is_array($where))
		{
			$this->CI->db->where($where);
		}

		$query = $this->CI->db->get();

		return $query->result_array();
	}

	public function formatdata(&$data)
	{
		if (empty($data['fyStart']) && !empty($data['countryCode'])) {
			$data['fyStart'] = 1;
			// april fiscal start date
			if (in_array($data['countryCode'], array('IN','HK','GB','NZ','ZA'))) {
				$data['fyStart'] = 4;
			}
			if (in_array($data['countryCode'], array('US','TH','CR'))) {
				$data['fyStart'] = 10;
			}
			if (in_array($data['countryCode'], array('AU','BD','EG'))) {
				$data['fyStart'] = 7;
			}
		}
		return true;
	}

	public function save($data, $params= array())
	{
		$values = parent::strip_fields($data);

		if (!$cId = parent::save($values))
		{
			return false;
		}

		$mainbId = $this->update_main_branch_details($cId);

		return $cId;
	}

	public function update_main_branch_details($cId=0)
	{
		if (!$cId)
		{
			return false;
		}

		$tmp = $this->CI->db->select('mainbId')->from('companies')->where('id',$cId)->get()->row_array();
		$mainbId = !empty($tmp['mainbId'])?$tmp['mainbId']:0;

		$query = "select ".($mainbId?$mainbId.' as id,':'')."c.id AS cId,if(jcc.name!='',jcc.name,'Main Branch') as name,if(jcc.name!='',jcc.name,'Main Branch') AS company,'B' AS csType,c.stateCode AS stateCode,c.stateId AS stateId,ifnull(c.email,'') as email,ifnull(c.phone,'') AS contactPersonMobile,1 AS isActive,jcc.taxNo as taxNo,jcc.conTaxScheme as conTaxScheme,jcc.perTax AS perTax,-1 AS plId,1 AS 'rank',-1 as bId,cs.defBank as defaultPayAcc from ob_companies as c 
		LEFT join ob_compsettings as cs on cs.cId=c.id
		LEFT join (select cc.cId,group_concat(if(cc.code='mainBranch',cc.value,null)) as name, group_concat(if(cc.code='gstin',cc.value,null)) as taxNo,group_concat(if(cc.code='isCompositionScheme' && cc.value,'C',NULL)) as conTaxScheme,
		group_concat(if(cc.code='pan',cc.value,null)) as perTax from ob_compconfig AS cc where cc.code in ('gstin','isCompositionScheme','pan','mainBranch') group by cId) as jcc on jcc.cId=c.id where c.id=".$cId;
		$main_cont = $this->CI->db->query($query)->row_array();

		// if (!empty($main_cont))
		// {
			$main_cont = array_map('strval', $main_cont);
			$this->CI->db->replace('contacts', $main_cont);
		// }

		$mainbId = $mainbId?$mainbId:$this->CI->db->insert_id();
		$this->CI->db->where('id', $cId);
		$this->CI->db->update('companies',array('mainbId' => $mainbId));

		//contacts_address
		$addr = $this->CI->db->select('id')->from('contacts_address')->where(array('cId' => $cId, 'conId'=>$mainbId))->get()->row_array();
		
		$this->CI->db->select(($addr?$addr['id'].' as id,':'').'cp.mainbId as conId,ifnull(cp.address1,"") as address1,ifnull(cp.address2,"") as address2, cp.city, cp.stateCode, cp.stateId, cp.stateName, cp.zip, cp.countryCode, cp.country, ifnull(cp.phone,"") as phone, "" as location, ifnull(cp.email,"") as email');
		$this->CI->db->from('companies as cp');
		$this->CI->db->join('contacts as c','c.id=cp.mainbId');
		$this->CI->db->where('cp.id', $cId);
		$cont_addr = $this->CI->db->get()->row_array();
		
		$cont_addr['cId']=$cId;
		$cont_addr = array_map('strval', $cont_addr);
		
		$this->CI->db->replace('contacts_address',$cont_addr);
		return $mainbId;				
	}
}

