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

class Retainedearning extends CI_Model{
	//modified on 2-1-2015 (Sayem Ahmed). Adding opening balance option.
	public function CurrentYear($accountGroup, $groupdetails, $accountdetails,$openBal = true ){
		//print_r($accountdetails);
		$datatbl_total_last = 0;
		$datatbl_total = 0;
		foreach($accountGroup as $datatbl):
			/*if($datatbl->acctTypeID != 3 || $datatbl->acctTypeID != 4){
				continue;
			}*/
      		foreach($accountdetails as $row):
      			//print_r($row);
      			if($row->acctGroupID == 3 || $row->acctGroupID ==4){
					if($row->currentyeardebit != '' || $row->currentyearcredit !='' || $row->openingBalanceDr !=0 || $row->openingBalanceCr !=0){ 
	                 	$totalamount_last_year = ($row->lastyearcredit+$openBal?$row->openingBalanceCr:0) - ($row->lastyeardebit+$openBal?$row->openingBalanceDr:0); 
	                 	$totalamount = ($row->currentyearcredit+$openBal?$row->openingBalanceCr:0) - ($row->currentyeardebit+$openBal?$row->openingBalanceDr:0); 
						$datatbl_total_last = $datatbl_total_last + $totalamount_last_year;

						//echo "(".$datatbl_total.")-------------------(".$totalamount.")----------".$row->acctGroupID."----------<br />";
						$datatbl_total = $datatbl_total + $totalamount;
					}
				} 
			endforeach;
      		if($groupdetails){
				foreach($groupdetails as $rowdet):
					$rowdet_credit = 0;
					if($rowdet->parentID == $datatbl->ID){
      					foreach($accountdetails as $row):
							if($row->acctGroupID == $rowdet->ID){
								if($row->currentyeardebit != '' || $row->currentyearcredit !='' || $row->openingBalanceDr !=0 || $row->openingBalanceCr !=0){ 
                 					$totalamount_last_year = ($row->lastyearcredit+($openBal?$row->openingBalanceCr:0)) - ($row->lastyeardebit+($openBal?$row->openingBalanceDr:0));
                 					$totalamount = ($row->currentyearcredit+($openBal?$row->openingBalanceCr:0)) - ($row->currentyeardebit+($openBal?$row->openingBalanceDr:0));
									$rowdet_credit = $rowdet_credit + $totalamount;
									$datatbl_total_last = $datatbl_total_last + $totalamount_last_year;
									$datatbl_total = $datatbl_total + $totalamount;
								}
							}
						endforeach;
						foreach($groupdetails as $rowdet1): 
							$rowdet1_credit = 0;
							if($rowdet1->parentID == $rowdet->ID){
								foreach($groupdetails as $rowdet2): 
									$rowdet2_credit = 0; 
									if($rowdet2->parentID == $rowdet1->ID){
 										foreach($groupdetails as $rowdet3): 
											$rowdet3_credit = 0; 
											if($rowdet3->parentID == $rowdet2->ID){
     											foreach($accountdetails as $row2):
													if($row2->acctGroupID == $rowdet3->ID){
														if($row2->currentyeardebit != '' || $row2->currentyearcredit !='' || $row2->openingBalanceDr !=0 || $row2->openingBalanceCr !=0){ 
                 											$totalamount_last_year = ($row2->lastyearcredit+($openBal?$row2->openingBalanceCr:0)) - ($row2->lastyeardebit+($openBal?$row2->openingBalanceDr:0));
                 											$totalamount = ($row2->currentyearcredit+($openBal?$row2->openingBalanceCr:0)) - ($row2->currentyeardebit+($openBal?$row2->openingBalanceDr:0));
															$datatbl_total_last = $datatbl_total_last + $totalamount_last_year;
															$datatbl_total = $datatbl_total + $totalamount;
														}
													}
												endforeach;
											}
										endforeach;
     									foreach($accountdetails as $row2):
											if($row2->acctGroupID == $rowdet2->ID){
												if($row2->currentyeardebit != '' || $row2->currentyearcredit !='' || $row2->openingBalanceDr !=0 || $row2->openingBalanceCr !=0){ 
                 									$totalamount_last_year = ($row2->lastyearcredit+($openBal?$row2->openingBalanceCr:0)) - ($row2->lastyeardebit+($openBal?$row2->openingBalanceDr:0)); 
                 									$totalamount = ($row2->currentyearcredit+($openBal?$row2->openingBalanceCr:0)) - ($row2->currentyeardebit+($openBal?$row2->openingBalanceDr:0)); 
													$datatbl_total_last = $datatbl_total_last + $totalamount_last_year;
													$datatbl_total = $datatbl_total + $totalamount;
												}
											}
										endforeach;
									}
								endforeach;
      							foreach($accountdetails as $row2):
									if($row2->acctGroupID == $rowdet1->ID){
										if($row2->currentyeardebit != '' || $row2->currentyearcredit !='' || $row2->openingBalanceDr !=0 || $row2->openingBalanceCr !=0){ 
                 							$totalamount_last_year = ($row2->lastyearcredit+($openBal?$row2->openingBalanceCr:0)) - ($row2->lastyeardebit+($openBal?$row2->openingBalanceDr:0));
                 							$totalamount = ($row2->currentyearcredit+($openBal?$row2->openingBalanceCr:0)) - ($row2->currentyeardebit+($openBal?$row2->openingBalanceDr:0));
											$datatbl_total_last = $datatbl_total_last + $totalamount_last_year;
											$datatbl_total = $datatbl_total + $totalamount;
										}
									}
								endforeach;
							}
						endforeach;
					}
				endforeach;
			}
		endforeach; 
		return $datatbl_total;
	}
	
