<?php include('techsyn_header.php');
?>
<!-- Main Content Container for side bar and body-->
<div class="main-container ace-save-state" id="main-container">
	<script type="text/javascript">
		try {
			ace.settings.loadState('main-container')
		} catch (e) {}
	</script>
	<?php include('techsyn_sidebar.php'); ?>
	<?php
	error_reporting(E_ERROR | E_PARSE);
	$id = ($_REQUEST['flex_opd_id'] != '' && $_REQUEST['flex_opd_id'] != null) ? $_POST['flex_opd_id'] : $_REQUEST['emp_id_history'];
	// echo $id;
	$query = "select * from patient_master where id = '" . $id . "' ";
	// echo $query;
	if (!$result = @mysqli_query($conn, $query)) {
		exit(mysqli_error($conn));
	} else {
		$row = @mysqli_fetch_array($result);
		@extract($row);
	}

	?>
	<div class="main-content">
		<div class="main-content-inner">
			<div class="breadcrumbs ace-save-state" id="breadcrumbs">
				<ul class="breadcrumb">
					<li><i class="ace-icon fa fa-home home-icon"></i> <a href="#">Home</a>
					</li>
					<li class="#">Patient Visit</li>
					<li class="active">Health Surveillance</li>
				</ul>
			</div>
			<div class="row" id="sickness_form_id">
				<div class="col-xs-12">
					<div class="widget-box">
						<div class="widget-body">
							<div class="widget-main">
								<div class="row">
									<div style="margin: 5px;">
										<div class="tabbable">
											<ul class="nav nav-tabs" id="myTab">
												<li class="active"><a data-toggle="tab" href="#appointment" aria-expanded="false"> Preventive Check-up Form <span class="badge badge-success">+</span>
													</a></li>

												<!-- <li><a href='#' class="blue" onclick="open_dashboard(<?=$patient_id?>)"><i class="ace-icon fa fa-user bigger-130"></i><?= $patient_name ?>'s Profile</a>
												</li> -->
												<li class=""><a data-toggle="tab" href="#history1" aria-expanded="false"> <input type="hidden" id="emp_id" name="emp_id" value="<?php echo ($_REQUEST['flex_opd_id'] != '' && $_REQUEST['flex_opd_id'] != null) ? $_POST['flex_opd_id'] : $_REQUEST['emp_id_history']; ?>">
														History <span class="badge badge-danger" id="history_record"><?php
																														$history_count = getTableFieldValue('checkup_form', 'count(*)', 'emp_id', ($_REQUEST['flex_opd_id'] != '' && $_REQUEST['flex_opd_id'] != null) ? $_POST['flex_opd_id'] : $_REQUEST['emp_id_history']);
																														if ($history_count == '' || $history_count == null)
																															$history_count = 0;
																														echo $history_count;
																														?></span>
													</a></li>
												<?php if (isset($_REQUEST['returnPage'])) { ?>
													<div class="dt-buttons btn-overlap btn-group" style="margin-left: 608px; margin-top: 2px">
														<a href="<?= $_REQUEST['returnPage'] . '&backButon=back' ?>" class="dt-button buttons-csv buttons-html5 btn btn-white btn-primary btn-bold save_button">Back</a>
													<?php  } ?>
													</div>
											</ul>
											<div class="tab-content">
												<div id="appointment" class="tab-pane fade in active ">
													<?php
													error_log("going into checkup_form");
													include('checkup_form.php'); ?>
												</div>

												<div id="history1" class="tab-pane fade">
													<?php
													error_log("entry into history");
													include('history_checkup.php'); ?>
												</div>
											</div>
										</div>
										<!--end tab table-->
									</div>
									<!--end of inner row-->
								</div>
								<!--end of widget-main -->
							</div>
							<!--end of inner widgetbody-->
						</div>
						<!--end of inner widgetbox-->
					</div>
					<!--end of xs-->
				</div>
				<!--end of inner widgetbody-->
			</div>
		</div>
		<!--end of outer col-xs-12">-->
	</div>
	<!--end of outer row-->
</div>
<form name="f1" method="post" id="flex_opd_id_medical" action="">
	<div id="flex1" style="width: 100%"></div>
	<input type="hidden" name="flex_opd_id" id="flex_opd_id" />
</form>

