<?php
// error_reporting(E_ERROR | E_PARSE);
include('log_entry.php');
include('includes/config/config.php');
include('includes/functions.php');
// print_r($_POST);

error_log("Start Printing Request Attributes");
foreach ($_REQUEST as $key => $value) {
	error_log($key . " : " . $value . "<br />\r\n");
}
error_log("End Printing Request Attributes");

begin();

$id = $_POST['patient_id'];
$data['patient_id'] = $id;
$father_name = $_POST['father_name'];
$dob = $_POST['dob'];
$doj = $_POST['doj'];
$designation_id = $_POST['emp_designation'];
$dep_loc = $_POST['dep_loc'];

$grade_id = $_POST['emp_grade'];
$plant_id = $_POST['emp_plant'];

$pre_emp_cat_id = getTableFieldValue('patient_category', 'patient_cat_id', 'patient_cat_name', '"Pre Employment"');
if ($_POST['patient_category'] == $pre_emp_cat_id) {
	$emp_code = $_POST['temp_emp_code'];
} else {
	$emp_code = $_POST['emp_code'];
}
$emp_type_id = $_POST['emp_type_id'];
$bu_id = $_POST['bussiness_unit'];
$section_id = $_POST['section'];
$sub_section_id = $_POST['sub_section'];
$gender = $_POST['gender'];
// $address = $_POST['address'];
$primary_phone = $_POST['primary_phone'];
$personal_phone = $_POST['personal_phone'];
$email = $_POST['email'];
$aadhar_no = $_POST['aadhar_no'];
$ohc_type_id = $_POST['ohc_type_id'];
$identity = $_POST['identity'];
if (!isset($ohc_type_id)) {
	$ohc_type_id = $_SESSION['current_ohcttype'];
}
$status = $_POST['status'];
$blood_group = $_POST['blood_group'];
$manager_emp_id = $_POST['manager_emp_id'];
$offiial_email = $_POST['offiial_email'];
$has_first_aid = $_POST['has_first_aid'];
$hazardous_process = $_POST['hazardous_process'];
$dangerous_process = $_POST['dangerous_process'];
$raw_materials_exposed = $_POST['raw_materials_exposed'];
$is_ohc_staff = $_POST['is_ohc_staff'];
if (isset($known_health_advices)) {
	$known_health_advices = implode(',', $known_health_advices);
	$known_health_advices = $known_health_advices . ",";
	$known_health_advices = addslashes($known_health_advices);
	// $known_health_advices='ifNull(known_health_advices,)'addslashes($known_health_advices);
} else {
	$known_health_advices = "concat(known_health_advices,'')";
	// /echo $known_health_advices;
}
if ($known_health_risks != '') {
	$known_health_risks = implode(',', $known_health_risks);
	$known_health_risks = $known_health_risks . ",";
	$known_health_risks = addslashes($known_health_risks);
} else {
	$known_health_risks = "concat(known_health_risks,'')";
}
// echo $known_health_risks;
// echo $known_health_advices;
$imgData = null;
$photoQuery = "";

error_log(count($_FILES) . " COUNT OF FILES");

if (count($_FILES) > 0) {
	$file_name = $_FILES['emp_sign']['name'];
	$file_size = $_FILES['emp_sign']['size'];
	$file_tmp = $_FILES['emp_sign']['tmp_name'];
	$file_type = $_FILES['emp_sign']['type'];

	if ($_FILES['photo']['name'] !="") {
		$UploadFileName = "photo";
	}else{
		$UploadFileName = "photoDM";
	}


	$file_name_photo = $_FILES[$UploadFileName]['name'];
	$file_size_photo = $_FILES[$UploadFileName]['size'];
	$file_tmp_photo = $_FILES[$UploadFileName]['tmp_name'];
	$file_type_photo = $_FILES[$UploadFileName]['type'];





	$file_ext = strtolower(end(explode('.', $_FILES['emp_sign']['name'])));
	$file_ext_stamp = strtolower(end(explode('.', $file_name_photo)));



	$_FILES['emp_sign']['tmp_name'];
	$file_tmp_photo;


	if (is_uploaded_file($_FILES['emp_sign']['tmp_name']) || is_uploaded_file($file_tmp_photo)) {



		$info = pathinfo($_FILES['emp_sign']['name']);

		$info_photo = pathinfo($file_name_photo);




		$ext = pathinfo($info, PATHINFO_EXTENSION);

		$ext_photo = pathinfo($info_photo, PATHINFO_EXTENSION);




		$imgData = addslashes(file_get_contents($_FILES['emp_sign']['tmp_name']));

		$imgData_photo = addslashes(file_get_contents($file_tmp_photo));



		$imageProperties = getimageSize($_FILES['emp_sign']['tmp_name']);

		$imageProperties_photo = getimageSize($file_tmp_photo);


		$photoQuery = "emp_sign='{$imgData}'  ,image_type='{$imageProperties['mime']}',emp_photo='{$imgData_photo}'  ,emp_image_type='{$imageProperties_photo['mime']}',";

		error_log("PHOTO QUERY::" . $photoQuery);
	}
}