	//current year earning...
	public function earning($year,$period,$current = true){
		$this->load->model('CompAcctDet');
		$lastClosedYear = $this->CompAcctDet->yearPeriodClosed($year);
		$lastClosedYear = (!empty($lastClosedYear))?($lastClosedYear):($year-1);

		$this->db->select("SUM(balance) as bal")->where(array(
													'companyID'=> $this->session->userdata('companyID'),			
													'acctType' => '3',					
													))
				->group_by('acctType');
		if($current){
			$this->db->where(array(
								'period <='=> intval($period),
								'year'	   => $year,
							));
		}else{
			$this->db->where(array(
								'year <='=> $year,
							));
			if($year != $lastClosedYear){
				$this->db->where('year >=', $lastClosedYear);
			}
		}
		$income = $this->db->get('view_expence_and_income')->result();


		$this->db->select("SUM(balance) as bal")
		        ->where(array(
						'companyID'=> $this->session->userdata('companyID'),				
						'acctType' => '4',					
						))
				->group_by('acctType');
		if($current){
			$this->db->where(array(
								'period <='=> intval($period),
								'year'	   => $year,
							));
		}else{
			$this->db->where(array(
								'year <='	   => $year,
							));
			if($year != $lastClosedYear){
				$this->db->where('year >', $lastClosedYear);
			}
		}
		$expence = $this->db->get('view_expence_and_income')->result();


		//find currenct PNL
		$this->load->model('Compfinancialyear');
		if(!$current)	$period = $this->Compfinancialyear->get_lastPeriod($year);

		$this->load->model('CompAcctGroup_model');
		$this->load->model('CompAcctDet');
		//Getting current year information
		$data['accountGroup'] = $this->CompAcctGroup_model->companyacctgroup_parentID_PNL();
		$data['groupdetails'] = $this->CompAcctGroup_model->companyacctgroup_subID_PNL();
		$data['accountdetails'] = $this->CompAcctDet->AcctDet_allfypnl($year,$period);
		$data['selyear'] = $year;
		$data['selper'] = $period;
		$this->load->library('parser');
		$this->lang->load("pnl",$this->session->userdata('language'));
		$pnl = $this->getPnl($data);//$this->parser->parse('gl/transactions/pnlParse', $data, TRUE);
		/*echo $pnl;
		exit();*/
		return $pnl;


		if(!empty($income) && !empty($expence)){
			return $income[0]->bal - $expence[0]->bal;
		}elseif(empty($income) && !empty($expence)){
			return $expence[0]->bal*(-1);
		}elseif(!empty($income) && empty($expence)){
			return $income[0]->bal;
		}else{
			return 0;
		}
	}

