<?php
include ("connect.php");
	$leaveNo = $_POST["leaveNo"];
	$staffName = $_POST["staffName"];
	$leaveStartDate = $_POST["leaveStartDate"];
	$leaveEndDate = $_POST["leaveEndDate"];
	$leaveStartTime = $_POST["leaveStartTime"];
	$leaveEndTime = $_POST["leaveEndTime"];
	$leaveReason = $_POST["leaveReason"];
	
	$d1=strtotime($leaveEndDate);
	$d2=strtotime($leaveStartDate);
	$Days=round(($d1-$d2)/3600/24 + 1);
	
	$t1=strtotime($leaveEndTime);
	$t2=strtotime($leaveStartTime);
	$Times=round(($t1-$t2)/60/60);
	
	if($Times == 0){
	$totalLeave = $Days * 8;
	}else{
	$totalLeave = $Times;
	}
	
	if($_POST["Cancel"] == "Cancel")
{
	echo "<script language='javascript'>window.location='leavemain.php'</script>";
}else{

	$result1 = mysql_query("SELECT * FROM staff WHERE staffName = '$staffName'");
	
	$row1 = mysql_fetch_array($result1);
	
	$staffPayLeave = $row1['staffPayLeave'];
	$leaveBalance = $row1['leaveBalance'];
	
	$newleaveBalance = $leaveBalance - $totalLeave;
	if($newleaveBalance>0){
	$newleaveBalance2 = $newleaveBalance;
	$NPleave = 0;
	$payLeave = $totalLeave;
	}else{
	$NPleave = $totalLeave - $leaveBalance;
	$newleaveBalance2 = 0;
	$payLeave = $leaveBalance;
	}
	
	$result = mysql_query("INSERT INTO staffleave(leaveNo, staffName, leaveStartDate, leaveEndDate, leaveStartTime, leaveEndTime, leaveReason, payLeave, Nopayleave, totalLeave)
	VALUES
	('$leaveNo', '$staffName', '$leaveStartDate', '$leaveEndDate', '$leaveStartTime', '$leaveEndTime', '$leaveReason', '$payLeave', '$NPleave', '$totalLeave')");
	
	
	$result2 = mysql_query("UPDATE staff SET 
	leaveBalance = '$newleaveBalance2'
	WHERE staffName = '$staffName'");
	
	
	$db = mysql_close();
	echo "<script language='javascript'>alert('Your apply is under process.')</script>";
	echo "<script language='javascript'>window.location='leavemain.php'</script>";
}
?>