<?php 
//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);
//error_reporting(E_ALL);
include_once 'db_functions.php'; 
$db = new DB_Functions(); 
$json = $_REQUEST["leaveJSON"];
///// remove special character
function cleanData($str) {
	$str = preg_replace("/\t/", "", $str); 
	$str = preg_replace("/\r?\n/", "", $str);
	$str = preg_replace("/\n/", "", $str);
	$str = preg_replace("/%0A/", "", $str);
	$str = preg_replace('/\s+/','',$str);
	if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"'; 
	return $str;
} 
///// find date difference /////
function daysDifference($endDate, $beginDate){
	$date_parts1=explode("-", $beginDate); $date_parts2=explode("-", $endDate);
	$start_date=gregoriantojd($date_parts1[1], $date_parts1[2], $date_parts1[0]);
	$end_date=gregoriantojd($date_parts2[1], $date_parts2[2], $date_parts2[0]);
	return $end_date - $start_date;
}
//////	
if (get_magic_quotes_gpc()){ 
	$json = stripslashes($json); 
}
//Decode JSON into an Array 
$data = json_decode($json); 
//print_r($data);
//Util arrays to create response JSON 
$response=array(); 
///// extract JSON
for($i = 0; $i < count($data) ; $i++) {
	$empid = $data[$i]->empid;
	$leave_type = $data[$i]->leave_type;
	$from_date = $data[$i]->from_date;
	$to_date = $data[$i]->to_date;
	$purpose = $data[$i]->purpose;
	$leave_description = cleanData($data[$i]->leave_description);
	$leave_duration = daysDifference($to_date, $from_date)+1;
	$sub_leave_type=$data[$i]->sub_leave_type;
		
	//Store Leave info into MySQL DB 
	$res = $db->addLeave($empid , $leave_type , $from_date , $to_date , $purpose , $leave_description, $leave_duration,$sub_leave_type);  
}
if($res==1){ 
	$response[] = array('status'=>'1','response'=>'Applied Successfully.');
}else{
	$response[] = array('status'=>'0','response'=>'Some Error Occurred.');
}

echo json_encode($response); 
?>