<script>
	function open_dashboard(emp_id) {
		if (emp_id != null && emp_id != '') {
			$("#flex_opd_id").val(emp_id);
			$("#flex_opd_id_medical").attr('target','_blank');
			$("#flex_opd_id_medical").attr('method', 'POST');
			$("#flex_opd_id_medical").attr('action', 'emp_dashboard.php');
			$("#flex_opd_id_medical").submit();

		}
	}
	<?php error_log("function start in checkup"); ?>

	function save() {
		//alert(" gfgdgdg");
		get_section_id();
		$.ajax({
			url: 'save_checkup_form.php',
			type: "POST",
			data: $("#checkup_form_employee").serialize(),
			success: function(data) {
				
				if (data.indexOf("FAILURE") != -1) {
					BootstrapDialog.alert('Error Saving Checkup Form :Select the checkup_section_ids.');
				} else {
					var checkId = JSON.parse(data);
					updateApp(checkId);
					if ($("#checkup_id").val() == "") {
						var history_record = $("#history_record").text();
						$('#history_record').text(parseInt(history_record) + 1);
					}
					$("#checkup_id").val(checkId);
					//$("#flex1").flexReload();
					BootstrapDialog.alert('Checkup Form Saved Successfully.');
					opens(checkId);
					<?php if ($_SESSION['RoleCode'] == 'RCP') {

						echo "location.replace('" . $_SESSION['role_home_page'] . "')";
					} ?>
				}
			},
			error: function(data) {
				BootstrapDialog.alert('Error Saving Checkup Form');
				return;
			}
		});
		//  $('.close').click();
	}
	var flex_checkup_id = "<?php echo $_REQUEST['flex_checkup_id']; ?>"
	if (flex_checkup_id != "" && flex_checkup_id != null)
		opens(flex_checkup_id);

	function opens(id) {
		$.ajax({
			url: 'select_checkup_form.php?id=' + id + '',
			type: 'POST',
			success: function(data) {
				//alert(data);
				if (data != null) {
					var data = $.parseJSON(data);
					//alert(data);
					myDateFormaterTime(data.parent.checkup_date);
					$("#checkup_id").val(data.parent.checkup_id);
					//$("#checkdown_date").val(myDateFormater(data.parent.checkup_date));
					var checkup_parameter_array = <?php echo json_encode($checkup_parameter_array) ?>;
					$("#remarks").val(data.parent.remarks);
					if (data.child != 'undefined' && data.child != '' && data.child != null)
						for (var i = 0; i < data.child.length; i++) {

							$("#" + data.child[i].checkup_form_key).val(data.child[i].checkup_form_value);
							$("#" + data.child[i].checkup_form_key).trigger('chosen:updated');
						}

					$("#checkup_type_id").val(data.parent.checkup_type_id);
					$('#checkup_type_id').trigger('chosen:updated');

					var element = document.getElementById('health_risk_name');
					var element1 = document.getElementById('health_advice_name');
					if (data.parent.health_advice_id != null && data.parent.health_advice_id != '') {
						var health_advice_name = data.parent.health_advice_id;
						if (health_advice_name.length > 0) {
							dataarray1 = health_advice_name.split(",");
							for (var i = 0; i < element1.options.length; i++) {
								element1.options[i].selected = dataarray1.indexOf(element1.options[i].value) >= 0;
							}
							$('#health_advice_name').trigger('chosen:updated');
						}
					}
					//$("#health_risk_name").val(data.health_risk_id);
					if (data.parent.health_risk_id != null && data.parent.health_risk_id != '') {
						var health_risk_name = data.parent.health_risk_id;
						if (health_risk_name.length > 0) {
							dataarray = health_risk_name.split(",");
							for (var i = 0; i < element.options.length; i++) {
								element.options[i].selected = dataarray.indexOf(element.options[i].value) >= 0;
							}
							$('#health_risk_name').trigger('chosen:updated');
						}
					}
				}
			},
			error: function(data) {
				BootstrapDialog.alert('Error Populating Checkup Form ');
				return;
			}
		});
	}
	/* $('#checkdown_date').datepicker({
						autoclose:true,
						format: 'dd/mm/yyyy',
					}).next().on(ace.click_event, function(){
						$(this).prev().focus();
					});*/
	function myDateFormaterTime(myDate) {
		$('#checkdown_date').datetimepicker({
			format: 'DD/MM/YYYY h:mm A', //use this option to display seconds
			defaultDate: new Date(myDate),
		});
	}

	var highlightedFields = "<?php echo getFieldFromTable("highlighted_fields", "medical_examination_highlighted", "medical_exam_id", $_REQUEST['flex_checkup_id']) ?>"


	console.log(highlightedFields);
	$(document).ready(function() {
		$("#hiddenHighlighter").val(highlightedFields);
		highlightedFields = highlightedFields.split(",")
		console.log(highlightedFields);
		// console.log("length"+highlighted_fieldslds.length);
		for (var i = 1; i < highlightedFields.length; i++) {
			console.log("values:" + highlightedFields[i]);
			ids = $("[name='" + highlightedFields[i] + "']");
			ids.css("borderColor", "tomato");
			ids.css("color", "red");

		}

	});

	function updateApp(id){
		$.ajax({
			url: 'update_book_app.php',
			data: {
                    id: id,
					emp_id:$('#checkup_emp_id').val(),
					app_type:'MED',
					checkdown_date:$('#checkdown_date').val(),
                },
         
			type: 'POST',
			success: function(data) {
				var checkId = JSON.parse(data);
				if(checkId!='' && checkId!=null){
					open_mail(checkId,'save');		
				}
			},
			error: function(data) {
				BootstrapDialog.alert('Error Populating Checkup Form ');
				return;
			}
		});
	
	}

	function open_mail(appointmentId,type) {
    
    

    $.ajax({
        url: 'select_app_data.php',
        type: "POST",
        data: {
            'cityId': appointmentId,
        },
        dataType: 'json',
        success: function(data) {
            var app_id = data.id;

            var link = ""+data.app_root+"/checkup_form_pdf.php?checkup_id=" + data.app_id;
            // var link = "" + app_root + "/opd_form_pdf.php?appointment_id_pdf=" + app_id;
            var emailContent = "";
            var status = '';
            var sub_status = '';
                sub_status = 'completed';
                status = "<font color=green>completed</font> ";
                data.app_type = 'Periodic Health Checkup';
            

            var email_list_to = data.emp_mail;
            var email_list_cc = data.doc_mail;
            // var app_root = '<?php echo getConfigKey('APP_ROOT') ?>';

            ref_type = "Appointments Booked";

            var subject = 'Your '+ data.app_type+' got ' + sub_status + ' in ' + data.ohc_type + ' OHC on ' + data
                .date + '.';
            emailContent +=
                "<p>Dear Sir/Madam,</p><p>Your " + data.app_type + " in " + data.ohc_type + " ohc got " +
                status +
                ".<br>Below are more details of your booking  </p><br><table class=`table-bordered` width=`100%`><thead><tr><th>Date</th><th>Time</th><th>Patient Name</th>";
                
                // emailContent +="<th>Doc Name</th>";

                emailContent +="<th> Appointment Type</th><th> status</th><th> Remarks</th></tr><thead><tbody>";
            emailContent += "<tr><td>" + data.date + "</td><td>" + data.slot + '-' + data.slot_end +
                "</td><td>" +
                data.patient_name +
                // "</td><td>" +
                // data.doctor_name +
                "</td><td>" + data.app_type +
                "</td><td>" + status +
                "</td><td>" + data.remarks + "</td></tr>";
            emailContent +=
                "</tbody></table>";
            emailContent += "<br><a href=" + link +
                ">More Details</a> ";

            emailContent += "<p> Regards,</p><p> Team OHC</p>";

            message = emailContent;


            var id = appointmentId;
            message = emailContent;

            send_email(ref_type, appointmentId, email_list_to, email_list_cc, subject,
                message,type);
        },
        error: function(data) {
            BootstrapDialog.alert('Error In Pulling Id');
            return id;
        }

    });
}

function send_email(ref_type, ref_identifier, email_list_to, email_list_cc, subject, message, type) {

    $.ajax({
        url: 'send_email.php',
        type: 'POST',
        data: {
            ref_type: ref_type,
            ref_identifier: ref_identifier,
            email_list_to: email_list_to,
            email_list_cc: email_list_cc,
            subject: subject,
            message: message,
        },
        success: function(data) {

            return;

        },
        error: function(data) {
            BootstrapDialog.alert('Error in sending mail');
            return;
        }
    });
    $('.close').click();
}


</script>
<?php
$header_visible =  getFieldFromTable('sec_choice','checkup_type','checkup_type_id',$checkup_type_id);
error_log("key value header visible: " . $header_visible);
if ($header_visible == "No") {
?>

<script>
	document.getElementById("checkup_section_header").style.display="none";
</script>

<?php
}

?>
<?php include('techsyn_footer.php'); ?>