<?php
include_once("../class/class.MySQL.php");
include_once("../class/resizeImage.php");

$db	=new MySQL();

if($_GET['action'] == 'loademp_details'){

	$emp_id 		= $_GET['emp_id'];
	$financial_year = $_GET['financial_year'];
	$empname_list = $db->fetchQuery("select *,CONCAT(e_fname,e_lname) as emp_name,DATE_FORMAT(STR_TO_DATE(date_join,'%d-%m-%Y'),'%d %b %Y')as date_join from employee  where e_id=".$emp_id);
	echo '{"empnamelist":'.json_encode($empname_list).'}';
}

if($_GET['action'] == 'insert'){

	$ded_id			= $_POST['ded_id'];
	$ded_amnt		= $_POST['ded_amnt'];
	$emp_id			= $_POST['emp_id'];
	$financial_year = $_POST['financial_year'];
	for($i=0;$i<count($ded_id);$i++)
	{
		$check_ded_exist = $db->fetchQuery("SELECT count(*) as cnt FROM users_incometax_deductions where deduction_id=".$ded_id[$i]." AND emp_id=".$emp_id." AND financial_yr_id=".$financial_year);
		if($check_ded_exist[0]['cnt']){
			$data['deduction_id']   	= $ded_id[$i];
			$data['amount'] 	    	= $ded_amnt[$i];
			$data['emp_id'] 	    	= $emp_id;
			$where['emp_id']	    	= $emp_id;
			$where['deduction_id']		= $ded_id[$i];
			$where['financial_yr_id']	= $financial_year;
			
			$db->Update('users_incometax_deductions',$data,$where);
		} else {
			$data['deduction_id'] 		= $ded_id[$i];
			$data['amount'] 	  		= $ded_amnt[$i];
			$data['emp_id'] 	  		= $emp_id;
			$data['financial_yr_id'] 	= $financial_year;
			$db->Insert($data,'users_incometax_deductions');
		}
	}
	$check_note_exist = $db->fetchQuery("SELECT count(*) as cnt FROM users_incometax_deduction_notes where emp_id=".$emp_id." AND financial_yr_id=".$financial_year);
	if($check_note_exist[0]['cnt']){
			$data1['declaration_note']     = $_POST['declaration_note'];
			$data1['rental_note']  		   = $_POST['rental_note'];
			$data1['section_note']  	   = $_POST['section_note'];
			$data1['pre_emp_note']  	   = $_POST['pre_emp_note'];
			$data1['other_income_note']    = $_POST['other_income_note'];
			$data1['other_income1']        = $_POST['other_income1'];
			$data1['other_income2']  	   = $_POST['other_income2'];
			$data1['other_income1_amount'] = $_POST['other_income1_amount'];
			$data1['other_income2_amount'] = $_POST['other_income2_amount'];
			$where1['emp_id']	           = $emp_id;
			$where1['financial_yr_id']	   = $financial_year;
			$db->Update('users_incometax_deduction_notes',$data1,$where1);
	} else {
			$data1['emp_id'] 	 		    = $emp_id;
			$data1['declaration_note']      = $_POST['declaration_note'];
			$data1['rental_note']  		    = $_POST['rental_note'];
			$data1['section_note']  		= $_POST['section_note'];
			$data1['pre_emp_note']  		= $_POST['pre_emp_note'];
			$data1['other_income_note']     = $_POST['other_income_note'];
			$data1['other_income1']         = $_POST['other_income1'];
			$data1['other_income2']  	    = $_POST['other_income2'];
			$data1['other_income1_amount']  = $_POST['other_income1_amount'];
			$data1['other_income2_amount']  = $_POST['other_income2_amount'];
			$data1['financial_yr_id'] 		= $financial_year;
			$db->Insert($data1,'users_incometax_deduction_notes');
	}
	
}

if($_GET['action'] == 'load_incometax_details'){

	$emp_id 		  = $_GET['emp_id'];
	$financial_year   = $_GET['financial_year'];
	$declaration_list = $db->fetchQuery("select * from users_incometax_deductions  where emp_id=".$emp_id." AND financial_yr_id=".$financial_year." ORDER BY id	ASC");
	$notes_list = $db->fetchQuery("select * from users_incometax_deduction_notes  where emp_id=".$emp_id." AND financial_yr_id=".$financial_year);
	$landlord_list = $db->fetchQuery("select * from landlord_details  where emp_id=".$emp_id." AND financial_yr_id=".$financial_year);
	echo '{"declaration_list":'.json_encode($declaration_list).',"notes_list":'.json_encode($notes_list).',"landlord_list":'.json_encode($landlord_list).'}';
}