$data = array();
$initial_query = "";
$end_query = "";
$emp_id = "";
//optional parameters for Patient master. Which should not be changed unless there is a value being passed for them.
$optional_params = "";
if (isset($primary_contact_person)) {
	$optional_params .= ", primary_contact_person='" . addslashes($primary_contact_person) . "'";
}
if (isset($primary_contact_no)) {
	$optional_params .= ", primary_contact_no='" . addslashes($primary_contact_no) . "'";
}
if (isset($email)) {
	$optional_params .= ", email_id='" . addslashes($email) . "'";
}
if (isset($secondary_contact_person)) {
	$optional_params .= ", secondary_contact_person='" . addslashes($secondary_contact_person) . "'";
}
if (isset($secondary_contact_no)) {
	$optional_params .= ", secondary_contact_no='" . addslashes($secondary_contact_no) . "'";
}
if (isset($personal_phone)) {
	$optional_params .= ", personal_phone='" . addslashes($personal_phone) . "'";
}
if (isset($is_ohc_staff)) {
	$optional_params .= ", is_ohc_staff='" . addslashes($is_ohc_staff) . "'";
}
if (isset($has_first_aid)) {
	$optional_params .= ", is_first_aid='" . addslashes($has_first_aid) . "'";
}
if (isset($has_disabled)) {
	$optional_params .= ", is_disabled='" . addslashes($has_disabled) . "'";
}

if (isset($known_health_advices)) {
	$optional_params .= ", known_health_advices='" . addslashes($known_health_advices) . "'";
}
if (isset($known_health_risks)) {
	$optional_params .= ", known_health_risks='" . addslashes($known_health_risks) . "'";
}
if (isset($offiial_email)) {
	$optional_params .= ", offiial_email_id='" . addslashes($offiial_email) . "'";
}
if (isset($hazardous_process)) {
	$optional_params .= ", hazardous_process='" . addslashes($hazardous_process) . "'";
}
if (isset($dangerous_process)) {
	$optional_params .= ", dangerous_process='" . addslashes($dangerous_process) . "'";
}
if (isset($raw_materials_exposed)) {
	$optional_params .= ", raw_materials_exposed='" . addslashes($raw_materials_exposed) . "'";
}
if (isset($manager_emp_id)) {
	$optional_params .= ", emp_mgr_code='" . addslashes($manager_emp_id) . "'";
}
if (isset($blood_group)) {
	$optional_params .= ", blood_group='" . addslashes($blood_group) . "'";
}
// if(isset($_POST ['primary_phone'])){
// 	$optional_params.=", primary_phone='" . addslashes ($_POST ['primary_phone']) . "'";
// }
if (isset($status)) {
	$optional_params .= ", status='" . addslashes($status) . "'";
}
if (isset($primary_patient_id)) {
	$optional_params .= ", primary_patient_id='" . addslashes($primary_patient_id) . "'";
}
if (isset($primary_patient_id) && isset($relation_type)) {
	$optional_params .= ", relation_type='" . addslashes($relation_type) . "'";
}

if (isset($grade_id)) {
	$optional_params .= " , grade_id='" . addslashes($grade_id) . "' ";
}

if (isset($plant_id)) {
	$optional_params .= " , plant_id='" . addslashes($plant_id) . "' ";
}



