<?php
include "class/class.MySQL.php";
$db = new MySQL();
$basicPay = "25000";
$designation = 2;
error_reporting(0);

$earningsDeduction = $db->fetchQuery("SELECT * FROM salary_designation A 
											   LEFT JOIN salary_structure B ON A.salary_structure_id = B.structure_id 
											   LEFT JOIN earning_deduction C ON B.earning_deduction_id	= C.id
											   WHERE A.designation_id='$designation'");
$eacalculation = array();										   
echo "<pre>";




$c=0;
foreach($earningsDeduction as $eacalculation){
	
	// Get All earnings
	if($eacalculation['type'] == 1){
		$calculation['earnings'][$c]['name'] 		= $eacalculation['name'];
		$calculation['earnings'][$c]['percentage'] 	= $eacalculation['percentage'];
		$calculation['earnings'][$c]['maxamount']	= $eacalculation['amount'];
		$calculation['earnings'][$c]['id']			= $eacalculation['id'];
		
		if($eacalculation['parent_id'] == 1 ){
			$parentAmount = $basicPay;
		}else{
			$parentAmount =searchForId($eacalculation['parent_id'], $calculation['earnings']);  
		}
		
		$calculation['earnings'][$c]['calculateAmt']= calculatePercent($eacalculation,$parentAmount);
		
		
	}
	
	// Get all deduction
	if($eacalculation['type'] ==2){
		$calculation['deduction'][$c]['name'] 		= $eacalculation['name'];
		$calculation['deduction'][$c]['percentage'] = $eacalculation['percentage'];
		$calculation['deduction'][$c]['maxamount']	= $eacalculation['amount'];
		$calculation['deduction'][$c]['id']			= $eacalculation['id'];


	
		if($eacalculation['parent_id'] == 1 ){
			$parentAmount = $basicPay;
		}elseif($eacalculation['parent_id'] == 2){
			$parentAmount = getGrossPay($calculation['earnings'],$basicPay);
		}else{
			$parentAmount =searchForId($eacalculation['parent_id'], $calculation['earnings'],'2');  
		}
		$calculation['deduction'][$c]['calculateAmt']= calculatePercent($eacalculation,$parentAmount);
		
	}
	$c++;
}



function calculatePercent($eacalculation,$parentAmount,$type="1"){
	$basicpay = $parentAmount;
	$percent  = $eacalculation['percentage'];
	$amount = $basicpay*($percent/100);
	return $amount;
}

function searchForId($id, $array) {
   foreach ($array as $key => $val) {
       if ($val['id'] === $id) {
           return $val['calculateAmt'];
       }
   }
   return null;
}

function getGrossPay($earnings,$basicPay){
	$grossPay  = $basicPay;
	foreach($earnings as $earnings){
		$grossPay +=$earnings['calculateAmt'];
	}
	return $grossPay;
}


print_r($calculation);







?>