if($_GET['action'] == 'landlord_insert'){

	$emp_id			= $_POST['emp_id'];
	$financial_year = $_POST['financial_year'];
	$check_lnd_exist = $db->fetchQuery("SELECT count(*) as cnt FROM landlord_details where emp_id=".$emp_id." AND financial_yr_id=".$financial_year);
	if($check_lnd_exist[0]['cnt']){
		$data1['landlord_name']          = $_POST['landlord_name'];
		$data1['landlord_address']  	 = $_POST['landlord_address'];
		$data1['landlord_has_pan']  	 = $_POST['landlord_has_pan'];
		$data1['landlord_pan_number']  	 = $_POST['landlord_pan_number'];
		$data1['landloard_declaration']  = $_POST['landloard_declaration'];
		$where['emp_id']	   			 = $emp_id;
		$where['financial_yr_id']	   	 = $financial_year;
		$db->Update('landlord_details',$data1,$where);
	} else {
		$data1['emp_id'] 	 		     = $emp_id;
		$data1['landlord_name']          = $_POST['landlord_name'];
		$data1['landlord_address']  	 = $_POST['landlord_address'];
		$data1['landlord_has_pan']  	 = $_POST['landlord_has_pan'];
		$data1['landlord_pan_number']  	 = $_POST['landlord_pan_number'];
		$data1['landloard_declaration']  = $_POST['landloard_declaration'];
		$data1['financial_yr_id'] 		 = $financial_year;
		$db->Insert($data1,'landlord_details');
	}
	
	$data	= array();
	if(isset($_FILES['fileupload']['name']) && $_FILES['fileupload']['name']!=''){
		$randnum						= rand(12000,9999999);
		$image							= $randnum.$_FILES['fileupload']['name'];
		$data['landloard_declaration']	= $image;
		$pathimg						= "../upload/landlord_declaration/".$image;
		
		try {
			$image  = new ImageResize($_FILES['fileupload']['tmp_name']);
			/// Save Image
			$image1 = new ImageResize($_FILES['fileupload']['tmp_name']);
			$image1->resizeToWidth(500);
			$image1->save($pathimg);
		} catch (Exception $e) {

		}
		$where1['emp_id']	   			 = $emp_id;
		$db->Update('landlord_details',$data,$where1);
	}
}
if($_GET['action'] == 'tax_calculation'){

	$emp_id			= $_GET['emp_id'];
	$financial_year = $_GET['financial_year'];
	$month		    = $_POST['month']; 
	$financial_yr = $db->fetchQuery("SELECT * FROM  `financial_year` WHERE id=$financial_year");
	$fin_year 		= explode('-',$financial_yr[0]['financial_year']);
	
	$EmpPayStructure_row = $db->fetchQuery("SELECT A.e_id,A.employee_id,A.e_post,emp_basic_pay FROM employee A WHERE A.e_id=$emp_id");
	$basicPay            = $EmpPayStructure_row[0]['emp_basic_pay'];
	
	$condition_structure['employee_id'] = $emp_id;
	$emp_str_count = $db->CountRows('salary_structure_employee',$condition_structure);
		
	if($emp_str_count == 0){
		$str_type=1;
		$designation = $EmpPayStructure_row[0]['e_post'];
	}else{
		$str_type=2;
		$designation = $EmpPayStructure_row[0]['e_id'];
	}
	$earning_deductions 	= earningDeductionFields($designation,$basicPay,$str_type);	
	$employee_earnings  	= $earning_deductions['earnings'];
	$employee_deductions    = $earning_deductions['deduction'];			
	
	
	$taxable_income	= '<td  style="border:none;" valign="top">
						<table class="table-info" style="vertical-align:top;">
							<tr>
								<th>Item</th>
								<th>Total</th>
							</tr>
							<tr>
								<td colspan="2">(i) Monthly Income</td>
							</tr>';
							foreach($employee_earnings as $earnings) {
							
								$tl_earnings	= $tl_earnings+$earnings['calculateAmt'];
								$total_earnings = $tl_earnings?$tl_earnings:"0.00";
	$taxable_income	.=		'<tr>
								<td>'.strtoupper($earnings['name']).'</td>
								<td>'.$earnings['calculateAmt'].'</td>
							</tr>';
							}
	$taxable_income	.=		'<tr>
								<td><strong>Total</strong></td>
								<td><strong>'.$total_earnings.'</strong></td>
							</tr>
							<tr style="background-color:#98cae0;">
								<td><strong>Sub Total</strong></td>
								<td><strong>'.$total_earnings.'</strong></td>
							</tr>
						</table>
					</td>
					<td  style="border:none;" valign="top">	
						<table class="table-info" width="100%" style="vertical-align:top;">
						<tr>
							<th>April '.$fin_year[0].'</th>
							<th>May '.$fin_year[0].'</th>
							<th>Jun '.$fin_year[0].' </th>
							<th>Jul '.$fin_year[0].'</th>
							<th>Aug '.$fin_year[0].' </th>
							<th>Sep '.$fin_year[0].' </th>
							<th>Oct '.$fin_year[0].'</th>
							<th>Nov '.$fin_year[0].'</th>
							<th>Dec '.$fin_year[0].'</th>
							<th>Jan '.$fin_year[1].'</th>
							<th>Feb '.$fin_year[1].'</th>
							<th>Mar '.$fin_year[1].'</th>
						</tr>
						<tr>
							<td colspan="12">&nbsp;</td>
						</tr>';
						foreach($employee_earnings as $earnings) {
								
								$monthly_amount 		= $earnings['calculateAmt']/12;
								$monthly_total_earnings	= $monthly_total_earnings+ $monthly_amount;
	$taxable_income	.=	'<tr>
							<td>'.$monthly_amount.'</td>
							<td>'.$monthly_amount.'</td>
							<td>'.$monthly_amount.'</td>
							<td>'.$monthly_amount.'</td>
							<td>'.$monthly_amount.'</td>
							<td>'.$monthly_amount.'</td>
							<td>'.$monthly_amount.'</td>
							<td>'.$monthly_amount.'</td>
							<td>'.$monthly_amount.'</td>
							<td>'.$monthly_amount.'</td>
							<td>'.$monthly_amount.'</td>
							<td>'.$monthly_amount.'</td>
						</tr>';
						}
	$taxable_income	.=	'<tr>
							<td>'.$monthly_total_earnings.'</td>
							<td>'.$monthly_total_earnings.'</td>
							<td>'.$monthly_total_earnings.'</td>
							<td>'.$monthly_total_earnings.'</td>
							<td>'.$monthly_total_earnings.'</td>
							<td>'.$monthly_total_earnings.'</td>
							<td>'.$monthly_total_earnings.'</td>
							<td>'.$monthly_total_earnings.'</td>
							<td>'.$monthly_total_earnings.'</td>
							<td>'.$monthly_total_earnings.'</td>
							<td>'.$monthly_total_earnings.'</td>
							<td>'.$monthly_total_earnings.'</td>
						 </tr>
						 <tr>
							<td colspan="12" style="background-color:#98cae0;">&nbsp;</td>
						 </tr>
					</table>
				</td>	';	
				
	$deductions	= '<td  style="border:none;" valign="top">
						<table class="table-info" style="vertical-align:top;">
							<tr>
								<th>Item</th>
								<th>Total</th>
							</tr>
							<tr>
								<td colspan="2">(i) Monthly Income</td>
							</tr>';
							foreach($employee_deductions as $deduction) {
								$tl_deductions	  = $tl_deductions+$deduction['calculateAmt'];
								$total_deductions = $tl_deductions?$tl_deductions:"0.00";
	$deductions	.=		'<tr>
								<td>'.strtoupper($deduction['name']).'</td>
								<td>'.$deduction['calculateAmt'].'</td>
							</tr>';
							}
	$deductions	.=		'<tr>
								<td><strong>Total</strong></td>
								<td><strong>'.$total_deductions.'</strong></td>
							</tr>
							<tr style="background-color:#98cae0;">
								<td><strong>Sub Total</strong></td>
								<td><strong>'.$total_deductions.'</strong></td>
							</tr>
						</table>
					</td>
					<td  style="border:none;" valign="top">	
						<table class="table-info" width="100%" style="vertical-align:top;">
						<tr>
							<th>April '.$fin_year[0].'</th>
							<th>May '.$fin_year[0].'</th>
							<th>Jun '.$fin_year[0].' </th>
							<th>Jul '.$fin_year[0].'</th>
							<th>Aug '.$fin_year[0].' </th>
							<th>Sep '.$fin_year[0].' </th>
							<th>Oct '.$fin_year[0].'</th>
							<th>Nov '.$fin_year[0].'</th>
							<th>Dec '.$fin_year[0].'</th>
							<th>Jan '.$fin_year[1].'</th>
							<th>Feb '.$fin_year[1].'</th>
							<th>Mar '.$fin_year[1].'</th>
						</tr>
						<tr>
							<td colspan="12">&nbsp;</td>
						</tr>';
						foreach($employee_deductions as $deduction) {
								$monthly_amount 		 = $deduction['calculateAmt']/12;
								$monthly_total_deduction = $monthly_total_deduction+ $monthly_amount;
	$deductions	.=	'<tr>
							<td>'.$monthly_amount.'</td>
							<td>'.$monthly_amount.'</td>
							<td>'.$monthly_amount.'</td>
							<td>'.$monthly_amount.'</td>
							<td>'.$monthly_amount.'</td>
							<td>'.$monthly_amount.'</td>
							<td>'.$monthly_amount.'</td>
							<td>'.$monthly_amount.'</td>
							<td>'.$monthly_amount.'</td>
							<td>'.$monthly_amount.'</td>
							<td>'.$monthly_amount.'</td>
							<td>'.$monthly_amount.'</td>
						</tr>';
						}
	$deductions	.=	'<tr>
							<td>'.$monthly_total_deduction.'</td>
							<td>'.$monthly_total_deduction.'</td>
							<td>'.$monthly_total_deduction.'</td>
							<td>'.$monthly_total_deduction.'</td>
							<td>'.$monthly_total_deduction.'</td>
							<td>'.$monthly_total_deduction.'</td>
							<td>'.$monthly_total_deduction.'</td>
							<td>'.$monthly_total_deduction.'</td>
							<td>'.$monthly_total_deduction.'</td>
							<td>'.$monthly_total_deduction.'</td>
							<td>'.$monthly_total_deduction.'</td>
							<td>'.$monthly_total_deduction.'</td>
						 </tr>
						 <tr>
							<td colspan="12" style="background-color:#98cae0;">&nbsp;</td>
						 </tr>
					</table>
				</td>	';			
					echo '{"taxable_income":'.json_encode($taxable_income).',"tax_deduction":'.json_encode($deductions).'}';
					
}