$emp_code = trim($emp_code);
$aadhar_no = trim($aadhar_no);
/*
if (empty($id) &&( !empty($aadhar_no) ||  !empty($emp_code) )) {
	error_log("checking duplicate patient record");
	$row_existing = runSqlGenericSingleRow ("select id from patient_master where aadhar_no='$aadhar_no' or  emp_code='$emp_code'" );
	if ($row_existing != null) {
		error_log("checking duplicate patient record success");
		$id = $row_existing ['id'];
		$data ['patient_id'] = $id;
	}
}
*/
if (!empty($id)) {
	$initial_query = "update patient_master set " . $photoQuery . " ";
	$end_query = " where id = " . $id . " ";
} else {
	if (!empty($_POST['patient_name'])) {
		$initial_query = "insert into patient_master set " . $photoQuery . " ";
		$end_query = "";
	}
}
$final_query = $initial_query . "  patient_name='" . addslashes(trim($_POST['patient_name'])) . "', father_name = '" . addslashes(trim($father_name)) . "',
dob=STR_TO_DATE('" . $_POST['dob'] . "', '%d/%m/%Y'),  doj=STR_TO_DATE('" . $_POST['doj'] . "', '%d/%m/%Y'), designation_id='" . addslashes($designation_id) . "',
emp_code='" . addslashes($emp_code) . "', bu_id='" . $bu_id . "',dept_id='" . $_POST['dept'] . "',section_id='" . $section_id . "',sub_section_id='" . $sub_section_id . "' ,  emp_cat_id='" . $_POST['emp_cat'] . "' ,  emp_cadre='" . $_POST['emp_cadre'] . "', nature_of_job='" . $_POST['nature_job'] . "',
employer_contractor_id='" . $_POST['employer_contractor_id'] . "',	emp_sub_cat_id='" . $_POST['emp_sub_cat'] . "',patient_cat_id='" . $_POST['patient_category'] . "',deployment_location = '" . $_POST['dep_loc'] . "',
gender='$gender',aadhar_no='" . addslashes($aadhar_no) . "',ohc_type_id='" . addslashes($ohc_type_id) . "',identity='" . addslashes($identity) . "',
village='" . addslashes($_POST['village']) . "', post='" . addslashes($_POST['post']) . "', ps='" . addslashes($_POST['ps']) . "',
tehsil='" . addslashes($_POST['tehsil']) . "',district='" . addslashes($_POST['district']) . "', state='" . addslashes($_POST['state']) . "', primary_phone='" . addslashes($_POST['primary_phone']) . "',
pin_code='" . addslashes($_POST['pin_code']) . "', modified_by ='" . $_SESSION['user_id'] . "' " . $optional_params . $end_query;
// echo $final_query;




