<?php
/*
* date last modified 28-11-2017
* Edited by PI-Digi Logical Solutions
* HTML Files - add_user.html.php
* Mysql Tables - tbl_designation, tbl_staff
*/
include('includes/functions.php'); # general functions


$debug = true;

if(isset($_REQUEST['task_id']) && $_REQUEST['task_id']!=''){
	$taskId = trim($_REQUEST['task_id']);
	$chRs = mysqli_query($con, "SELECT technician_id FROM tbl_job WHERE id = '".$taskId."'");
	if(mysqli_num_rows($chRs)>0){
		//ok
		//get all extra techs
		$chkExtraRs = mysqli_query($con, "SELECT id, technician_id, commission_percent FROM tbl_job_extra_tech WHERE job_id = '".$taskId."' AND technician_id != '0' AND status != 'rejected'");
	} else {
		$error = 'Sorry, unable to find the task';
	}
	
	$taskRec = mysqli_fetch_array(mysqli_query($con, "SELECT technician_id, admin_commission_percent, fixed_rate, admin_discount, admin_extra, tech_discount FROM tbl_job WHERE id = '".$taskId."'"));
	$adminCommission = $taskRec['admin_commission_percent'];
	$fixedRate = $taskRec['fixed_rate'];
	$mainTechId = $taskRec['technician_id'];
	$adminDiscount = $taskRec['admin_discount'];
	$adminExtra = $taskRec['admin_extra'];
	$techDiscount = $taskRec['tech_discount'];
	$totalDiscounts = $adminDiscount+$techDiscount-$adminExtra;
	
	

	if(isset($_POST['submit'])) {
		
		$totalVal = 0;
		$extraIdArray = array();		
		
		if(isset($_POST['admin_commission']) && strlen($_POST['admin_commission'])>0) {
			$admin_commission = trim($_POST['admin_commission']);
			if(is_numeric($admin_commission) && $admin_commission>=0 && $admin_commission<=100){
				//ok						
			} else {
				$error = 'Please enter a valid commission for admin';
			}
		} else {
			$error = 'Please enter commission for admin';
		}
		
		if(isset($_POST['commission_main']) && strlen($_POST['commission_main'])>0) {
			$commission_main = trim($_POST['commission_main']);
			if(is_numeric($commission_main) && $commission_main>=0 && $commission_main<=100){
				//ok
				$totalVal+=$commission_main;				
			} else {
				$error = 'Please enter a valid commission for main technician';
			}
		} else {
			$error = 'Please enter commission for main technician';
		}	
		
		foreach ($_POST as $field => $extraCommission) {
			if($field!='commission_main' && $field!= 'admin_commission' && $field!='submit'){
				//echo $field.'<br>';
				$fieldArr = explode('-', $field);
				if($fieldArr[1]!=''){
					$extraId = $fieldArr[1];
					if(is_numeric($extraCommission) && $extraCommission>=0 && $extraCommission<=100){
						//ok
						$totalVal+=$extraCommission;
						$extraIdArray[$extraId] = $extraCommission;
					} else {
						$error = 'Please enter valid commission for extra technicians';
					}
				}
			}
		}
		
		if($totalVal==100){
			//ok
		} else {
			$error = 'Total commission should be 100%';
		}
							
		if(empty($error)) {			
			$adminId = $_SESSION['adminId'];
			
			//print_r($extraIdArray);
			
			foreach ($extraIdArray as $techId => $value) {
				mysqli_query($con, "UPDATE tbl_job_extra_tech SET commission_percent = '".$value."' WHERE technician_id = '".$techId."' AND job_id = '".$taskId."'");
			}

			mysqli_query($con, "UPDATE tbl_job SET admin_commission_percent = '".$admin_commission."' WHERE id = '".$taskId."'");
			//if completed do the changes
			$chkRs = mysqli_query($con, "SELECT id FROM tbl_task_completed WHERE task_id = '".$taskId."'");
			if(mysqli_num_rows($chkRs)>0){
				$taskCompletedRs = mysqli_query($con, "SELECT id, tech_id, task_amount FROM tbl_task_completed WHERE task_id = '".$taskId."'");
					if(mysqli_num_rows($taskCompletedRs)>0){
						//change tech income, admin commission
						$totTaskRec = mysqli_fetch_array(mysqli_query($con, "SELECT SUM(task_amount) AS amount FROM tbl_task_completed WHERE task_id = '".$taskId."'"));
						if($fixedRate>0){
							$totalTaskAmount = $fixedRate;
						} else {
							$totalTaskAmount = $totTaskRec['amount'];
						}
						//$newTotalTaskAmount = $totalTaskAmount-$discount;
						$adminCommissionRec = mysqli_fetch_array(mysqli_query($con, "SELECT admin_commission_percent FROM tbl_job WHERE id = '".$taskId."'"));
						$adminCommission = $adminCommissionRec['admin_commission_percent'];
						while($taskCompletedRec = mysqli_fetch_array($taskCompletedRs)){
							$completeId = $taskCompletedRec['id'];
							$extaTechId = $taskCompletedRec['tech_id'];
							$completeTaskAmount = $taskCompletedRec['task_amount'];
							//find new task amount after deducting tech discount for this tech
							$taskPercent = ($completeTaskAmount*100)/$totalTaskAmount;
							if($taskPercent == 100){
								$completeTaskAmount = $completeTaskAmount-$totalDiscounts;
								$newAdminCommission = ($completeTaskAmount*$admin_commission)/100;		
								$newTechIncome = $completeTaskAmount-$newAdminCommission;					
							} else {
								$taskPercent = number_format((float)$taskPercent, 2, '.', '');
								if($totalDiscounts!=0){
									$techDiscount = ($totalDiscounts*$taskPercent)/100;
									$completeTaskAmount = $completeTaskAmount-$techDiscount;
								}								
								//$newTaskAmount = ($completeTaskAmount*$taskPercent)/100;
								$newAdminCommission = ($completeTaskAmount*$admin_commission)/100;	
								$newTechIncome = $completeTaskAmount-$newAdminCommission;		
							}							
							
							//update
							//echo "UPDATE tbl_task_completed SET tech_discount_amount = '0', admin_commission = '".$newAdminCommission."', tech_income = '".$newTechIncome."' WHERE id = '".$completeId."'";
							mysqli_query($con, "UPDATE tbl_task_completed SET tech_discount_amount = '0', admin_commission = '".$newAdminCommission."', tech_income = '".$newTechIncome."' WHERE id = '".$completeId."'");
							//update tbl_job_extra_tech also
							//mysqli_query($con, "UPDATE tbl_job_extra_tech SET commission = '".$newTaskAmount."' WHERE job_id = '".$editId."' AND technician_id = '".$extaTechId."'");		
							//exit;						
						}
					}

			}  else {
				//just update the task admin commission. it will change all tech charges on complete
				mysqli_query($con, "UPDATE tbl_job SET admin_commission_percent = '".$admin_commission."' WHERE id = '".$taskId."'");
				//if extra techs exists, change their commission
				if(isset($extraIdArray) && count($extraIdArray)>0){
					$extraTechsRs  = mysqli_query($con, "SELECT technician_id FROM tbl_job_extra_tech WHERE job_id = '".$taskId."'");
					if(mysqli_num_rows($extraTechsRs)>0){
						while($extraTechsRec = mysqli_fetch_array($extraTechsRs)){
							$extraTechid = $extraTechsRec['technician_id'];
							if(isset($extraIdArray[$extraTechid]) && $extraIdArray[$extraTechid]!=''){
								mysqli_query($con, "UPDATE tbl_job_extra_tech SET commission_percent = '".$extraIdArray[$extraTechid]."' WHERE job_id = '".$taskId."' AND technician_id = '".$extraTechid."'");
							}
						}
						
					}
				}			
			}
			
			header('Location:index.php?page=view_task&id='.$taskId.'&success=Updated the rates');
			exit();
			$success = 'Updated the rates';		
		} 
	}



	if(isset($_POST['submit_hourly'])) {
				
		if(isset($_POST['admin_commission']) && strlen($_POST['admin_commission'])>0) {
			$admin_commission = trim($_POST['admin_commission']);
			if(is_numeric($admin_commission) && $admin_commission>=0 && $admin_commission<=100){
				//ok						
			} else {
				$error = 'Please enter a valid commission';
			}
		} else {
			$error = 'Please enter commission';
		}
									
		if(empty($error)) {			
			$adminId = $_SESSION['adminId'];						
			
			//if completed do the changes
			$chkRs = mysqli_query($con, "SELECT id FROM tbl_task_completed WHERE task_id = '".$taskId."'");
			if(mysqli_num_rows($chkRs)>0){
				$taskCompletedRs = mysqli_query($con, "SELECT id, tech_id, task_amount FROM tbl_task_completed WHERE task_id = '".$taskId."'");
					if(mysqli_num_rows($taskCompletedRs)>0){
						//change tech income, admin commission
						$totTaskRec = mysqli_fetch_array(mysqli_query($con, "SELECT SUM(task_amount) AS amount FROM tbl_task_completed WHERE task_id = '".$taskId."'"));
						$totalTaskAmount = $totTaskRec['amount'];					
						
						$adminCommissionRec = mysqli_fetch_array(mysqli_query($con, "SELECT admin_commission_percent FROM tbl_job WHERE id = '".$taskId."'"));
						$adminCommission = $adminCommissionRec['admin_commission_percent'];
						
						while($taskCompletedRec = mysqli_fetch_array($taskCompletedRs)){
							$completeId = $taskCompletedRec['id'];
							$extaTechId = $taskCompletedRec['tech_id'];
							$completeTaskAmount = $taskCompletedRec['task_amount'];
							//find new task amount after deducting tech discount for this tech
							$taskPercent = ($completeTaskAmount*100)/$totalTaskAmount;
							if($taskPercent == 100){
								$completeTaskAmount = $completeTaskAmount-$totalDiscounts;
								$newAdminCommission = ($completeTaskAmount*$admin_commission)/100;		
								$newTechIncome = $completeTaskAmount-$newAdminCommission;					
							} else {
								$taskPercent = number_format((float)$taskPercent, 2, '.', '');
								if($totalDiscounts!=0){
									$techDiscount = ($totalDiscounts*$taskPercent)/100;
									$completeTaskAmount = $completeTaskAmount-$techDiscount;
								}								
								//$newTaskAmount = ($completeTaskAmount*$taskPercent)/100;
								$newAdminCommission = ($completeTaskAmount*$admin_commission)/100;	
								$newTechIncome = $completeTaskAmount-$newAdminCommission;		
							}							
							
							//update							
							mysqli_query($con, "UPDATE tbl_task_completed SET admin_commission = '".$newAdminCommission."', tech_income = '".$newTechIncome."' WHERE id = '".$completeId."'");
							
												
						}

						//if user paid for task chnage in income table and technician payments table
						$newIncomeRec = mysqli_fetch_array(mysqli_query($con, "SELECT SUM(admin_commission) AS admin_commission FROM tbl_task_completed WHERE task_id = '".$taskId."'"));
						$newIncome = $newIncomeRec['admin_commission'];
						//set 0 to all recs (if more than 1 rec exists) and set new income at the last record as we are taking the total income from task completed table
						mysqli_query($con, "UPDATE tbl_incomes SET amount = '0' WHERE task_id = '".$taskId."'");
						mysqli_query($con, "UPDATE tbl_incomes SET amount = '".$newIncome."' WHERE task_id = '".$taskId."' ORDER BY id DESC LIMIT 1");
						
						mysqli_query($con, "UPDATE tbl_technician_payments SET admin_fee = '0' WHERE job_id = '".$taskId."'");
						mysqli_query($con, "UPDATE tbl_technician_payments SET admin_fee = '".$newIncome."' WHERE job_id = '".$taskId."' ORDER BY id DESC LIMIT 1");
						
					}		
					mysqli_query($con, "UPDATE tbl_job SET admin_commission_percent = '".$admin_commission."' WHERE id = '".$taskId."'");
					
		
			} else {
				//just update the task admin commission. it will change all tech charges on complete
				mysqli_query($con, "UPDATE tbl_job SET admin_commission_percent = '".$admin_commission."' WHERE id = '".$taskId."'");			
			}		
			header('Location:index.php?page=view_task&id='.$taskId.'&success=Updated the rates');
			exit();
			$success = 'Updated the rates';		
		} 
	}








} else {
	header('Location:index.php?page=manage_user_tasks');
	exit();
}

?>