function earningDeductionFields($designation,$basicPay,$str_type=1)
{
	if($str_type == 1){
	
	$earningsDeduction = $GLOBALS[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' ORDER BY B.id ASC");
	}else{
		
	
	$earningsDeduction = $GLOBALS[db]->fetchQuery("SELECT * FROM salary_structure_employee 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.employee_id='$designation' ORDER BY B.id ASC");	
	}
	if($basicPay == 0){
		$basicPay = $earningsDeduction[0]['amount'];
	}			
	$eacalculation = array();
	$c=0;
	foreach($earningsDeduction as $eacalculation){
		// Get All earnings
		if($eacalculation['type'] == 1){
			$calculation['earnings'][$c]['name'] 		= $eacalculation['name'];
			$calculation['earnings'][$c]['parentid'] 	= $eacalculation['parent_id'];
			$calculation['earnings'][$c]['percentage'] 	= $eacalculation['percentage'];
			$calculation['earnings'][$c]['maxamount']	= $eacalculation['amount'];
			$calculation['earnings'][$c]['id']			= $eacalculation['id'];
			$maxamount 									= $eacalculation['amount'];
			if($eacalculation['parent_id'] == 0 ){
				$parentAmount = $basicPay;
			}else{
				$parentAmount =searchForId($eacalculation['parent_id'], $calculation['earnings']);  
			}
			
			$calculation['earnings'][$c]['calculateAmt']= calculatePercent($eacalculation,$parentAmount,$maxamount);
			
			
		}
		
		// Get all deduction
		if($eacalculation['type'] ==2){
			$calculation['deduction'][$c]['name'] 		= $eacalculation['name'];
			$calculation['deduction'][$c]['parentid'] 		= $eacalculation['parent_id'];
			$calculation['deduction'][$c]['percentage'] = $eacalculation['percentage'];
			$calculation['deduction'][$c]['maxamount']	= $eacalculation['amount'];
			$calculation['deduction'][$c]['id']			= $eacalculation['id'];
			$maxamount = $eacalculation['amount'];
			
			if($eacalculation['parent_id'] == 0 ){
			
				$parentAmount = $basicPay;
				
			}elseif($eacalculation['parent_id'] == 2){
			
				$parentAmount = getGrossPay($calculation['earnings'],$basicPay);
			
			}else{
				$parentAmount =searchForId($eacalculation['parent_id'], $calculation['earnings']);  
			}
			
			$calculation['deduction'][$c]['calculateAmt']= calculatePercent($eacalculation,$parentAmount,$maxamount);
			
		}
		
		$c++;	
	}
	return $calculation;
}
function searchForId($id, $array) {
   foreach ($array as $key => $val) {
       if ($val['id'] === $id) {
           return $val['calculateAmt'];
       }
   }
   return null;
}

function getGrossPay($earnings,$basicPay){
//print_r($earnings);
	$grossPay  = 0;
	foreach($earnings as $earnings){
		 $grossPay +=$earnings['calculateAmt'];
	}
	return $grossPay;
}
function calculatePercent($eacalculation,$parentAmount,$maxamount){
	$basicpay = $parentAmount;
	$percent  = $eacalculation['percentage'];
	$amount = $basicpay*($percent/100);
	if(round($basicpay))
	{
		if($amount && round($maxamount))
		{
			$amount = ($amount < $maxamount)?$amount:$maxamount;
		}
		elseif($amount)
		{
			$amount =$amount;
		}
		else
		{
			$amount = $maxamount;
		}
	}
	else
	{
		$amount=0;
	}
	
	return $amount;
}
?>