	public function getPnl($data){
		$accountGroup = $data['accountGroup'];
		$groupdetails = $data['groupdetails'];
		$accountdetails = $data['accountdetails'];
		if(empty($accountdetails)){
			return 0;
		}
		$selyear = $data['selyear'];
		$selper = $data['selper'];
		$bil = 0; 
		$datatbl_total = 0;
		$datatbl_budgettotal = 0;
		if($accountGroup){
			$bil = 1;
			foreach($accountGroup as $datatbl){
				foreach($accountdetails as $row){
					if($row->acctGroupID == $datatbl->ID){
						if(($row->currentyeardebit != '' && $row->currentyearcredit !='')) {
							$totalamount =  $row->currentyeardebit - $row->currentyearcredit;

							$datatbl_total = $datatbl_total + $totalamount;
						}
					} 
				}//endforeach;
				if($groupdetails){ 
					foreach($groupdetails as $rowdet){
						$rowdet_credit = 0;
						$rowdet_budgetcredit = 0;
						if($rowdet->parentID == $datatbl->ID){

							foreach($accountdetails as $row){
								if($row->acctGroupID == $rowdet->ID){	

									if($row->currentyeardebit != '' || $row->currentyearcredit !=''){
										$totalamount = ($row->currentyeardebit+$row->openingBalanceDr) - ($row->currentyearcredit+$row->openingBalanceCr);

										$rowdet_credit = $rowdet_credit + $totalamount;
										$datatbl_total = $datatbl_total + $totalamount;
									} 
						 		} 
							}//endforeach;
							foreach($groupdetails as $rowdet1){
								$rowdet1_credit = 0; 
								$rowdet1_budgetcredit = 0; 
								if($rowdet1->parentID == $rowdet->ID){
									foreach($groupdetails as $rowdet2){ 
										$rowdet2_credit = 0; 
										$rowdet2_budgetcredit = 0; 
										if($rowdet2->parentID == $rowdet1->ID){
											foreach($groupdetails as $rowdet3){ 
												$rowdet3_credit = 0; 
												$rowdet3_budgetcredit = 0;
												if($rowdet3->parentID == $rowdet2->ID){
													foreach($accountdetails as $row2){
														if($row2->acctGroupID == $rowdet3->ID){
															if($row2->currentyeardebit != '' || $row2->currentyearcredit !=''){ 
																$totalamount =  $row2->currentyeardebit - $row2->currentyearcredit;

																$rowdet_credit = $rowdet_credit + $totalamount;
																$rowdet1_credit = $rowdet1_credit + $totalamount;
																$rowdet2_credit = $rowdet2_credit + $totalamount;
																$rowdet3_credit = $rowdet3_credit + $totalamount;

																$datatbl_total = $datatbl_total + $totalamount;
															}
														}	 
													}//endforeach;
												} 
											}//endforeach;
											foreach($accountdetails as $row2){
												if($row2->acctGroupID == $rowdet2->ID){
									
													if($row2->currentyeardebit != '' || $row2->currentyearcredit !=''){ 
														$totalamount =  $row2->currentyeardebit - $row2->currentyearcredit;
														$rowdet_credit = $rowdet_credit + $totalamount;
														$rowdet1_credit = $rowdet1_credit + $totalamount;
														$rowdet2_credit = $rowdet2_credit + $totalamount;
														$datatbl_total = $datatbl_total + $totalamount;
													} 
												}
											}//endforeach;
										}
									}//endforeach;
									foreach($accountdetails as $row2){
										if($row2->acctGroupID == $rowdet1->ID){

											if($row2->currentyeardebit != '' || $row2->currentyearcredit !=''){
												$totalamount = $row2->currentyeardebit - $row2->currentyearcredit;

												$rowdet_credit = $rowdet_credit + $totalamount;
												$rowdet1_credit = $rowdet1_credit + $totalamount;
												$datatbl_total = $datatbl_total + $totalamount;
											} 
										}
									}//endforeach;
								}
							}//endforeach;
						}
					}//endforeach;
					if($datatbl->status == 1){

						echo $datatbl->status."<->".$datatbl_total."\r\n";
						//echo ($datatbl_total < 0 )?'('.number_format($datatbl_total,2).')':number_format($datatbl_total * -1,2);
						return ($datatbl_total < 0 )?$datatbl_total*-1:$datatbl_total;
					}else{
						//echo ">>>>>>>".$selyear.">>>".$selper."<->".$datatbl->status."<->".$datatbl_total."<<<<<<<<<<<\r\n";
						//echo ($datatbl_total > 0 )?'('.number_format($datatbl_total,2).')':number_format($datatbl_total * -1,2);
						return $datatbl_total;//($datatbl_total > 0 )?$datatbl_total:$datatbl_total*-1;
					}
				}
			}//endforeach;
		}
	}