error_log("final query....." . $final_query);
if (!$result = @mysqli_query($conn, $final_query)) {
	$data['status'] = 500;
	error_log("Failed to Execute Final Query Insert/Update Exception:" . mysqli_error($conn) . " Query::: " . $final_query);
	rollback();
	die(mysqli_error($conn));
} else {
	$data['status'] = 200;
	if (empty($id)) {
		$id = @mysqli_insert_id($conn);
	}
	$data['patient_id'] = $id;
}
if (!empty($id)) {
	$rowCount = $_POST['rowCount'];
	$select_query_family_members = "select id from emp_family_members where emp_id=$id ";
	$result_family_members = @mysqli_query($conn, $select_query_family_members);
	$rows_family_members = @mysqli_num_rows($result_family_members);
	$members_id = array();
	$count = 0;
	while ($row_members = @mysqli_fetch_assoc($result_family_members)) {
		$members_id[$count] = $row_members['id'];
		$count++;
	}
	$query_initial = "";
	$query_end = "";
	for ($i = 0; $i < $rowCount; $i++) {
		if ($rows_family_members > 0) {
			if ($rows_family_members == $rowCount) {
				$query_initial = " update emp_family_members ";
				$query_end = " where id='$members_id[$i]'";
			} elseif ($rows_family_members < $rowCount) {
				if ($i < $rows_family_members) {
					$query_initial = " update emp_family_members ";
					$query_end = " where id='$members_id[$i]'";
				} else {
					$query_initial = " insert into emp_family_members";
					$query_end = "";
				}
			}
			// $query_family_members=$query_initial." set name='".addslashes($_POST['name'.$i])."' ,age='".addslashes($_POST['age'.$i])."', gender='".addslashes($_POST['gender'.$i])."', relation_type='".addslashes($_POST['relation_type'.$i])."',emp_id='$emp_id' ".$query_end;
			// echo $query_family_members;
			// @mysqli_query($conn,$query_family_members);
		} else {
			$query_initial = "insert into emp_family_members";
			// echo $query_initial;
		}
		// echo $i;
		error_log($_POST['dobb' . $i] . " DOB DM");
		$query_family_members = $query_initial . " set name='" . addslashes($_POST['name' . $i]) . "' ,dob=STR_TO_DATE('" . $_POST['dobb' . $i] . "', '%d/%m/%Y') ,gender='" . addslashes($_POST['gender' . $i]) . "', relation_type='" . addslashes($_POST['relation_type' . $i]) . "',active_status='" . addslashes($_POST['active_status' . $i]) . "',emp_id=$id " . $query_end;
		// echo $query_family_members;
		if (!@mysqli_query($conn, $query_family_members)) {
			error_log("Failed to Execute Family Member Insert/Update Query::: " . $query_family_members . " Exception:" . mysqli_error($conn));
			rollback();
			die(mysqli_error($conn));
		}

		error_log("STATUS:" . $query_family_members);
	}

	//Direct Insert from OHC Registration Desk for family members as Non-Employee Patients. Insert new record only if it doesnt already exist

	if (isset($primary_patient_id) && isset($relation_type) && $id != $primary_patient_id) {
		$rowDynamicMember = runSqlGenericSingleRow("select name from emp_family_members where upper(trim(name))=upper(trim('" . addslashes($_POST['patient_name']) . "')) ");
		if ($rowDynamicMember == null || !isset($rowDynamicMember['name'])) {
			$query_initial = "insert into emp_family_members";
			$query_family_members = $query_initial . " set name='" . addslashes($_POST['patient_name']) . "' ,age='" . ageCalculator($_POST['dob'])  . "', gender='" . addslashes($_POST['gender']) . "', relation_type='" . addslashes($_POST['relation_type']) . "',active_status='" . addslashes($_POST['active_status' . $i]) . "',emp_id=$primary_patient_id ";
			error_log($query_family_members . " emp_family_members");
			if (!@mysqli_query($conn, $query_family_members)) {
				error_log("Failed to Execute Dynamic add of Family Member Insert Query::: " . $query_family_members . " Exception:" . mysqli_error($conn));
				//rollback ();
				//die ( mysqli_error () );
			}
		}
	}



	$checkup_header_val = explode(',', $_POST['checkup_header_val']);
	for ($h = 0; $h < count($checkup_header_val); $h++) {
		$querowCount = $_POST['querowCount'];
		// echo $querowCount;
		$select_query_que = "select ans_id from questionnaire_ans where emp_id=$id AND  section_id=$checkup_header_val[$h] ";
		// echo $select_query_que;
		$result_que = @mysqli_query($conn, $select_query_que);
		$rows_que = @mysqli_num_rows($result_que);
		$ans_id = array();
		$count = 0;
		while ($row_questions = @mysqli_fetch_assoc($result_que)) {
			$ans_id[$count] = $row_questions['ans_id'];
			$count++;
		}
		$select_query_child_que = "select ans_id from questionnaire_ans where emp_id=$id AND  section_id is null ";
		// echo $select_query_child_que;
		$result_child_que = @mysqli_query($conn, $select_query_child_que);
		$rows_child_que = @mysqli_num_rows($result_child_que);
		$child_ans_id = array();
		$count_child = 0;
		while ($row_child_questions = @mysqli_fetch_assoc($result_child_que)) {
			$child_ans_id[$count_child] = $row_child_questions['ans_id'];
			$count_child++;
		}
		// print_r($child_ans_id);
		$query_initial = "";
		$query_end = "";
		for ($i = 0; $i < $querowCount; $i++) {
			$que_id = $_POST['que_id' . $i];
			$childQuesQuery = "select * from questionnaire where parentId = '$que_id'";
			// echo $i." ".$childQuesQuery."<br>";
			$childQueResult = @mysqli_query($conn, $childQuesQuery);
			$numQuesRows = @mysqli_num_rows($childQueResult);
			// echo $childQuesQuery." ".$numQuesRows."<br>";
			if ($numQuesRows != 0) {
				while ($rowChildQue = @mysqli_fetch_array($childQueResult)) {
					$childQueId = $rowChildQue['question_id'];
					// echo $childQueId."<br>";
					if ($rows_child_que > 0) {
						// echo $rows_child_que;
						if ($_POST[$childQueId . 'ans' . $i] == null or $_POST[$childQueId . 'ans' . $i] == "") {
							$query_child_delete = "DELETE FROM questionnaire_ans WHERE ans_id='$child_ans_id[0]';";
							// echo $query_child_delete;
							@mysqli_query($conn, $query_child_delete);
						} else {
							$query_child_initial = "update questionnaire_ans ";
							$query_child_end = "where ans_id='$child_ans_id[$i]'";
						}
						if ($i < $rows_que) {
							if ($_POST[$childQueId . 'ans' . $i] == null or $_POST[$childQueId . 'ans' . $i] == "") {
								$query_child_delete = "DELETE FROM questionnaire_ans WHERE ans_id='$child_ans_id[$i]';";
								// echo "<br>".$query_child_delete;
								@mysqli_query($conn, $query_child_delete);
							} else {
								$query_child_initial = "update questionnaire_ans ";
								$query_child_end = "where ans_id='$child_ans_id[$i]'";
							}
						} else {
							if ($_POST[$childQueId . 'ans' . $i] != null or $_POST[$childQueId . 'ans' . $i] != "") {
								$query_child_initial = "insert into questionnaire_ans";
								$query_child_end = "";
							}
						}
						// $query_family_members=$query_initial." set name='".addslashes($_POST['name'.$i])."' ,age='".addslashes($_POST['age'.$i])."', gender='".addslashes($_POST['gender'.$i])."', relation_type='".addslashes($_POST['relation_type'.$i])."',emp_id='$emp_id' ".$query_end;
						// echo $query_family_members;
						// @mysqli_query($conn,$query_family_members);
					} else {
						$query_child_initial = "insert into questionnaire_ans";
					}
					// echo $i;
					if ($_POST[$childQueId . 'ans' . $i] != null or $_POST[$childQueId . 'ans' . $i] != "") {
						$ans = $_POST[$childQueId . 'ans' . $i];
						$query_child_que = $query_child_initial . " set answer='$ans' ,que_id='" . addslashes($_POST[$childQueId . 'que_id' . $i]) . "' ,emp_id=$id , modified_by = '" . $_SESSION['user_id'] . "'" . $query_child_end;
						// echo $query_child_que . "<br>";
						@mysqli_query($conn, $query_child_que);
					}
				}
			}
			$que_id = $_POST['que_id' . $i];
			$QuesQuery = "select requiredDetailsIds from questionnaire where question_id = '$que_id'";
			// echo $i." ".$childQuesQuery."<br>";
			$QueResult = @mysqli_query($conn, $QuesQuery);
			$quesRows = @mysqli_fetch_array($QueResult);
			$ans = "";
			if ($_POST['ans' . $i] != null or $_POST['ans' . $i] != "") {
				$requiredDetails = $quesRows['requiredDetailsIds'];
				// echo $requiredDetails;
				$requiredDetailsArr = explode(",", $requiredDetails);
				$ans = $_POST['ans' . $i] . "";
				foreach ($requiredDetailsArr as $requiredDetailsIdsArrval) {
					$requiredDetailsArrval = getTableFieldValue('question_sub_details', 'sub_detail_name', 'sub_detail_id', $requiredDetailsIdsArrval);
					$ans = $ans . '' . $requiredDetailsArrval . "" . $_POST[$requiredDetailsArrval . $i];
				}
			}
			// echo "que row".$rows_que;
			if ($rows_que > 0) {
				if ($rows_que == $querowCount) {
					if ($_POST['ans' . $i] == null or $_POST['ans' . $i] == "") {
						$query_delete = "DELETE FROM questionnaire_ans WHERE ans_id='$ans_id[$i]' AND  section_id=$checkup_header_val[$h] ;";
						// echo $query_delete;
						@mysqli_query($conn, $query_delete);
					} else {
						$query_initial = "update questionnaire_ans  ";
						// echo $query_initial;
						$query_end = "where ans_id='$ans_id[$i]'";
					}
				} elseif ($rows_que < $querowCount) {
					if ($i < $rows_que) {
						if ($_POST['ans' . $i] == null or $_POST['ans' . $i] == "") {
							$query_delete = "DELETE FROM questionnaire_ans WHERE ans_id='$ans_id[$i]' AND  section_id=$checkup_header_val[$h];";
							// echo $query_delete;
							@mysqli_query($conn, $query_delete);
						} else {
							$query_initial = "update questionnaire_ans ";
							$query_end = "where ans_id='$ans_id[$i]' AND  section_id=$checkup_header_val[$h]";
						}
					} else {
						if ($_POST['ans' . $i] != null or $_POST['ans' . $i] != "") {
							$query_initial = "insert into questionnaire_ans";
							$query_initial;
							$query_end = "";
						}
					}
				}
				// $query_family_members=$query_initial." set name='".addslashes($_POST['name'.$i])."' ,age='".addslashes($_POST['age'.$i])."', gender='".addslashes($_POST['gender'.$i])."', relation_type='".addslashes($_POST['relation_type'.$i])."',emp_id='$emp_id' ".$query_end;
				// echo $query_family_members;
				// @mysqli_query($conn,$query_family_members);
			} else {
				$query_initial = "insert into questionnaire_ans";
				$query_initial;
			}
			// echo $i;
			if ($_POST['ans' . $i] != null or $_POST['ans' . $i] != "") {
				// $query_initial = "update questionnaire_ans ";
				// $query_end = "";
				$query_que = $query_initial . " set answer='$ans' ,que_id='" . addslashes($_POST['que_id' . $i]) . "' ,emp_id=$id , modified_by = '" . $_SESSION['user_id'] . "',section_id='" . $checkup_header_val[$h] . "' " . $query_end;
				// echo $query_que;
				@mysqli_query($conn, $query_que);
			}
		}
		$docsData = null;
		$docsQuery = "";
		if (count($_FILES) > 0) {
			$FileType = [
				'application/vnd.ms-excel',
				'text/xls',
				'text/xlsx',
				'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
			];
			$_FILES['userfile']['tmp_name'];
			/*
			 * if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
			 *
			 *
			 *
			 * $info = pathinfo($_FILES['userfile']['name']);
			 *
			 * $fileName = $_FILES['userfile']['name'];
			 *
			 * $position = strpos($fileName, ".");
			 *
			 *
			 *
			 * $fileextension = substr($fileName, $position + 1);
			 *
			 *
			 *
			 * $fileextension = strtolower($fileextension);
			 *
			 * /*
			 *
			 * $targetDir = "files/";
			 *
			 * $targetFilePath = $targetDir . $fileName;
			 *
			 */
			/*
			 * $ext = pathinfo($info, PATHINFO_EXTENSION);
			 *
			 * $docsData = addslashes(file_get_contents($_FILES['userfile']['tmp_name']));
			 *
			 * $docsProperties = getimageSize($_FILES['userfile']['tmp_name']);
			 *
			 * // if(move_uploaded_file($_FILES["userfile"]["tmp_name"], $targetFilePath)){
			 *
			 * $docsQuery = "insert into employee_docs set document='$docsData', doc_type='$fileextension', doc_name='$fileName', emp_id=$id ,modified_by='" . $_SESSION['user_id'] . "' ";
			 *
			 * @mysqli_query($conn,$docsQuery);
			 *
			 * // echo $docsQuery;
			 *
			 * // }
			 *
			 * }
			 */
			if (in_array($_FILES["userfile"]["type"], $FileType)) {
				$targetPath = 'excel/uploads/' . $_FILES['userfile']['name'];
				move_uploaded_file($_FILES['userfile']['tmp_name'], $targetPath);
				$Reader = new SpreadsheetReader($targetPath);
				$sheetCount = count($Reader->sheets());
				for ($i = 0; $i < $sheetCount; $i++) {
					$Reader->ChangeSheet($i);
					foreach ($Reader as $Row) {
						$question_name = "";
						if (isset($Row[0])) {
							$question_name = mysqli_real_escape_string($conn, $Row[0]);
						}
						$question_type = "";
						if (isset($Row[1])) {
							$question_type = mysqli_real_escape_string($conn, $Row[1]);
						}
						$question_section_id = "";
						if (isset($Row[2])) {
							$question_section_id = mysqli_real_escape_string($conn, $Row[2]);
						}
						if (!empty($question_name) || !empty($question_type) || !empty($question_section_id)) {
							$query = "insert into questionnaire(question_name,question_type,question_section_id) values('" . $question_name . "','" . $question_type . "','" . $question_section_id . "')";
							$result = mysqli_query($conn, $query);
							if (!empty($result)) {
								$type = "success";
								$message = "Excel Data Imported into the Database";
							} else {
								$type = "error";
								$message = "Problem in Importing Excel Data";
							}
						}
					}
				}
			}
			$_FILES['userfile']['tmp_name'];
			if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
				$info = pathinfo($_FILES['userfile']['name']);
				$fileName = $_POST['file_name'];
				$fileDesc = $_POST['file_desc'];
				$position = strpos($fileName, ".");
				$fileextension = substr($fileName, $position + 1);
				$fileextension = strtolower($fileextension);
				$file_type = $_FILES['userfile']['type'];
				/*
				 *
				 * $targetDir = "files/";
				 *
				 *
				 *
				 * $targetFilePath = $targetDir . $fileName;
				 *
				 */
				$ext = pathinfo($info, PATHINFO_EXTENSION);
				$docsData = addslashes(file_get_contents($_FILES['userfile']['tmp_name']));
				$docsProperties = getimageSize($_FILES['userfile']['tmp_name']);
				// if(move_uploaded_file($_FILES["userfile"]["tmp_name"], $targetFilePath)){
				$docsQuery = "insert into employee_docs set document='$docsData', doc_type='$file_type', doc_name='$fileName',doc_desc='$fileDesc' ,emp_id=$id ,modified_by='" . $_SESSION['user_id'] . "' ";
				error_log("DOCUMENT QUERY::" . $docsQuery);
				if (!@mysqli_query($conn, $docsQuery)) {
					error_log("Failed to insert document details. Query::: " . $docsQuery . " Exception:" . mysqli_error($conn));
					rollback();
					die(mysqli_error($conn));
				}
				// echo $docsQuery;
				// }
			}
		}


		$covid_test_counter = $_POST['vaccine_count_items'];
		error_log("Vaccination count:" . $covid_test_counter);
		$covid_test_dr = "";
		if ($covid_test_counter > 0) {
			error_log("saving vaccine details for emp_id:" . $id);

			// loop through covid test numbers
			for ($i = 0; $i < $covid_test_counter; $i++) {

				$vac_id = $_POST['vac_id' . $i];
				$vac_name = $_POST['vac_name' . $i];
				if ($vac_name == null || $vac_name == '') {
					error_log("invalid vaccine entry found at pos:" . $i . " name:" . $vac_name);
					continue;
				}
				error_log("processing vaccine entry found at pos:" . $i . " name:" . $vac_name);
				if ($_POST['dose1_' . $i] == '') {
					$dose1_result = '';
				} else {
					$dose1 = new DateTime($_POST['dose1_' . $i]);
					$dose1_result = $dose1->format('Y-m-d');
				}

				$vac_center1 = ($_POST['vac_center1_' . $i]);





				if ($_POST['dose2_' . $i] == '') {
					$dose2_result = '';
				} else {
					$dose2 = new DateTime($_POST['dose2_' . $i]);
					$dose2_result = $dose2->format('Y-m-d');
				}
				$vac_center2 = ($_POST['vac_center2_' . $i]);



				if ($_POST['dose3_' . $i] == '') {
					$dose3_result = '';
				} else {
					$dose3 = new DateTime($_POST['dose3_' . $i]);
					$dose3_result = $dose3->format('Y-m-d');
				}
				$vac_center3 = ($_POST['vac_center3_' . $i]);
				$in_q = '';
				$end_q = '';
				if ($vac_id == '' || $vac_id == null) {
					$in_q = 'insert into';
				} else {
					$in_q = 'update';
					$end_q = "where id='" . $vac_id . "'";
				}
				// error_log('dose1: '.$_POST['dose1_'.$i].' dose1 result '.$dose1_result);
				$remarks = $_POST['remarks_' . $i];
				$insert_vac_query = $in_q . "  vaccination_details set emp_id =$id , vac_id = '" . $vac_name . "', vac_d1 ='" . $dose1_result . "',vac_center1='" . $vac_center1 . "', vac_d2 ='" . $dose2_result . "',vac_center2='" . $vac_center2 . "', vac_d3 ='" . $dose3_result . "',vac_center3='" . $vac_center3 . "', remarks ='" . $remarks . "'" . $end_q;
				error_log("going to save vaccine details:" . $insert_vac_query);
				if (!@mysqli_query($conn, $insert_vac_query)) {
					error_log("Failed to insert vaccination data. Query::: " . $insert_vac_query . ". Exception:" . mysqli_error($conn));
					rollback();
					die(mysqli_error($conn));
				}
			}
		}

		$med_claim_counter = $_POST['med_count_items'];
		error_log("Medclaim count:" . $med_claim_counter);

		// $approved_buffer = $_POST ['approved_buffer' . $i];
		// error_log("counter i".$i);
		// error_log("approved_bufferrrrrrrrr".$approved_buffer);


		if ($med_claim_counter > 0) {
			error_log("saving medclaim details for emp_id:" . $id);

			mysqli_query($conn, "delete from mediclaim where emp_id=$id");


			for ($i = 0; $i < $med_claim_counter; $i++) {



				if ($_POST['approved_buffer' . $i] == null || $_POST['approved_buffer' . $i] == '') {
					error_log("invalid medclaim entry found at pos:" . $i . " name:" . $approved_buffer);
					continue;
				}
				error_log("processing medclaim entry found at pos:" . $i . " name:" . $approved_buffer);

				$remarks = $_POST['remarks' . $i];
				$insert_med_query = "insert into mediclaim set emp_id =$id , financial_year = '" . $_POST['fy' . $i] . "', mediclaim_limit ='" . $_POST['med_limit' . $i] . "', approved_buffer_limit ='" . $_POST['approved_buffer' . $i] . "', total_limit ='" . $_POST['total_limit' . $i] . "',utilized_amount='" . $_POST['utilized_amount' . $i] . "', balance = '" . $_POST['balance' . $i] . "',remarks ='" . $remarks . "'";
				error_log("going to save medclaim details:" . $insert_med_query);
				if (!@mysqli_query($conn, $insert_med_query)) {
					error_log("Failed to insert medclaim  data. Query::: " . $insert_med_query . ". Exception:" . mysqli_error($conn));
					rollback();
					die(mysqli_error($conn));
				}
			}
		}

		$npmed_claim_counter = $_POST['npmed_count_items'];
		error_log("Non-pay Medclaim count:" . $npmed_claim_counter);

		// $nputilized_amount = $_POST ['nputilized_amount' . $i];
		// error_log("counter i1".$i);
		// error_log("npamounttttttt".$nputilized_amount);

		if ($npmed_claim_counter > 0) {
			error_log("saving non-pay medclaim details for emp_id:" . $id);

			$sql_delete =  "delete from non_payable_mediclaim where emp_id=$id";
			mysqli_query($conn, $sql_delete);
			error_log("going to delete medclaim for non-payable mediclaim details:" . $sql_delete);


			for ($i = 0; $i < $npmed_claim_counter; $i++) {



				if ($_POST['nputilized_amount' . $i] == null || $_POST['nputilized_amount' . $i] == '') {
					error_log("invalid non-pay medclaim entry found at pos:" . $i . " name:" . $nputilized_amount);
					continue;
				}
				error_log("processing non-pay medclaim entry found at pos:" . $i . " name:" . $nputilized_amount);

				$remarks = $_POST['npremarks' . $i];
				$insert_med_query = "insert into non_payable_mediclaim set emp_id =$id , financial_year = '" . $_POST['npfy' . $i] . "',nonpay_med_limit ='" . $_POST['nonpay_med_limit' . $i] . "', utilized_amount='" . $_POST['nputilized_amount' . $i] . "', balance = '" . $_POST['npbalance' . $i] . "',remarks ='" . $remarks . "'";
				error_log("going to save non-pay medclaim details:" . $insert_med_query);
				if (!@mysqli_query($conn, $insert_med_query)) {
					error_log("Failed to insert non-pay medclaim  data. Query::: " . $insert_med_query . ". Exception:" . mysqli_error($conn));
					rollback();
					die(mysqli_error($conn));
				}
			}
		}

		$dismed_claim_counter = $_POST['dismed_count_items'];
		error_log("Medclaim count:" . $dismed_claim_counter);

		// $disutilized_amount = $_POST ['disutilized_amount' . $i];
		// error_log("counter i2".$i);
		// error_log("dis_amountttttttt".$disutilized_amount);

		if ($dismed_claim_counter > 0) {
			error_log("saving medclaim details for emp_id:" . $id);


			$sql_delete =  "delete from mediclaim_disease_not_covered where emp_id=$id";
			mysqli_query($conn, $sql_delete);
			error_log("going to save medclaim for disease not covered details:" . $sql_delete);



			for ($i = 0; $i < $dismed_claim_counter; $i++) {



				if ($_POST['disutilized_amount' . $i] == null || $_POST['disutilized_amount' . $i] == '') {
					error_log("invalid medclaim for disease not covered entry found at pos:" . $i . " name:" . $disutilized_amount);
					continue;
				}
				error_log("processing medclaim for disease not covered entry found at pos:" . $i . " name:" . $disutilized_amount);

				$remarks = $_POST['disremarks' . $i];
				$insert_med_query = "insert into mediclaim_disease_not_covered set emp_id =$id , financial_year = '" . $_POST['disfy' . $i] . "', nonpay_medclaim_limit ='" . $_POST['dismed_limit' . $i] . "', utilized_amount='" . $_POST['disutilized_amount' . $i] . "', balance = '" . $_POST['disbalance' . $i] . "',remarks ='" . $remarks . "'";
				error_log("going to save medclaim for disease not covered details:" . $insert_med_query);
				if (!@mysqli_query($conn, $insert_med_query)) {
					error_log("Failed to insert medclaim for disease not covered  data. Query::: " . $insert_med_query . ". Exception:" . mysqli_error($conn));
					rollback();
					die(mysqli_error($conn));
				}
			}
		}
	}
}

commit();
echo json_encode($data);