	//Income and Expenses
	public function incomeNexpenses($year,$period,$current = 0){
		$this->load->model('CompAcctDet');
		//$lastClosedYear = $this->CompAcctDet->yearPeriodClosed($year);
		$lastClosedYear = $year-1;

		/*
		'cogs' => array('8', false),
        'operational' => array('10', false),
        'loan' => array('4', true),
        'asset' => array('2', true),
		*/

		$this->db->select("SUM(balance) as bal")->where(array(
													'companyID'=> $this->session->userdata('companyID'),			
													'acctType' => '3',					
													))
				->group_by('acctType');
		if($current == 1){
			$this->db->where(array(
								'period <='=> intval($period),
								'year'	   => $year,
							));
		}elseif($current == 2){
			$this->db->where(array(
								'period '=> intval($period),
								'year'	   => $year,
							));
		}else{
			$this->db->where(array(
								'year <='=> $year,
							));
			if($year != $lastClosedYear){
				$this->db->where('year >=', $lastClosedYear);
			}
		}
		$income = $this->db->get('view_expence_and_income')->result();


		$this->db->select("SUM(balance) as bal")
		        ->where(array(
						'companyID'=> $this->session->userdata('companyID'),				
						'acctType' => '4',					
						))
				->group_by('acctType');
		if($current == 1){
			$this->db->where(array(
								'period <='=> intval($period),
								'year'	   => $year,
							));
		}if($current == 2){
			$this->db->where(array(
								'period '=> intval($period),
								'year'	   => $year,
							));
		}else{
			$this->db->where(array(
								'year <='	   => $year,
							));
			if($year != $lastClosedYear){
				$this->db->where('year >', $lastClosedYear);
			}
		}
		$expence = $this->db->get('view_expence_and_income')->result();

		if(!empty($income) && !empty($expence)){
			return array('income'=>$income[0]->bal,'expense'=>$expence[0]->bal*(-1));
		}elseif(empty($income) && !empty($expence)){
			return array('income'=>0,'expense'=>$expence[0]->bal*(-1));
		}elseif(!empty($income) && empty($expence)){
			return array('income'=>$income[0]->bal,'expense'=>0);
		}else{
			return array('income'=>0,'expense'=>0);
		}
	}

	/*
	////////////////////-------------------neutralize opening balance for old companies
	//update
	UPDATE `comp_opening_balance` a

	left join comp_chart_of_acct b on b.ID = a.accountID
	left join _ref_acct_group c on c.ID = b.acctGroupID

	SET a.`debit`=0,a.`credit`=0

	WHERE a.companyID = 131 and a.year > 2013 and (c.acctTypeID = 3 or c.acctTypeID = 4)


	//Select
	SELECT a.companyID,a.year,a.debit,a.credit,
	b.acctGroupID,c.acctTypeID 


	FROM `comp_opening_balance` a 

	left join comp_chart_of_acct b on b.ID = a.accountID
	left join _ref_acct_group c on c.ID = b.acctGroupID
	where a.companyID = 131 and a.year > 2013 
	and (c.acctTypeID = 3 or c.acctTypeID = 4)
	*/
}

// Created By Yahaya Abdollah
// Dated : 30th May 2014