HEX
Server: nginx/1.24.0
System: Linux DGT-WORDPRESS-VM-SERVER 6.14.0-1017-azure #17~24.04.1-Ubuntu SMP Mon Dec 1 20:10:50 UTC 2025 x86_64
User: ubuntu (1000)
PHP: 8.4.12
Disabled: NONE
Upload Files
File: /mnt/data/doccure-wp/wp-content/themes/doccure/directory/front-end/ajax-hooks3.php
<?php

if (!function_exists('doccure_get_booking_data_new')) {

	function doccure_get_booking_data_new()
	{
		global $wpdb;
		$post_id = !empty($_POST['id']) ? intval($_POST['id']) : '';
		$doctor_id = !empty($_POST['doctor_id']) ? intval($_POST['doctor_id']) : '';
		$slot_id = !empty($_POST['slot_id']) ? intval($_POST['slot_id']) : '';
		$json = array();

		$table_name = $wpdb->prefix . "dc_schedule";
		$get_parent_doctor_id = $wpdb->get_var($wpdb->prepare(
			"SELECT parent_doctor_id FROM $table_name WHERE id = %d",
			$slot_id
		));

		if ($get_parent_doctor_id != '0') {
			$get_parent_doctor_id = $get_parent_doctor_id;
			$get_doctor_id = get_user_meta($get_parent_doctor_id, '_linked_profile', true);
		} else {

			$table_name = $wpdb->prefix . "dc_schedule";
			$doctor_user_id_new = $wpdb->get_var($wpdb->prepare(
				"SELECT doctor_id FROM $table_name WHERE id = %d",
				$slot_id
			));

			$get_doctor_id = $doctor_user_id_new;
		}


		if (function_exists('doccure_validate_user')) {
			doccure_validate_user();
		}
		; //if user is logged in

		//security check
		$do_check = check_ajax_referer('ajax_nonce', 'security', false);
		if ($do_check == false) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Security check failed, this could be because of your browser cache. Please clear the cache and check it againe', 'doccure');
			wp_send_json($json);
		}

		if (!empty($post_id)) {

			$json['consultant_fee'] = '';

			$doctor_user_id = get_post_field('post_author', $doctor_id);
			// $consultant_fee_get = get_user_meta($doctor_user_id, 'consultation_fee', true);
			//$consultant_fee =  doccure_price_format( $consultant_fee_get);


			$am_consultant_fee = get_user_meta($doctor_user_id, 'consultation_fee', true);
			$consultant_fee = !empty($am_consultant_fee) ? doccure_price_format($am_consultant_fee, 'return') : doccure_price_format(0, 'return');


			if (isset($consultant_fee)) {
				$json['consultant_fee'] = '<ul class="at-taxesfees"><li id="consultant_fee"><span>' . esc_html__('Consultation fee', 'doccure') . '<em>' . $consultant_fee . '<span class=" dc-consultant-fee dc-service-price" data-price="' . $am_consultant_fee . '" data-tipso="Verified user"></span></em></span></li><li class="at-toteltextfee"><span>' . esc_html__('Total', 'doccure') . '<em id="dc-total-price" data-price="' . $am_consultant_fee . '">' . $consultant_fee . '</em></span></li></ul>';
			}

			$service_html = '';
			$day = strtolower(date('D'));
			$date = date('Y-m-d');
			$reponse_slots = doccure_get_time_slots_spaces($post_id, $day, $date);
			$norecourd_found = apply_filters('doccure_empty_records_html', 'dc-empty-articls dc-emptyholder-sm', esc_html__('There are no any sloat available.', 'doccure'), true);
			$reponse_slots = !empty($reponse_slots) ? $reponse_slots : $norecourd_found;
			$json['time_slots'] = $reponse_slots;

			$service_html = apply_filters('doccure_get_group_services_with_speciality_new', $slot_id, '', 'return', 'location', $get_doctor_id);




			$json['type'] = 'success';
			$json['booking_services'] = $service_html;
			wp_send_json($json);
		} else {
			$json['type'] = 'error';
			$json['message'] = esc_html__('You need to select hospital.', 'doccure');
			wp_send_json($json);
		}
	}

	add_action('wp_ajax_doccure_get_booking_data_new', 'doccure_get_booking_data_new');
	add_action('wp_ajax_nopriv_doccure_get_booking_data_new', 'doccure_get_booking_data_new');
}

/**
 * Get Booking data

 */
if (!function_exists('doccure_get_slots')) {

	function doccure_get_slots()
	{
		$_date = !empty($_POST['_date']) ? ($_POST['_date']) : '';
		$_hospital_id = !empty($_POST['_hospital_id']) ? ($_POST['_hospital_id']) : '';
		$json = array();

		if (function_exists('doccure_validate_user')) {
			doccure_validate_user();
		}
		; //if user is logged in

		//security check
		$do_check = check_ajax_referer('ajax_nonce', 'security', false);
		if ($do_check == false) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Security check failed, this could be because of your browser cache. Please clear the cache and check it againe', 'doccure');
			wp_send_json($json);
		}

		if (!empty($_hospital_id)) {
			$json['type'] = 'success';
			$day = strtolower(date('D', strtotime($_date)));
			$reponse_slots = doccure_get_time_slots_spaces($_hospital_id, $day, $_date);

			$norecourd_found = apply_filters('doccure_empty_records_html', 'dc-empty-articls dc-emptyholder-sm', esc_html__('There are no any sloat available.', 'doccure'), true);
			$reponse_slots = !empty($reponse_slots) ? $reponse_slots : $norecourd_found;
			$json['time_slots'] = $reponse_slots;
			wp_send_json($json);
		} else {
			$json['type'] = 'error';
			$json['message'] = esc_html__('You need to select hospital.', 'doccure');
			wp_send_json($json);
		}
	}

	add_action('wp_ajax_doccure_get_slots', 'doccure_get_slots');
	add_action('wp_ajax_nopriv_doccure_get_slots', 'doccure_get_slots');
}




if (!function_exists('doccure_get_slots_new')) {

	function doccure_get_slots_new()
	{
		$_date = !empty($_POST['_date']) ? ($_POST['_date']) : '';
		$_hospital_id = !empty($_POST['_hospital_id']) ? ($_POST['_hospital_id']) : '';
		$slot_id = !empty($_POST['slot_id']) ? ($_POST['slot_id']) : '';
		$json = array();

		if (function_exists('doccure_validate_user')) {
			doccure_validate_user();
		}
		; //if user is logged in

		//security check
		$do_check = check_ajax_referer('ajax_nonce', 'security', false);
		if ($do_check == false) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Security check failed, this could be because of your browser cache. Please clear the cache and check it againe', 'doccure');
			wp_send_json($json);
		}
		//$clinic_name = get_the_title($_hospital_id); 
		if (!empty($_hospital_id)) {
			$json['type'] = 'success';
			$day = strtolower(date('D', strtotime($_date)));
			$reponse_slots = doccure_get_time_slots_spaces_new($_hospital_id, $day, $_date, $slot_id);

			$norecourd_found = apply_filters('doccure_empty_records_html', 'dc-empty-articls dc-emptyholder-sm', esc_html__('There are no any sloat available.', 'doccure'), true);
			$reponse_slots = !empty($reponse_slots) ? $reponse_slots : $norecourd_found;
			$json['time_slots'] = $reponse_slots;
			//$json['clinic_name']		= $clinic_name;
			wp_send_json($json);
		} else {
			$json['type'] = 'error';
			$json['message'] = esc_html__('You need to select hospital.', 'doccure');
			wp_send_json($json);
		}
	}

	add_action('wp_ajax_doccure_get_slots_new', 'doccure_get_slots_new');
	add_action('wp_ajax_nopriv_doccure_get_slots_new', 'doccure_get_slots_new');
}

// AJAX: Email + Password login for booking (regular_users only)
if (!function_exists('doccure_email_password_login')) {
	function doccure_email_password_login() {
		check_ajax_referer('ajax_nonce', 'security');

		$email    = !empty($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';
		$password = !empty($_POST['password']) ? $_POST['password'] : '';

		if (empty($email) || empty($password)) {
			wp_send_json_error(array(
				'message' => esc_html__('Email and password are required.', 'doccure'),
			));
		}

		$user = wp_authenticate($email, $password);

		if (is_wp_error($user)) {
			wp_send_json_error(array(
				'message' => esc_html__('Invalid email or password.', 'doccure'),
			));
		}

		// Only allow regular_users to login via this flow
		if (empty($user->roles) || !in_array('regular_users', (array) $user->roles, true)) {
			wp_send_json_error(array(
				'message' => esc_html__('Only regular users can book appointments with this form.', 'doccure'),
			));
		}

		// Log the user in
		wp_set_current_user($user->ID);
		wp_set_auth_cookie($user->ID, true);

		wp_send_json_success(array(
			'message' => esc_html__('Login successful. Reloading...', 'doccure'),
		));
	}

	add_action('wp_ajax_doccure_email_password_login', 'doccure_email_password_login');
	add_action('wp_ajax_nopriv_doccure_email_password_login', 'doccure_email_password_login');
}

if (!function_exists('doccure_booking_doctor_reschedule')) {

	function doccure_booking_doctor_reschedule()
	{
		global $doccure_options, $current_user, $wpdb;
		$user_id = !empty($_POST['user_id']) ? sanitize_text_field($_POST['user_id']) : '';
		$order_post_id = !empty($_POST['order_post_id']) ? sanitize_text_field($_POST['order_post_id']) : '';
		$post_user_id = doccure_get_linked_profile_id($current_user->ID);

		$is_verified = get_post_meta($post_user_id, '_is_verified', true);

		// if (function_exists('doccure_is_demo_site')) {
		// 	doccure_is_demo_site();
		// }
		// ; //if demo site then prevent

		if (function_exists('doccure_validate_user')) {
			doccure_validate_user();
		}
		; //if user is logged in

		if (empty($is_verified) || $is_verified === 'no') {
			$json['type'] = 'error';
			$json['message'] = esc_html__('You are not verified user, so you can\'t create a appointment', 'doccure');
			wp_send_json($json);
		}

		//security check
		$do_check = check_ajax_referer('ajax_nonce', 'security', false);
		if ($do_check == false) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Security check failed, this could be because of your browser cache. Please clear the cache and check it againe', 'doccure');
			wp_send_json($json);
		}

		$json = array();
		$post_meta = array();
		$date_formate = get_option('date_format');
		$time_format = get_option('time_format');
		$booking_hospitals = !empty($_POST['booking_hospitals']) ? sanitize_text_field($_POST['booking_hospitals']) : '';
		$doctor_id = !empty($_POST['id']) ? sanitize_text_field($_POST['id']) : '';
		$appointment_date = !empty($_POST['appointment_date']) ? sanitize_text_field($_POST['appointment_date']) : '';
		$booking_slot = !empty($_POST['booking_slot']) ? sanitize_text_field($_POST['booking_slot']) : '';

		$email = !empty($_POST['email']) ? is_email($_POST['email']) : '';
		$phone = !empty($_POST['phone']) ? ($_POST['phone']) : '';
		$first_name = !empty($_POST['first_name']) ? sanitize_text_field($_POST['first_name']) : '';
		$last_name = !empty($_POST['last_name']) ? sanitize_text_field($_POST['last_name']) : '';
		$total_price = !empty($_POST['total_price']) ? sanitize_text_field($_POST['total_price']) : 0;
		$doctor_id = doccure_get_linked_profile_id($current_user->ID);
		$rand_val = rand(1, 9999);

		$am_specialities = doccure_get_post_meta($doctor_id, 'am_specialities');
		$am_specialities = !empty($am_specialities) ? $am_specialities : array();




		$update_services = array();
		if (!empty($booking_service)) {

			foreach ($booking_service as $key => $service_single) {
				if (!empty($service_single)) {
					foreach ($service_single as $service) {
						$price = !empty($am_specialities[$key][$service]['price']) ? $am_specialities[$key][$service]['price'] : 0;
						$price = !empty($price) ? $price : 0;
						$update_services[$key][$service] = $price;
					}
				}
			}
		}




		if (!empty($booking_slot) && !empty($appointment_date)) {

			$booking_id = $order_post_id;

			if (!empty($booking_id)) {
				$am_booking_new = get_post_meta($booking_id, '_am_booking', true);


				$post_meta = maybe_unserialize($am_booking_new);

				$am_consultant_fee = get_post_meta($booking_hospitals, '_consultant_fee', true);
				$price = !empty($am_consultant_fee) ? $am_consultant_fee : 0;
				$post_meta['_consultant_fee'] = $price;
				$post_meta['_price'] = $total_price;
				$post_meta['_appointment_date'] = $appointment_date;
				$post_meta['_slots'] = $booking_slot;
				$post_meta['_hospital_id'] = $booking_hospitals;



				$order_id = get_post_meta($booking_id, '_order_id', true);
				if ($order_id) {
					$item_meta_key = 'cus_woo_product_data';

					$new_appointment_date = $appointment_date;
					$new_slots = $booking_slot;

					$order = wc_get_order($order_id);

					if ($order) {
						$items = $order->get_items();

						$item = reset($items);

						if ($item) {
							$meta_value = $item->get_meta($item_meta_key, true);
							$cus_woo_product_data = maybe_unserialize($meta_value);

							$cus_woo_product_data['appointment_date'] = $new_appointment_date;
							$cus_woo_product_data['slots'] = $new_slots;

							$updated_meta_value = maybe_serialize($cus_woo_product_data);

							$item->update_meta_data($item_meta_key, $updated_meta_value);
							$item->save();
						}
					}

				}

				update_post_meta($booking_id, '_appointment_date', $post_meta['_appointment_date']);
				update_post_meta($booking_id, '_price', $total_price);
				update_post_meta($booking_id, '_booking_slot', $post_meta['_slots']);
				$post_meta_new = maybe_unserialize($post_meta);
				update_post_meta($booking_id, '_am_booking', $post_meta_new);


				$time = !empty($post_meta['_slots']) ? explode('-', $post_meta['_slots']) : array();
				$start_time = !empty($time[0]) ? date($time_format, strtotime('2016-01-01' . $time[0])) : '';
				$end_time = !empty($time[1]) ? date($time_format, strtotime('2016-01-01' . $time[1])) : '';

				$appointment_time = $start_time . ' ' . esc_html__('to', 'doccure') . ' ' . $end_time;
				$tprice = doccure_price_format($post_meta['_price'], 'return');
				$consultant_fee = doccure_price_format($post_meta['_consultant_fee'], 'return');

				global $doccure_options;




				$role = $current_user->roles[0];

				$user_id = get_post_meta($booking_id, '_patient_id', true);
				$user_info = get_userdata($user_id);
				$user_name = $user_info->display_name;


				$doctor_id = get_post_meta($booking_id, '_doctor_id', true);
				$post = get_post($doctor_id);
				$author_id = $post->post_author;
				$doctor_info = get_userdata($author_id);
				$doctor_name = $doctor_info->display_name;



				if ($role == 'doctors') {
					$order_id = get_post_meta($booking_id, '_order_id', true);
					if ($order_id) {
						$bk_email = get_post_meta($booking_id, 'bk_email', true);
						$user_name = get_post_meta($booking_id, 'bk_username', true);

					} else {
						$bk_email = $user_info->user_email;
						$user_name = $user_info->display_name;
					}


					$is_enabled = $doccure_options['new_order_email_enabled_redoc'];
					$subject = $doccure_options['new_order_email_subject_redoc'];
					$email_content = $doccure_options['new_order_email_content_redoc'];

				} else {

					$order_id = get_post_meta($booking_id, '_order_id', true);
					if ($order_id) {
						$user_name = get_post_meta($booking_id, 'bk_username', true);

					} else {
						$user_name = $user_info->display_name;
					}


					$bk_email = $doctor_info->user_email;
					$is_enabled = $doccure_options['new_order_email_enabled_repat'];
					$subject = $doccure_options['new_order_email_subject_repat'];
					$email_content = $doccure_options['new_order_email_content_repat'];
				}


				$from_email = $doccure_options['emails_from_email'] ?? get_bloginfo('admin_email');
				$email_logo = $doccure_options['email_logo'];
				$email_logo_url = $email_logo['url'];

				// Check if the notification is enabled
				if (!$is_enabled) {
					return;
				}
				$product_details = ''; // Variable to hold all product details if multiple products are purchased

				// Build product details for each item in HTML table format with titles at the top
				$product_details .= '<table style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">';
				$product_details .= '<tr style="background-color: #f2f2f2;">';
				$product_details .= '<th>Patient Name</th>';
				$product_details .= '<th>Doctor Name</th>';
				$product_details .= '<th>Appointment Date</th>';
				$product_details .= '<th>Appointment Time</th>';
				$product_details .= '<th>Consultant Fee</th>';
				$product_details .= '<th>Total Price</th>';
				//$product_details .= '<th>Description</th>';
				$product_details .= '</tr>';
				// Loop through each order item to get metadata and product details
				$product_details .= '<tr>';
				$product_details .= '<td >' . esc_html($user_name) . '</td>';
				$product_details .= '<td >' . esc_html($doctor_name) . '</td>';
				$product_details .= '<td >' . esc_html($post_meta['_appointment_date']) . '</td>';
				$product_details .= '<td >' . esc_html($appointment_time) . '</td>';


				$product_details .= '<td >' . esc_html($consultant_fee) . '</td>';
				$product_details .= '<td >' . esc_html($tprice) . '</td>';
				//$product_details .= '<td >' . esc_html($post_meta['_slots']) . '</td>';
				$product_details .= '</tr>';


				$product_details .= '</table>';

				// Replace placeholders in the email content
				$replacements = array(
					'{patient_name}' => esc_html($user_name),
					'{doctor_name}' => esc_html($doctor_name),
					'{appointment_date}' => esc_html($post_meta['_appointment_date']),
					'{appointment_time}' => esc_html($appointment_time),
					'{consultant_fee}' => esc_html($consultant_fee),
					'{total_price}' => esc_html($tprice),
					//'{description}'    => esc_html($post_meta['_slots']),
					'{booking_details}' => $product_details // Insert the product details into the content
				);
				$email_content = strtr($email_content, $replacements);

				// Email headers for HTML format
				$headers = [
					'Content-Type: text/html; charset=UTF-8',
					'From: ' . get_bloginfo('name') . ' <' . $from_email . '>'
				];

				// Build the HTML message
				$message = '<!DOCTYPE html>
			<html>
			<head>
				<meta charset="UTF-8">
				<meta name="viewport" content="width=device-width, initial-scale=1.0">
				<style>
					body { font-family: Arial, sans-serif; color: #333; line-height: 1.6; }
					.container { max-width: 100%; margin: 0 auto; padding: 20px; background-color: #f9f9f9; border: 1px solid #ddd; }
					.header { text-align: center; margin-bottom: 30px; }
					.content { background: #fff; padding: 20px; border-radius: 5px; }
					.content ul{ padding-left: 0px; }
					.footer { margin-top: 30px; text-align: center; color: #999; font-size: 12px; }
					.content table th {padding: 8px; border: 1px solid #ddd;}
					.content  table td{padding: 8px; border: 1px solid #ddd;}
				</style>
			</head>
			<body>
				<div class="container">
					<div class="header">';
				if (!empty($email_logo_url)) {
					$message .= '<img src="' . esc_url($email_logo_url) . '" alt="Logo">';
				}
				$message .= '</div>
					<div class="content">'
					. $email_content .
					'</div>
					<div class="footer">
						&copy; ' . date("Y") . ' ' . get_bloginfo('name') . '. All rights reserved.
					</div>
				</div>
			</body>
			</html>';
				// Send the email to the customer
				send_password_reset_email($bk_email, $subject, $message, $headers);

			}

			$json['type'] = 'success';
			$json['message'] = esc_html__('Your booking has been successfully submitted.', 'doccure');
			wp_send_json($json);





		}


	}

	add_action('wp_ajax_doccure_booking_doctor_reschedule', 'doccure_booking_doctor_reschedule');
	add_action('wp_ajax_nopriv_doccure_booking_doctor_reschedule', 'doccure_booking_doctor_reschedule');
}

/**
 * Booking step 1

 */
if (!function_exists('doccure_booking_doctor')) {

	function doccure_booking_doctor()
	{
		global $doccure_options, $current_user, $wpdb;
		$user_id = !empty($_POST['user_id']) ? sanitize_text_field($_POST['user_id']) : '';
		$post_user_id = doccure_get_linked_profile_id($current_user->ID);

		$is_verified = get_post_meta($post_user_id, '_is_verified', true);

		if (function_exists('doccure_is_demo_site')) {
			doccure_is_demo_site();
		}
		; //if demo site then prevent

		if (function_exists('doccure_validate_user')) {
			doccure_validate_user();
		}
		; //if user is logged in

		if (empty($is_verified) || $is_verified === 'no') {
			$json['type'] = 'error';
			$json['message'] = esc_html__('You are not verified user, so you can\'t create a appointment', 'doccure');
			wp_send_json($json);
		}

		//security check
		$do_check = check_ajax_referer('ajax_nonce', 'security', false);
		if ($do_check == false) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Security check failed, this could be because of your browser cache. Please clear the cache and check it againe', 'doccure');
			wp_send_json($json);
		}

		$json = array();
		$required = array();
		$post_meta = array();
		$date_formate = get_option('date_format');
		$time_format = get_option('time_format');

		$required = array(
			'booking_hospitals' => esc_html__('Please select the hospital', 'doccure'),
			'booking_slot' => esc_html__('Please select the time slot', 'doccure'),
			'appointment_date' => esc_html__('Please select appointment date', 'doccure'),
			'email' => esc_html__('Email is required field', 'doccure')
		);

		$required = apply_filters('doccure_doccure_booking_doctor_validation', $required);

		if (empty($_POST['user_id'])) {
			$required['email'] = esc_html__('Email is required field', 'doccure');
			$required['first_name'] = esc_html__('First name is required field', 'doccure');
			$required['last_name'] = esc_html__('Last name is required field', 'doccure');
		}

		foreach ($required as $key => $req) {
			if (empty($_POST[$key])) {
				$json['type'] = 'error';
				$json['message'] = $req;
				wp_send_json($json);
			}
		}

		$booking_hospitals = !empty($_POST['booking_hospitals']) ? sanitize_text_field($_POST['booking_hospitals']) : '';
		$doctor_id = !empty($_POST['id']) ? sanitize_text_field($_POST['id']) : '';
		$appointment_date = !empty($_POST['appointment_date']) ? sanitize_text_field($_POST['appointment_date']) : '';
		$myself = !empty($_POST['myself']) ? sanitize_text_field($_POST['myself']) : '';
		$other_name = !empty($_POST['other_name']) ? sanitize_text_field($_POST['other_name']) : '';
		$relation = !empty($_POST['relation']) ? sanitize_text_field($_POST['relation']) : '';
		$booking_service = !empty($_POST['service']) ? ($_POST['service']) : array();
		$booking_content = !empty($_POST['booking_content']) ? sanitize_textarea_field($_POST['booking_content']) : '';
		$booking_slot = !empty($_POST['booking_slot']) ? sanitize_text_field($_POST['booking_slot']) : '';
		$create_user = !empty($_POST['create_user']) ? sanitize_text_field($_POST['create_user']) : '';

		$email = !empty($_POST['email']) ? is_email($_POST['email']) : '';
		$phone = !empty($_POST['phone']) ? ($_POST['phone']) : '';
		$first_name = !empty($_POST['first_name']) ? sanitize_text_field($_POST['first_name']) : '';
		$last_name = !empty($_POST['last_name']) ? sanitize_text_field($_POST['last_name']) : '';
		$total_price = !empty($_POST['total_price']) ? sanitize_text_field($_POST['total_price']) : 0;
		$doctor_id = doccure_get_linked_profile_id($current_user->ID);
		$rand_val = rand(1, 9999);

		$am_specialities = doccure_get_post_meta($doctor_id, 'am_specialities');
		$am_specialities = !empty($am_specialities) ? $am_specialities : array();

		$update_services = array();
		if (!empty($booking_service)) {

			foreach ($booking_service as $key => $service_single) {
				if (!empty($service_single)) {
					foreach ($service_single as $service) {
						$price = !empty($am_specialities[$key][$service]['price']) ? $am_specialities[$key][$service]['price'] : 0;
						$price = !empty($price) ? $price : 0;
						$update_services[$key][$service] = $price;
					}
				}
			}
		}


		if (!empty($booking_hospitals) && !empty($booking_slot) && !empty($appointment_date)) {

			if (!empty($user_id)) {
				$auther_id = $user_id;
			} else {
				$auther_id = 1;

				// For non-logged users: if an account already exists for this email,
				// use that user as the booking author for this request.
				if (!is_user_logged_in() && !empty($email)) {
					$existing_user = get_user_by('email', $email);
					if ($existing_user && !is_wp_error($existing_user)) {
						wp_set_current_user($existing_user->ID);
						$auther_id = $existing_user->ID;
					}
				}

				// If no existing user found for this email and create_user is requested,
				// create a new regular_users account as before.
				// if (!empty($create_user) && $auther_id === 1) {
				// 	$user_type = 'regular_users';
				// 	$random_password = rand(900, 10000);
				// 	$display_name = explode('@', $email);
				// 	$display_name = !empty($display_name[0]) ? $display_name[0] : $first_name;
				// 	$user_nicename = sanitize_title($display_name);
				// 	$userdata = array(
				// 		'user_login' => $display_name,
				// 		'user_pass' => $random_password,
				// 		'user_email' => $email,
				// 		'user_nicename' => $user_nicename,
				// 		'display_name' => $display_name
				// 	);

				// 	$user_identity = wp_insert_user($userdata);

				// 	if (is_wp_error($user_identity)) {
				// 		$json['type'] = "error";
				// 		$json['message'] = esc_html__("User already exists. Please try another one.", 'doccure');
				// 		wp_send_json($json);
				// 	} else {
				// 		wp_update_user(array('ID' => esc_sql($user_identity), 'role' => esc_sql($user_type), 'user_status' => 1));

				// 		$wpdb->update(
				// 			$wpdb->prefix . 'users',
				// 			array('user_status' => 1),
				// 			array('ID' => esc_sql($user_identity))
				// 		);

				// 		$auther_id = $user_identity;
				// 		update_user_meta($user_identity, 'first_name', $first_name);
				// 		update_user_meta($user_identity, 'last_name', $last_name);
				// 		update_user_meta($user_identity, 'phone', $phone);
				// 		update_user_meta($user_identity, '_is_verified', 'yes');
				// 		//update_user_meta( $user_identity, 'show_admin_bar_front', false);

				// 		//Create Post
				// 		$user_post = array(
				// 			'post_title' => wp_strip_all_tags($display_name),
				// 			'post_status' => 'publish',
				// 			'post_author' => $user_identity,
				// 			'post_type' => $user_type,
				// 		);

				// 		$post_id = wp_insert_post($user_post);

				// 		if (!is_wp_error($post_id)) {

				// 			$profile_data = array();
				// 			$profile_data['am_first_name'] = $first_name;
				// 			$profile_data['am_last_name'] = $last_name;
				// 			update_post_meta($post_id, 'am_' . $user_type . '_data', $profile_data);

				// 			//Update user linked profile
				// 			update_user_meta($user_identity, '_linked_profile', $post_id);
				// 			update_post_meta($post_id, '_is_verified', 'yes');
				// 			update_post_meta($post_id, '_linked_profile', $user_identity);
				// 			update_post_meta($post_id, 'is_featured', 0);

				// 			if (function_exists('doccure_full_name')) {
				// 				$name = doccure_full_name($post_id);
				// 			} else {
				// 				$name = $first_name;
				// 			}

				// 			$user_name = $name;
				// 			//Send email to users
				// 			if (class_exists('doccure_Email_helper')) {
				// 				$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
				// 				$emailData = array();

				// 				$emailData['name'] = $name;
				// 				$emailData['password'] = $random_password;
				// 				$emailData['email'] = $email;

				// 				$emailData['site'] = $blogname;
				// 				//Send code
				// 				if (class_exists('doccureRegisterNotify')) {
				// 					$email_helper = new doccureRegisterNotify();
				// 					if (!empty($user_type) && $user_type === 'regular_users') {
				// 						$email_helper->send_regular_user_email($emailData);
				// 					}
				// 				}

				// 				//Send admin email
				// 				if (class_exists('doccureRegisterNotify')) {
				// 					$email_helper = new doccureRegisterNotify();
				// 					$email_helper->send_admin_email($emailData);
				// 				}
				// 			}
				// 		}
				// 	}
				// }
			}

			$post_title = !empty($doccure_options['appointment_prefix']) ? $doccure_options['appointment_prefix'] : esc_html__('APP#', 'doccure');
			$contents = !empty($booking_content) ? $booking_content : '';
			$booking_post = array(
				'post_title' => wp_strip_all_tags($post_title) . '-' . $rand_val,
				'post_status' => 'publish',
				'post_author' => intval($auther_id),
				'post_type' => 'booking',
				'post_content' => $contents
			);

			$booking_id = wp_insert_post($booking_post);
			if (!empty($booking_id)) {
				$post_meta['_with_patient']['relation'] = !empty($relation) ? $relation : '';
				$post_meta['_with_patient']['other_name'] = !empty($other_name) ? $other_name : '';



				if (empty($user_id)) {

					update_post_meta($booking_id, 'bk_phone', $phone);
					update_post_meta($booking_id, 'bk_email', $email);
					update_post_meta($booking_id, 'bk_username', $first_name . ' ' . $last_name);
					if (!empty($create_user)) {
						update_post_meta($booking_id, '_user_type', 'regular_users');
					} else {
						update_post_meta($booking_id, '_user_type', 'guest');
						$user_name = !empty($first_name) ? $first_name . ' ' . $last_name : '';
						$post_meta['_user_details']['user_type'] = 'guest';
						$post_meta['_user_details']['full_name'] = $user_name;
						$post_meta['_user_details']['first_name'] = $first_name;
						$post_meta['_user_details']['last_name'] = $last_name;
						$post_meta['_user_details']['email'] = $email;
					}
				} else {
					$patient_profile_id = doccure_get_linked_profile_id($user_id);
					$name = doccure_full_name($patient_profile_id);
					$user_details = get_userdata($user_id);
					$phone = get_user_meta($user_id, 'phone', true);
					update_post_meta($booking_id, '_user_type', 'regular_users');

					update_post_meta($booking_id, 'bk_phone', $phone);
					update_post_meta($booking_id, 'bk_email', $user_details->user_email);
					update_post_meta($booking_id, 'bk_username', $name);
				}

				$am_consultant_fee = get_post_meta($booking_hospitals, '_consultant_fee', true);


				$price = !empty($am_consultant_fee) ? $am_consultant_fee : 0;

				$post_meta['_services'] = $update_services;
				$post_meta['_consultant_fee'] = $price;
				$post_meta['_price'] = $total_price;
				$post_meta['_appointment_date'] = $appointment_date;
				$post_meta['_slots'] = $booking_slot;
				$post_meta['_hospital_id'] = $booking_hospitals;

				//changes
				$hospital_id = $post_meta['_hospital_id'];

				update_post_meta($booking_id, '_order_id', $rand_val);

				update_post_meta($booking_id, '_appointment_date', $post_meta['_appointment_date']);
				update_post_meta($booking_id, '_booking_type', 'doctor');

				update_post_meta($booking_id, '_price', $total_price);
				update_post_meta($booking_id, '_booking_service', $post_meta['_services']);
				update_post_meta($booking_id, '_booking_slot', $post_meta['_slots']);
				update_post_meta($booking_id, '_booking_hospitals', $post_meta['_hospital_id']);
				update_post_meta($booking_id, '_hospital_id', $hospital_id);
				update_post_meta($booking_id, '_doctor_id', $doctor_id);
				//update_post_meta($booking_id,'_parentdoctor_id','132' );
				update_post_meta($booking_id, '_patient_id', $author_id);
				update_post_meta($booking_id, '_product_rand_offline', $rand_val);

				update_post_meta($booking_id, '_am_booking', $post_meta);

				if (function_exists('doccure_send_booking_message')) {
					doccure_send_booking_message($booking_id);
				}

				if (class_exists('doccure_Email_helper')) {
					$emailData = array();
					$emailData['user_name'] = $user_name;
					$time = !empty($post_meta['_slots']) ? explode('-', $post_meta['_slots']) : array();
					$start_time = !empty($time[0]) ? date($time_format, strtotime('2016-01-01' . $time[0])) : '';
					$end_time = !empty($time[1]) ? date($time_format, strtotime('2016-01-01' . $time[1])) : '';
					$hospital_id = get_post_meta($post_meta['_hospital_id'], 'hospital_id', true);

					$emailData['doctor_name'] = doccure_full_name($doctor_id);
					$emailData['doctor_link'] = get_the_permalink($doctor_id);
					$emailData['hospital_name'] = doccure_full_name($hospital_id);
					$emailData['hospital_link'] = get_the_permalink($hospital_id);

					$emailData['appointment_date'] = !empty($post_meta['_appointment_date']) ? date($date_formate, strtotime($post_meta['_appointment_date'])) : '';
					$emailData['appointment_time'] = $start_time . ' ' . esc_html__('to', 'doccure') . ' ' . $end_time;
					$emailData['price'] = doccure_price_format($total_price, 'return');
					$emailData['consultant_fee'] = doccure_price_format($post_meta['_consultant_fee'], 'return');
					$emailData['description'] = $contents;

					if (class_exists('doccureBookingNotify')) {
						$email_helper = new doccureBookingNotify();
						$emailData['email'] = $email;
						$email_helper->send_approved_email($emailData);
					}
				}
			}

			$json['type'] = 'success';
			$json['message'] = esc_html__('Your booking has been successfully submitted.', 'doccure');
			wp_send_json($json);
		}


	}

	add_action('wp_ajax_doccure_booking_doctor', 'doccure_booking_doctor');
	add_action('wp_ajax_nopriv_doccure_booking_doctor', 'doccure_booking_doctor');
}

/**
 * Booking step 1

 */
if (!function_exists('doccure_booking_step1')) {

	function doccure_booking_step1()
	{
		global $doccure_options;
		if (function_exists('doccure_is_demo_site')) {
			doccure_is_demo_site();
		}
		; //if demo site then prevent

		if (function_exists('doccure_validate_user')) {
			doccure_validate_user();
		}
		; //if user is logged in

		//security check
		$do_check = check_ajax_referer('ajax_nonce', 'security', false);
		if ($do_check == false) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Security check failed, this could be because of your browser cache. Please clear the cache and check it againe', 'doccure');
			wp_send_json($json);
		}

		if (!isset($_SESSION)) {
			session_start(array('user_data'));
		}

		$booking_verification = !empty($doccure_options['booking_verification']) ? $doccure_options['booking_verification'] : 'false';
		$json = array();
		$booking_hospitals = !empty($_POST['booking_hospitals']) ? sanitize_text_field($_POST['booking_hospitals']) : '';

		$get_hospital_name = !empty($_POST['get_hospital_name']) ? sanitize_text_field($_POST['get_hospital_name']) : '';



		$doctor_id = !empty($_POST['id']) ? sanitize_text_field($_POST['id']) : '';
		$parentdoctor_id = !empty($_POST['parentdoctor_id']) ? sanitize_text_field($_POST['parentdoctor_id']) : '';

		$appointment_date = !empty($_POST['appointment_date']) ? sanitize_text_field($_POST['appointment_date']) : '';
		$myself = !empty($_POST['myself']) ? sanitize_text_field($_POST['myself']) : '';
		$other_name = !empty($_POST['other_name']) ? sanitize_text_field($_POST['other_name']) : '';
		$relation = !empty($_POST['relation']) ? sanitize_text_field($_POST['relation']) : '';
		$booking_service = !empty($_POST['service']) ? ($_POST['service']) : array();
		$booking_content = !empty($_POST['booking_content']) ? sanitize_textarea_field($_POST['booking_content']) : '';
		$booking_slot = !empty($_POST['booking_slot']) ? sanitize_text_field($_POST['booking_slot']) : '';

		$bk_email = !empty($_POST['bk_email']) ? sanitize_text_field($_POST['bk_email']) : '';
		$bk_phone = !empty($_POST['bk_phone']) ? sanitize_text_field($_POST['bk_phone']) : '';
		//$slot_id			= !empty( $_POST['slot_id'] ) ? sanitize_text_field( $_POST['slot_id'] ) : '';
		// Insurance selection (Option 2): only ID and final discount are posted from JS
		$selected_insurance = !empty($_POST['selected_insurance']) ? intval($_POST['selected_insurance']) : 0;
		$insurance_discount = isset($_POST['insurance_discount']) ? floatval($_POST['insurance_discount']) : 0;

		if (empty($other_name)) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Patient name is required', 'doccure');
			wp_send_json($json);
		}

		if (empty($bk_email)) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Email address is required', 'doccure');
			wp_send_json($json);
		} elseif (!is_email($bk_email)) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Please add a valid email address', 'doccure');
			wp_send_json($json);
		}

		if (empty($bk_phone)) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Phone number is required', 'doccure');
			wp_send_json($json);
		} else {
			// Remove all non-digit characters
			$clean_phone = preg_replace('/[^0-9]/', '', $bk_phone);

			// Check if it's exactly 10 digits
		

		

			// Optional: Validate exchange code (digits 4-6) can't start with 0 or 1
			$exchange_code = substr($clean_phone, 3, 3);
			if ($exchange_code[0] < '2') {
				$json['type'] = 'error';
				$json['message'] = esc_html__('Please enter a valid phone number format', 'doccure');
				wp_send_json($json);
			}
		}

		if (empty($appointment_date)) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Please select the appointment date', 'doccure');
			wp_send_json($json);
		}

		if (empty($booking_hospitals)) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Please select the hospital', 'doccure');
			wp_send_json($json);
		}

		if (empty($booking_slot)) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Please select the time slot', 'doccure');
			wp_send_json($json);
		}

		if (empty($appointment_date)) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Please select the appointment date', 'doccure');
			wp_send_json($json);
		}

		if (!empty($booking_hospitals) && !empty($booking_slot) && !empty($appointment_date)) {
			$user_data = array();
			$user_data['booking']['post_title'] = get_the_title($booking_hospitals);
			$user_data['booking']['post_content'] = $booking_content;
			$user_data['booking']['_booking_service'] = $booking_service;
			$user_data['booking']['_booking_slot'] = $booking_slot;
			$user_data['booking']['_booking_hospitals'] = $booking_hospitals;
			$user_data['booking']['get_hospital_name'] = $get_hospital_name;

			$user_data['booking']['_appointment_date'] = $appointment_date;
			$user_data['booking']['_doctor_id'] = $doctor_id;
			$user_data['booking']['_parentdoctor_id'] = $parentdoctor_id;
			$user_data['booking']['_myself'] = $myself;

			$user_data['booking']['_relation'] = $relation;
			$user_data['booking']['bk_email'] = $bk_email;
			$user_data['booking']['bk_phone'] = $bk_phone;
			$user_data['booking']['other_name'] = $other_name;

			// Persist insurance info into session for doccure_booking_complete
			if ($selected_insurance && $insurance_discount > 0) {
				// Resolve company name from insurance taxonomy term
				$company_name = __('Insurance', 'doccure');
				$term = get_term($selected_insurance, 'insurance');
				if ($term && !is_wp_error($term)) {
					$company_name = $term->name;
				}
				// Store as a fixed-amount insurance; booking_complete will recompute
				$user_data['booking']['_has_insurance'] = true;
				$user_data['booking']['_insurance_details'] = array(
					'company_name' => $company_name,
					'type'         => 'fixed',
					'amount'       => $insurance_discount,
				);
				$user_data['booking']['_insurance_discount'] = $insurance_discount;
			} else {
				$user_data['booking']['_has_insurance']      = false;
				$user_data['booking']['_insurance_details']  = array();
				$user_data['booking']['_insurance_discount'] = 0;
			}

			$_SESSION['user_data'] = $user_data;

			//if( empty($booking_verification) ){
			doccure_booking_complete();
			//}

			$json['type'] = 'success';
			$json['message'] = esc_html__('Your booking is successfully submited.', 'doccure');
			wp_send_json($json);



		}


	}

	add_action('wp_ajax_doccure_booking_step1', 'doccure_booking_step1');
	add_action('wp_ajax_nopriv_doccure_booking_step1', 'doccure_booking_step1');
}

/**
 * Booking Resend Code

 */
if (!function_exists('doccure_booking_resend_code')) {

	function doccure_booking_resend_code()
	{
		global $current_user;

		if (function_exists('doccure_is_demo_site')) {
			doccure_is_demo_site();
		}
		; //if demo site then prevent

		if (function_exists('doccure_validate_user')) {
			doccure_validate_user();
		}
		; //if user is logged in

		//security check
		$do_check = check_ajax_referer('ajax_nonce', 'security', false);
		if ($do_check == false) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Security check failed, this could be because of your browser cache. Please clear the cache and check it againe', 'doccure');
			wp_send_json($json);
		}

		if (!isset($_SESSION)) {
			session_start(array('user_data'));
		}

		$json = array();

		if ($current_user->ID) {
			$key_hash = rand(1000, 9999);
			$json['email'] = $current_user->user_email;
			$json['type'] = 'success';
			$json['message'] = esc_html__('Verification code has sent on your email', 'doccure');
			$user_data = isset($_SESSION['user_data']) ? $_SESSION['user_data'] : array();
			$user_data['booking']['email'] = $current_user->user_email;
			$user_data['booking']['user_type'] = 'registered';
			$user_data['booking']['authentication_code'] = $key_hash;

			$_SESSION['user_data'] = $user_data;

			//update booking
			update_user_meta($current_user->ID, 'booking_auth', $key_hash);

			$profile_id = doccure_get_linked_profile_id($current_user->ID);
			$name = doccure_full_name($profile_id);
			$name = !empty($name) ? esc_html($name) : '';

			//Send verification code
			if (class_exists('doccure_Email_helper')) {
				if (class_exists('doccureBookingNotify')) {
					$email_helper = new doccureBookingNotify();
					$emailData['name'] = $name;
					$emailData['email'] = $current_user->user_email;
					$emailData['verification_code'] = $key_hash;
					$email_helper->send_verification($emailData);
				}
			}

			wp_send_json($json);
		}
	}

	add_action('wp_ajax_doccure_booking_resend_code', 'doccure_booking_resend_code');
	add_action('wp_ajax_nopriv_doccure_booking_resend_code', 'doccure_booking_resend_code');
}
/**
 * Booking step 2

 */
if (!function_exists('doccure_booking_step2')) {

	function doccure_booking_step2()
	{
		global $current_user;

		if (function_exists('doccure_validate_user')) {
			doccure_validate_user();
		}
		; //if user is logged in

		//security check
		$do_check = check_ajax_referer('ajax_nonce', 'security', false);
		if ($do_check == false) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Security check failed, this could be because of your browser cache. Please clear the cache and check it againe', 'doccure');
			wp_send_json($json);
		}

		if (function_exists('doccure_is_demo_site')) {
			doccure_is_demo_site();
		}
		; //if demo site then prevent

		if (!isset($_SESSION)) {
			session_start(array('user_data'));
		}

		$json = array();
		$key_hash = rand(1000, 9999);
		$emailData = array();
		$validations = array();

		if ($current_user->ID) {
			$password = !empty($_POST['password']) ? ($_POST['password']) : '';
			$retype_password = !empty($_POST['retype_password']) ? ($_POST['retype_password']) : '';

			$validations = array(
				'password' => esc_html__('Password is required.', 'doccure'),
				'retype_password' => esc_html__('Retype password is required.', 'doccure')
			);

			$validations = apply_filters('doccure_doccure_booking_step2_validation', $validations);

			foreach ($validations as $key => $val) {
				if (empty($_POST[$key])) {
					$json['type'] = 'error';
					$json['message'] = $val;
					wp_send_json($json);
				}
			}

			if ($password != $retype_password) {
				$json['type'] = 'error';
				$json['message'] = esc_html__('Password does not match.', 'doccure');
				wp_send_json($json);
			}

			$user_data = isset($_SESSION['user_data']) ? $_SESSION['user_data'] : array();

			if (!empty($password) && !empty($retype_password) && $password === $retype_password) {
				if (wp_check_password($password, $current_user->user_pass, $current_user->ID)) {

					$json['email'] = $current_user->user_email;
					$json['type'] = 'success';
					$json['message'] = esc_html__('Your informations are correct.', 'doccure');

					$user_data['booking']['email'] = $current_user->user_email;
					$user_data['booking']['user_type'] = 'registered';
					$user_data['booking']['authentication_code'] = $key_hash;

					$_SESSION['user_data'] = $user_data;

					//update booking
					update_user_meta($current_user->ID, 'booking_auth', $key_hash);

					$profile_id = doccure_get_linked_profile_id($current_user->ID);
					$name = doccure_full_name($profile_id);
					$name = !empty($name) ? esc_html($name) : '';

					//Send verification code
					if (class_exists('doccure_Email_helper')) {
						if (class_exists('doccureBookingNotify')) {
							$email_helper = new doccureBookingNotify();
							$emailData['name'] = $name;
							$emailData['email'] = $current_user->user_email;
							$emailData['verification_code'] = $key_hash;
							$email_helper->send_verification($emailData);
						}
					}

					wp_send_json($json);
				} else {
					$json['type'] = 'error';
					$json['message'] = esc_html__('Password is invalid.', 'doccure');
					wp_send_json($json);
				}
			}
		} else {
			$full_name = !empty($_POST['full_name']) ? ($_POST['full_name']) : '';
			$phone_number = !empty($_POST['phone_number']) ? ($_POST['phone_number']) : '';
			$email = !empty($_POST['email']) ? ($_POST['email']) : '';

			if (empty($full_name)) {
				$json['type'] = 'error';
				$json['message'] = esc_html__('Name is required.', 'doccure');
				wp_send_json($json);
			}

			if (empty($email)) {
				$json['type'] = 'error';
				$json['message'] = esc_html__('Email is required.', 'doccure');
				wp_send_json($json);
			}

			if (empty($phone_number)) {
				$json['type'] = 'error';
				$json['message'] = esc_html__('Phone number is required.', 'doccure');
				wp_send_json($json);
			}

			if (!empty($email) && !is_email($email)) {
				$json['type'] = 'error';
				$json['message'] = esc_html__('Email is invalid.', 'doccure');
				wp_send_json($json);
			}

			if (!empty($email) && !empty($full_name) && is_email($email) && !empty($phone_number)) {

				$user_data['booking']['email'] = $email;
				$user_data['booking']['user_type'] = 'guest';
				$user_data['booking']['full_name'] = $full_name;
				$user_data['booking']['phone_number'] = $phone_number;
				$user_data['booking']['authentication_code'] = $key_hash;
				$_SESSION['user_data'] = $user_data;

				//update booking
				update_user_meta($current_user->ID, 'booking_auth', $key_hash);

				$json['email'] = $email;

				//Send verification code
				if (class_exists('doccure_Email_helper')) {
					if (class_exists('doccureBookingNotify')) {
						$email_helper = new doccureBookingNotify();
						$emailData['name'] = $full_name;
						$emailData['email'] = $email;
						$emailData['verification_code'] = $key_hash;
						$email_helper->send_verification($emailData);
					}
				}

				$json['type'] = 'success';
				$json['message'] = esc_html__('Your informations are correct.', 'doccure');

				wp_send_json($json);
			}
		}
	}

	add_action('wp_ajax_doccure_booking_step2', 'doccure_booking_step2');
	add_action('wp_ajax_nopriv_doccure_booking_step2', 'doccure_booking_step2');
}

/**
 * Booking step 3

 */
if (!function_exists('doccure_booking_step3')) {

	function doccure_booking_step3()
	{
		global $woocommerce, $doccure_options, $current_user;
		if (function_exists('doccure_is_demo_site')) {
			doccure_is_demo_site();
		} //if demo site then prevent

		if (function_exists('doccure_validate_user')) {
			doccure_validate_user();
		}
		; //if user is logged in

		//security check
		$do_check = check_ajax_referer('ajax_nonce', 'security', false);
		if ($do_check == false) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Security check failed, this could be because of your browser cache. Please clear the cache and check it againe', 'doccure');
			wp_send_json($json);
		}

		$json = array();
		$date_formate = get_option('date_format');
		$time_format = get_option('time_format');
		$code = !empty($_POST['authentication_code']) ? ($_POST['authentication_code']) : '';

		if (!isset($_SESSION)) {
			session_start(array('user_data'));
		}

		$user_data = isset($_SESSION['user_data']) ? $_SESSION['user_data'] : array();

		if (empty($code)) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Please enter authentication code.', 'doccure');
			wp_send_json($json);
		} else {
			if (isset($user_data['booking']['authentication_code'])) {

				if (trim($user_data['booking']['authentication_code']) === trim($code)) {
					doccure_booking_complete();
				} else {
					$json['type'] = 'error';
					$json['message'] = esc_html__("Authentication code is incorrect.", 'doccure');
					wp_send_json($json);
				}
			} else {
				$json['type'] = 'error';
				$json['message'] = esc_html__("Oops! ", 'doccure');
				wp_send_json($json);
			}
		}
	}

	add_action('wp_ajax_doccure_booking_step3', 'doccure_booking_step3');
	add_action('wp_ajax_nopriv_doccure_booking_step3', 'doccure_booking_step3');
}



/**
 * Update booking status

 */
if (!function_exists('doccure_update_booking_status')) {

	function doccure_update_booking_status()
	{
		global $current_user;
		$post_id = !empty($_POST['id']) ? ($_POST['id']) : '';
		$status = !empty($_POST['status']) ? ($_POST['status']) : '';
		$offline_package = doccure_theme_option('payment_type');
		$time_format = get_option('time_format');
		$json = array();
		$update_post = array();

		if (function_exists('doccure_is_demo_site')) {
			doccure_is_demo_site();
		}
		; //if demo site then prevent

		if (function_exists('doccure_validate_user')) {
			doccure_validate_user();
		}
		; //if user is logged in

		$doctor_id = get_post_meta($post_id, '_doctor_id', true);
		$doctor_user_id = doccure_get_linked_profile_id($doctor_id, 'post');

		if (isset($doctor_user_id) && intval($doctor_user_id) !== $current_user->ID) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('You are not authorized to update the details', 'doccure');
			wp_send_json($json);
		}

		//security check
		$do_check = check_ajax_referer('ajax_nonce', 'security', false);
		if ($do_check == false) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Security check failed, this could be because of your browser cache. Please clear the cache and check it againe', 'doccure');
			wp_send_json($json);
		}


		if (empty($status)) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Post status is required.', 'doccure');
			wp_send_json($json);
		}

		if (empty($post_id)) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Post ID is required.', 'doccure');
			wp_send_json($json);
		}

		if (!empty($post_id) && !empty($status)) {
			// for offline 
			if (!empty($offline_package) && $offline_package === 'offline') {
				$order_id = get_post_meta($post_id, '_order_id', true);
				if (!empty($order_id) && class_exists('WC_Order')) {
					$order = new WC_Order($order_id);

					if (!empty($order)) {
						if ($status === 'publish') {
							$order->update_status('completed');
							$order->save();
						} else if ($status === 'cancelled') {
							$order->update_status('cancelled');
							$order->save();
						}
					}
				}
			}


			$update_post['ID'] = $post_id;
			$update_post['post_status'] = $status;

			// Update the post into the database
			wp_update_post($update_post);

			do_action('doccure_after_order_meta_update_offline', $post_id);


			$appointment_date = get_post_meta($post_id, '_appointment_date', true);
			$appointment_date = !empty($appointment_date) ? $appointment_date : '';

			$booking_slot = get_post_meta($post_id, '_booking_slot', true);
			$booking_slot = !empty($booking_slot) ? $booking_slot : array();

			$slot_key_val = explode('-', $booking_slot);
			$start_time = date($time_format, strtotime('2016-01-01' . $slot_key_val[0]));
			$end_time = date($time_format, strtotime('2016-01-01' . $slot_key_val[1]));

			$start_time = !empty($start_time) ? $start_time : '';
			$end_time = !empty($end_time) ? $end_time : '';

			$booking_hospitals = get_post_meta($post_id, '_booking_hospitals', true);
			$hospital_id = get_post_meta($booking_hospitals, 'hospital_id', true);
			$hospital_name = doccure_full_name($hospital_id);
			$hospital_name = !empty($hospital_name) ? $hospital_name : '';
			$doctor_id = get_post_meta($post_id, '_doctor_id', true);
			$doctor_id = !empty($doctor_id) ? $doctor_id : '';
			$doctor_name = doccure_full_name($doctor_id);
			$doctor_name = !empty($doctor_name) ? $doctor_name : '';
			$author_id = get_post_field('post_author', $post_id);
			$user_profile_id = doccure_get_linked_profile_id($author_id);
			$user_info = get_userdata($author_id);

			if (!empty($user_info)) {
				$emailData['email'] = $user_info->user_email;
				$emailData['user_name'] = doccure_full_name($user_profile_id);
			}

			$am_booking_new = get_post_meta($post_id, '_am_booking', true);
			$post_meta = maybe_unserialize($am_booking_new);
			$consultant_fee = $post_meta['_consultant_fee'];
			$total_price = $post_meta['_price'];

			$emailData['doctor_name'] = $doctor_name;
			$emailData['doctor_link'] = get_the_permalink($doctor_id);
			$emailData['hospital_link'] = get_the_permalink($hospital_id);
			$emailData['hospital_name'] = $hospital_name;
			$emailData['description'] = get_the_content($post_id);
			$emailData['appointment_date'] = $appointment_date;
			$emailData['appointment_time'] = $start_time . ' ' . esc_html__('to', 'doccure') . ' ' . $end_time;

			$emailData['price'] = doccure_price_format($total_price, 'return');
			$emailData['consultant_fee'] = doccure_price_format($consultant_fee, 'return');

			if (class_exists('doccure_Email_helper')) {
				if (class_exists('doccureBookingNotify')) {
					$email_helper = new doccureBookingNotify();
					if ($status === 'publish') {
						$email_helper->send_approved_email($emailData);
						if (function_exists('doccure_send_booking_message')) {
							doccure_send_booking_message($post_id);
						}
					} else if ($status === 'cancelled') {
						$email_helper->send_cancelled_email($emailData);
					}
				}
			}

			$json['type'] = 'success';
			$json['message'] = esc_html__('Booking status has been updated.', 'doccure');
		}


		wp_send_json($json);
	}

	add_action('wp_ajax_doccure_update_booking_status', 'doccure_update_booking_status');
	add_action('wp_ajax_nopriv_doccure_update_booking_status', 'doccure_update_booking_status');
}

/**
 * Update booking status

 */
if (!function_exists('doccure_send_message')) {

	function doccure_send_message()
	{
		global $current_user;
		$booking_id = !empty($_POST['id']) ? ($_POST['id']) : '';
		$message = !empty($_POST['msg']) ? ($_POST['msg']) : '';

		$post_author = get_post($booking_id);
		$post_author_id = !empty($post_author->post_author) ? intval($post_author->post_author) : 0;

		if (function_exists('doccure_is_demo_site')) {
			doccure_is_demo_site();
		}
		; //if demo site then prevent


		if (function_exists('doccure_validate_user')) {
			doccure_validate_user();
		}
		; //if user is logged in

		//security check
		$do_check = check_ajax_referer('ajax_nonce', 'security', false);
		if ($do_check == false) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Security check failed, this could be because of your browser cache. Please clear the cache and check it againe', 'doccure');
			wp_send_json($json);
		}

		$doctor_id = get_post_meta($booking_id, '_doctor_id', true);
		$doctor_user_id = doccure_get_linked_profile_id($doctor_id, 'post');

		$doctor_user_id = !empty($doctor_user_id) ? intval($doctor_user_id) : 0;
		$current_user_id = !empty($current_user->ID) ? intval($current_user->ID) : 0;
		$allowed_id = array($doctor_user_id, $post_author_id);

		if (
			!empty($doctor_user_id)
			&& !empty($post_author_id)
			&& (!in_array($current_user_id, $allowed_id))
		) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('You are not authorized to update the details', 'doccure');
			wp_send_json($json);
		}

		if (!empty($message) && !empty($booking_id)) {
			if (function_exists('doccure_send_booking_message')) {
				$active_id = doccure_send_booking_message($booking_id, $message);
				$json['url'] = doccure_Profile_Menu::doccure_profile_menu_link('chat', $current_user->ID, true, 'settings', $active_id);
				$json['type'] = 'success';
				$json['message'] = esc_html__('Message send successfuly.', 'doccure');

				wp_send_json($json);
			}
		}
	}

	add_action('wp_ajax_doccure_send_message', 'doccure_send_message');
	add_action('wp_ajax_nopriv_doccure_send_message', 'doccure_send_message');
}

/**
 * Update Payrols

 */
if (!function_exists('doccure_payrols_settings')) {

	function doccure_payrols_settings()
	{
		global $current_user;
		$user_identity = $current_user->ID;
		$json = array();
		$data = array();
		$payrols = doccure_get_payouts_lists();
		$fields = !empty($payrols[$_POST['payout_settings']['type']]['fields']) ? $payrols[$_POST['payout_settings']['type']]['fields'] : array();

		if (function_exists('doccure_is_demo_site')) {
			doccure_is_demo_site();
		}

		if (function_exists('doccure_validate_user')) {
			doccure_validate_user();
		}
		; //if user is logged in

		//security check
		$do_check = check_ajax_referer('ajax_nonce', 'security', false);
		if ($do_check == false) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Security check failed, this could be because of your browser cache. Please clear the cache and check it againe', 'doccure');
			wp_send_json($json);
		}

		if (!empty($fields)) {
			foreach ($fields as $key => $field) {
				if ($field['required'] === true && empty($_POST['payout_settings'][$key])) {
					$json['type'] = 'error';
					$json['message'] = $field['message'];
					wp_send_json($json);
				}
			}
		}

		update_user_meta($user_identity, 'payrols', $_POST['payout_settings']);
		$json['url'] = doccure_Profile_Menu::doccure_profile_menu_link('payouts', $user_identity, true, 'settings');
		$json['type'] = 'success';
		$json['message'] = esc_html__('Payout settings have been updated.', 'doccure');

		wp_send_json($json);
	}

	add_action('wp_ajax_doccure_payrols_settings', 'doccure_payrols_settings');
	add_action('wp_ajax_nopriv_doccure_payrols_settings', 'doccure_payrols_settings');
}

/**
 * Remove Payrols settings

 */
if (!function_exists('doccure_payrols_remove_settings')) {

	function doccure_payrols_remove_settings()
	{
		global $current_user;
		$user_identity = $current_user->ID;

		if (function_exists('doccure_validate_user')) {
			doccure_validate_user();
		}
		; //if user is logged in

		//security check
		$do_check = check_ajax_referer('ajax_nonce', 'security', false);
		if ($do_check == false) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Security check failed, this could be because of your browser cache. Please clear the cache and check it againe', 'doccure');
			wp_send_json($json);
		}

		update_user_meta($user_identity, 'payrols', array());
		$json['type'] = 'success';
		$json['message'] = esc_html__('Payout settings have been removed.', 'doccure');

		wp_send_json($json);
	}

	add_action('wp_ajax_doccure_payrols_remove_settings', 'doccure_payrols_remove_settings');
	add_action('wp_ajax_nopriv_doccure_payrols_remove_settings', 'doccure_payrols_remove_settings');
}


/**
 * check feedback

 */
if (!function_exists('doccure_check_feedback')) {

	function doccure_check_feedback()
	{
		global $current_user, $doccure_options;
		if (function_exists('doccure_is_demo_site')) {
			doccure_is_demo_site();
		}
		; //if demo site then prevent

		$user_identity = $current_user->ID;
		$user_type = apply_filters('doccure_get_user_type', $user_identity);
		$id = !empty($_POST['id']) ? sanitize_text_field($_POST['id']) : '';
		$metadata = array();


		if (function_exists('doccure_validate_user')) {
			doccure_validate_user();
		}
		; //if user is logged in

		//security check
		$do_check = check_ajax_referer('ajax_nonce', 'security', false);
		if ($do_check == false) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Security check failed, this could be because of your browser cache. Please clear the cache and check it againe', 'doccure');
			wp_send_json($json);
		}

		if (empty($id)) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Post ID is required', 'doccure');
			wp_send_json($json);
		}

		//check if patients only
		if (!empty($user_type) && $user_type != 'regular_users') {
			$json['type'] = 'error';
			$json['message'] = esc_html__('You are not allowed to add feedback.', 'doccure');
			wp_send_json($json);
		}

		$doctor_id = doccure_get_linked_profile_id($id, 'post');

		$user_reviews = array(
			'posts_per_page' => 1,
			'post_type' => 'reviews',
			'author' => $doctor_id,
			'meta_key' => '_user_id',
			'meta_value' => $user_identity,
			'meta_compare' => "=",
			'orderby' => 'meta_value',
			'order' => 'ASC',
		);

		$reviews_query = new WP_Query($user_reviews);
		$reviews_count = $reviews_query->post_count;

		if (isset($reviews_count) && $reviews_count > 0) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('You have already submit a review.', 'doccure');
			wp_send_json($json);
		}

		if ($user_type === 'regular_users' && !empty($id)) {
			$feedback_option = !empty($doccure_options['feedback_option']) ? $doccure_options['feedback_option'] : '';
			if (empty($feedback_option)) {
				$json['type'] = 'success';
				$json['message'] = esc_html__('Please add your feed back.', 'doccure');
			} else {
				$metadata['_doctor_id'] = $id;
				$bookings = doccure_get_total_posts_by_multiple_meta('booking', 'publish', $metadata, $user_identity);
				if (!empty($bookings) && $bookings > 0) {
					$json['type'] = 'success';
					$json['message'] = esc_html__('Please add your feed back.', 'doccure');
				} else {
					$json['type'] = 'error';
					$json['message'] = esc_html__('You need to complete atleast 1 appointment to add feedback.', 'doccure');
				}
			}
			wp_send_json($json);
		} else {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Something went wrong, please contact to administrator', 'doccure');
			wp_send_json($json);
		}
	}

	add_action('wp_ajax_doccure_check_feedback', 'doccure_check_feedback');
	add_action('wp_ajax_nopriv_doccure_check_feedback', 'doccure_check_feedback');
}

/**
 * On call contact details

 */
if (!function_exists('doccure_bookings_details')) {

	function doccure_bookings_details()
	{
		global $doccure_options;
		if (function_exists('doccure_is_demo_site')) {
			doccure_is_demo_site();
		}
		; //if demo site then prevent

		//security check
		$do_check = check_ajax_referer('ajax_nonce', 'security', false);
		if ($do_check == false) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Security check failed, this could be because of your browser cache. Please clear the cache and check it againe', 'doccure');
			wp_send_json($json);
		}

		$doctor_profile_id = !empty($_POST['id']) ? sanitize_text_field($_POST['id']) : '';
		if (empty($doctor_profile_id)) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Doctor profile is not found', 'doccure');
		} else {
			$html = '';
			$booking_option = !empty($doccure_options['booking_system_contact']) ? $doccure_options['booking_system_contact'] : '';

			if (empty($booking_option) || $booking_option === 'admin') {
				$contact_numbers = !empty($doccure_options['booking_contact_numbers']) ? $doccure_options['booking_contact_numbers'] : array();
				$booking_detail = !empty($doccure_options['booking_contact_detail']) ? $doccure_options['booking_contact_detail'] : '';
			} else {
				$contact_numbers_old = doccure_get_post_meta($doctor_profile_id, 'am_booking_contact');
				$booking_detail = doccure_get_post_meta($doctor_profile_id, 'am_booking_detail');

				$user_meta = doccure_get_post_meta($post_id);
				$contact_numbers = !empty($user_meta['am_mobile_number']) ? $user_meta['am_mobile_number'] : '';
			}

			$html .= '<div class="dc-tell-numbers">';
			if (!empty($booking_detail)) {
				$html .= '<span>' . $booking_detail . '</span>';
			}

			if (!empty($contact_numbers)) {

				$html .= '<a href="tel:+' . $contact_number . '" class="gh-numpopup">' . $user_meta . '</a>';
			}

			$html .= '</div>';

			if (empty($contact_numbers) && empty($booking_detail)) {
				$json['type'] = 'error';
				$json['message'] = esc_html__('We are sorry, but there is no contact information has been added.', 'doccure');
			} else {
				$json['type'] = 'success';
				$json['html'] = $html;
				$json['message'] = esc_html__('Booking contact details.', 'doccure');
			}
		}
		wp_send_json($json);
	}
	add_action('wp_ajax_doccure_bookings_details', 'doccure_bookings_details');
	add_action('wp_ajax_nopriv_doccure_bookings_details', 'doccure_bookings_details');
}
/**
 * Add doctor feedback

 */
if (!function_exists('doccure_users_invitations')) {

	function doccure_users_invitations()
	{
		global $current_user;
		if (function_exists('doccure_is_demo_site')) {
			doccure_is_demo_site();
		}
		; //if demo site then prevent

		if (function_exists('doccure_validate_user')) {
			doccure_validate_user();
		}
		; //if user is logged in

		//security check
		$do_check = check_ajax_referer('ajax_nonce', 'security', false);
		if ($do_check == false) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Security check failed, this could be because of your browser cache. Please clear the cache and check it againe', 'doccure');
			wp_send_json($json);
		}

		$fields = array(
			'emails' => esc_html('Email is required field.', 'doccure')
		);

		foreach ($fields as $key => $val) {
			if (empty($_POST[$key])) {
				$json['type'] = 'error';
				$json['message'] = $val;
				wp_send_json($json);
			}
		}

		$emails = !empty($_POST['emails']) ? $_POST['emails'] : array();
		$content = !empty($_POST['content']) ? $_POST['content'] : '';

		$user_name = doccure_get_username($current_user->ID);
		$user_detail = get_userdata($current_user->ID);
		$user_type = doccure_get_user_type($current_user->ID);
		$linked_profile = doccure_get_linked_profile_id($current_user->ID);
		$profile_url = get_the_permalink($linked_profile);

		if (class_exists('doccure_Email_helper')) {
			if (class_exists('doccureInvitationsNotify')) {
				$email_helper = new doccureInvitationsNotify();
				if (!empty($emails)) {
					$signup_page_url = doccure_get_signup_page_url();
					$signup_page_url = !empty($signup_page_url) ? $signup_page_url : home_url('/');
					foreach ($emails as $email) {
						if (is_email($email)) {
							$emailData = array();

							$emailData['email'] = $email;
							$emailData['invitation_content'] = $content;
							$emailData['invitation_link'] = $signup_page_url;

							if (!empty($user_type) && $user_type === 'doctors') {
								$emailData['doctor_name'] = $user_name;
								$emailData['doctor_profile_url'] = $profile_url;
								$emailData['doctor_email'] = $user_detail->user_email;
								$emailData['invited_hospital_email'] = $email;
								$email_helper->send_hospitals_email($emailData);
							} else if (!empty($user_type) && $user_type === 'hospitals') {
								$emailData['hospital_name'] = $user_name;
								$emailData['hospital_profile_url'] = $profile_url;
								$emailData['hospital_email'] = $user_detail->user_email;
								$emailData['invited_docor_email'] = $email;
								$email_helper->send_doctors_email($emailData);
							}
						}
					}
				}

				$json['type'] = 'success';
				$json['message'] = esc_html__('Your invitation is send to your email address.', 'doccure');
				wp_send_json($json);
			}
		}
	}
	add_action('wp_ajax_doccure_users_invitations', 'doccure_users_invitations');
	add_action('wp_ajax_nopriv_doccure_users_invitations', 'doccure_users_invitations');
}
/**
 * Add doctor feedback

 */
if (!function_exists('doccure_add_feedback')) {

	function doccure_add_feedback()
	{
		global $current_user, $wpdb;
		$user_identity = $current_user->ID;

		if (function_exists('doccure_is_demo_site')) {
			doccure_is_demo_site();
		}

		if (function_exists('doccure_validate_user')) {
			doccure_validate_user();
		}
		; //if user is logged in

		//security check
		$do_check = check_ajax_referer('ajax_nonce', 'security', false);
		if ($do_check == false) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Security check failed, this could be because of your browser cache. Please clear the cache and check it againe', 'doccure');
			wp_send_json($json);
		}

		//check if user is patient only
		$current_user_type = apply_filters('doccure_get_user_type', $user_identity);
		if (isset($current_user_type) && $current_user_type != 'regular_users') {
			$json['type'] = 'error';
			$json['message'] = esc_html__('You are not authorized to add the review', 'doccure');
			wp_send_json($json);
		}

		$fields = array(
			'feedback_recommend' => esc_html('Recommend is required field.', 'doccure'),
			'waiting_time' => esc_html('Select the waiting time.', 'doccure'),
			'feedback' => esc_html('Rating is required.', 'doccure'),
			'feedback_description' => esc_html('Description is required field.', 'doccure'),
			'doctor_id' => esc_html('Doctor ID is required.', 'doccure'),
		);

		foreach ($fields as $key => $val) {
			if (empty($_POST[$key])) {
				$json['type'] = 'error';
				$json['message'] = $val;
				wp_send_json($json);
			}
		}

		$contents = !empty($_POST['feedback_description']) ? sanitize_textarea_field($_POST['feedback_description']) : '';
		$recommend = !empty($_POST['feedback_recommend']) ? sanitize_text_field($_POST['feedback_recommend']) : '';
		$waiting_time = !empty($_POST['waiting_time']) ? sanitize_text_field($_POST['waiting_time']) : '';
		$doctor_profile_id = !empty($_POST['doctor_id']) ? sanitize_text_field($_POST['doctor_id']) : '';
		$feedbackpublicly = !empty($_POST['feedbackpublicly']) ? sanitize_text_field($_POST['feedbackpublicly']) : '';
		$reviews = !empty($_POST['feedback']) ? $_POST['feedback'] : array();
		$review_title = get_the_title($doctor_profile_id);
		$doctor_id = doccure_get_linked_profile_id($doctor_profile_id, 'post');

		$user_reviews = array(
			'posts_per_page' => 1,
			'post_type' => 'reviews',
			'author' => $doctor_id,
			'meta_key' => '_user_id',
			'meta_value' => $user_identity,
			'meta_compare' => "=",
			'orderby' => 'meta_value',
			'order' => 'ASC',
		);

		$reviews_query = new WP_Query($user_reviews);
		$reviews_count = $reviews_query->post_count;

		if (isset($reviews_count) && $reviews_count > 0) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('You have already submit a review.', 'doccure');
			wp_send_json($json);
		} else {
			$review_post = array(
				'post_title' => $review_title,
				'post_status' => 'publish',
				'post_content' => $contents,
				'post_author' => $doctor_id,
				'post_type' => 'reviews',
				'post_date' => current_time('Y-m-d H:i:s')
			);

			$post_id = wp_insert_post($review_post);

			/* Get the rating headings */
			$rating_evaluation = doccure_doctor_ratings();
			$rating_evaluation_count = !empty($rating_evaluation) ? doccure_count_items($rating_evaluation) : 0;

			$review_extra_meta = array();
			$rating = 0;
			$user_rating = 0;

			if (!empty($rating_evaluation)) {
				foreach ($rating_evaluation as $slug => $label) {
					if (isset($reviews[$slug])) {
						$review_extra_meta[$slug] = esc_html($reviews[$slug]);
						update_post_meta($post_id, $slug, esc_html($reviews[$slug]));
						$rating += (int) $reviews[$slug];
					}
				}
			}

			update_post_meta($post_id, '_user_id', $user_identity);
			update_post_meta($post_id, '_waiting_time', $waiting_time);
			update_post_meta($post_id, '_feedback_recommend', $recommend);
			update_post_meta($post_id, '_feedbackpublicly', $feedbackpublicly);

			if (!empty($rating)) {
				$user_rating = $rating / $rating_evaluation_count;
			}

			$user_profile_id = doccure_get_linked_profile_id($user_identity);
			$user_rating = number_format((float) $user_rating, 2, '.', '');
			$single_user_user_rating = $user_rating;
			$review_meta = array(
				'user_rating' => $user_rating,
				'user_from' => $user_profile_id,
				'user_to' => $doctor_profile_id,
				'review_date' => current_time('Y-m-d H:i:s'),
			);
			$review_meta = array_merge($review_meta, $review_extra_meta);

			//Update post meta
			foreach ($review_meta as $key => $value) {
				update_post_meta($post_id, $key, $value);
			}

			$table_review = $wpdb->prefix . "posts";
			$table_meta = $wpdb->prefix . "postmeta";

			$db_rating_query = $wpdb->get_row("
				SELECT p.ID,
				SUM( pm2.meta_value ) AS db_rating,
				count( p.ID ) AS db_total
				FROM " . $table_review . " p 
				LEFT JOIN " . $table_meta . " pm1 ON (pm1.post_id = p.ID AND pm1.meta_key = 'user_to') 
				LEFT JOIN " . $table_meta . " pm2 ON (pm2.post_id = p.ID AND pm2.meta_key = 'user_rating')
				WHERE post_status = 'publish'
				AND pm1.meta_value = " . $doctor_profile_id . "
				AND p.post_type = 'reviews'
				", ARRAY_A);

			//$user_rating = '0';

			if (empty($db_rating_query)) {
				$user_db_reviews['dc_average_rating'] = 0;
				$user_db_reviews['dc_total_rating'] = 0;
				$user_db_reviews['dc_total_percentage'] = 0;
				$user_db_reviews['wt_rating_count'] = 0;
			} else {

				$rating = !empty($db_rating_query['db_rating']) ? $db_rating_query['db_rating'] / $db_rating_query['db_total'] : 0;
				$user_rating = number_format((float) $rating, 2, '.', '');

				$user_db_reviews['dc_average_rating'] = $user_rating;
				$user_db_reviews['dc_total_rating'] = !empty($db_rating_query['db_total']) ? $db_rating_query['db_total'] : '';
				$user_db_reviews['dc_total_percentage'] = $user_rating * 20;
				$user_db_reviews['dc_rating_count'] = !empty($db_rating_query['db_rating']) ? $db_rating_query['db_rating'] : '';
			}

			update_post_meta($doctor_profile_id, 'review_data', $user_db_reviews);
			update_post_meta($doctor_profile_id, 'rating_filter', $user_rating);

			$total_rating = get_post_meta($doctor_profile_id, '_total_voting', true);
			$total_rating = !empty($total_rating) ? $total_rating + 1 : 0;

			$total_recommend = get_post_meta($doctor_profile_id, '_recommend', true);
			$total_recommend = !empty($total_recommend) ? $total_recommend : 0;
			$total_recommend = !empty($recommend) && $recommend === 'yes' ? $total_recommend + 1 : $total_recommend;

			update_post_meta($doctor_profile_id, '_recommend', $total_recommend);
			update_post_meta($doctor_profile_id, '_total_voting', $total_rating);

			//Send email to users
			if (class_exists('doccure_Email_helper')) {
				if (class_exists('doccureFeedbackNotify')) {
					$email_helper = new doccureFeedbackNotify();
					$doctor_details = !empty($doctor_id) ? get_userdata($doctor_id) : array();
					$emailData = array();
					$waiting_time_array = doccure_get_waiting_time();
					$emailData['email'] = !empty($doctor_details->user_email) ? $doctor_details->user_email : '';
					$emailData['user_name'] = !empty($user_profile_id) ? doccure_full_name($user_profile_id) : '';
					$emailData['doctor_name'] = !empty($doctor_profile_id) ? doccure_full_name($doctor_profile_id) : '';
					$emailData['waiting_time'] = !empty($waiting_time_array[$waiting_time]) ? esc_html($waiting_time_array[$waiting_time]) : '';
					$emailData['recommend'] = !empty($recommend) ? ucfirst($recommend) : '';
					$emailData['rating'] = !empty($single_user_user_rating) ? $single_user_user_rating : 0;
					$emailData['description'] = sanitize_textarea_field($contents);

					$email_helper->send_feedback_email_doctor($emailData);
				}
			}
			$json['type'] = 'success';
			$json['message'] = esc_html__('Your feedback is successfully submitted.', 'doccure');
			wp_send_json($json);
		}
	}

	add_action('wp_ajax_doccure_add_feedback', 'doccure_add_feedback');
	add_action('wp_ajax_nopriv_doccure_add_feedback', 'doccure_add_feedback');
}

/**
 * Send app url

 */
if (!function_exists('doccure_get_app_link')) {

	function doccure_get_app_link()
	{
		$app_eamil = !empty($_POST['app_eamil']) ? $_POST['app_eamil'] : '';
		if (function_exists('doccure_is_demo_site')) {
			doccure_is_demo_site();
		}

		if (empty($app_eamil)) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Email is required.', 'doccure');
			wp_send_json($json);
		}

		//security check
		$do_check = check_ajax_referer('ajax_nonce', 'security', false);
		if ($do_check == false) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Security check failed, this could be because of your browser cache. Please clear the cache and check it againe', 'doccure');
			wp_send_json($json);
		}

		if (is_email($app_eamil)) {
			//Send email to user
			if (class_exists('doccure_Email_helper')) {
				if (class_exists('doccureAppLinkNotify')) {
					$email_helper = new doccureAppLinkNotify();
					$emailData = array();
					$emailData['email'] = $app_eamil;
					$email_helper->send_applink_email($emailData);
					$json['type'] = 'success';
					$json['message'] = esc_html__('App link is send to your email address.', 'doccure');
					wp_send_json($json);
				}
			}
		} else {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Please enter a valid email address.', 'doccure');
			wp_send_json($json);
		}
	}

	add_action('wp_ajax_doccure_get_app_link', 'doccure_get_app_link');
	add_action('wp_ajax_nopriv_doccure_get_app_link', 'doccure_get_app_link');
}

/**
 * Update prescription

 */
if (!function_exists('doccure_update_prescription')) {

	function doccure_update_prescription()
	{
		global $current_user;
		$booking_id = !empty($_POST['booking_id']) ? sanitize_text_field($_POST['booking_id']) : '';

		if (function_exists('doccure_is_demo_site')) {
			doccure_is_demo_site();
		}

		if (function_exists('doccure_validate_user')) {
			doccure_validate_user();
		}
		; //if user is logged in

		//security check
		$do_check = check_ajax_referer('ajax_nonce', 'security', false);
		if ($do_check == false) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Security check failed, this could be because of your browser cache. Please clear the cache and check it againe', 'doccure');
			wp_send_json($json);
		}

		//$doctor_id			= get_post_meta($booking_id,'_doctor_id', true);
		//$doctor_user_id		= doccure_get_linked_profile_id($doctor_id,'post');


		$user_type = apply_filters('doccure_get_user_type', $current_user);

		if ($user_type === 'doctors') {
			$doctor_user_id = get_post_meta($booking_id, '_parentdoctor_id', true);
		} else {
			$doctor_id = get_post_meta($booking_id, '_doctor_id', true);
			$doctor_user_id = get_post_field('post_author', $doctor_id);
		}

		// if( isset($doctor_user_id) && intval( $doctor_user_id ) !== intval( $current_user->ID )  ){
		// 	$json['type'] 	 = 'error';
		// 	$json['message'] = esc_html__('You are not authorized to update the details', 'doccure');
		// 	wp_send_json( $json );
		// }

		$json = array();
		$fields = array(
			'patient_name' => esc_html('Name is required.', 'doccure'),
			'medical_history' => esc_html('Medical history is required.', 'doccure'),
			'booking_id' => esc_html('Booking ID is required.', 'doccure')
		);

		foreach ($fields as $key => $val) {
			if (empty($_POST[$key])) {
				$json['type'] = 'error';
				$json['message'] = $val;
				wp_send_json($json);
			}
		}


		$patient_name = !empty($_POST['patient_name']) ? sanitize_text_field($_POST['patient_name']) : '';
		$phone = !empty($_POST['phone']) ? sanitize_text_field($_POST['phone']) : '';
		$age = !empty($_POST['age']) ? sanitize_text_field($_POST['age']) : '';
		$address = !empty($_POST['address']) ? sanitize_text_field($_POST['address']) : '';
		$location = !empty($_POST['location']) ? doccure_get_term_by_type('slug', sanitize_text_field($_POST['location']), 'locations') : '';
		$gender = !empty($_POST['gender']) ? sanitize_text_field($_POST['gender']) : '';
		$marital_status = !empty($_POST['marital_status']) ? ($_POST['marital_status']) : '';
		$childhood_illness = !empty($_POST['childhood_illness']) ? ($_POST['childhood_illness']) : array();
		$laboratory_tests = !empty($_POST['laboratory_tests']) ? ($_POST['laboratory_tests']) : array();
		$vital_signs = !empty($_POST['vital_signs']) ? ($_POST['vital_signs']) : '';
		$medical_history = !empty($_POST['medical_history']) ? sanitize_text_field($_POST['medical_history']) : '';
		$medicine = !empty($_POST['medicine']) ? ($_POST['medicine']) : array();

		$diseases = !empty($_POST['diseases']) ? ($_POST['diseases']) : array();
		$medical_history = !empty($_POST['medical_history']) ? sanitize_textarea_field($_POST['medical_history']) : '';

		$doctor_id = get_post_meta($booking_id, '_doctor_id', true);
		//$doctor_id				= doccure_get_linked_profile_id($doctor_id,'post');
		$hospital_id = get_post_meta($booking_id, '_hospital_id', true);

		$prescription_id = get_post_meta($booking_id, '_prescription_id', true);
		$am_booking = get_post_meta($booking_id, '_am_booking', true);
		$patient_id = get_post_field('post_author', $booking_id);

		$myself = !empty($am_booking['myself']) ? $am_booking['myself'] : '';

		// if( !empty($doctor_id) && ($doctor_id != $current_user->ID) ){
		// 	$json['type'] 		= 'error';
		// 	$json['message'] 	= esc_html__('You are not allwod to add prescription.','doccure');        
		// 	wp_send_json($json);
		// }

		$post_array = array();
		$post_array['post_title'] = $patient_name;
		if (empty($prescription_id)) {
			$post_array['post_type'] = 'prescription';
			$post_array['post_status'] = 'publish';
			$prescription_id = wp_insert_post($post_array);
		} else {
			wp_update_post($post_array);
		}

		$post_meta = array();
		if (!empty($laboratory_tests)) {
			$laboratory_tests_array = array();
			foreach ($laboratory_tests as $laboratory_test) {
				$term = doccure_get_term_by_type('id', $laboratory_test, 'laboratory_tests', 'id');
				if (!empty($term)) {
					$laboratory_tests_id = $laboratory_test;
				} else {
					wp_insert_term($laboratory_test, 'laboratory_tests');
					$term = doccure_get_term_by_type('name', $laboratory_test, 'laboratory_tests', 'id');
					$laboratory_tests_id = !empty($term) ? $term : '';
				}

				if (!empty($laboratory_tests_id)) {
					$laboratory_tests_array[] = $laboratory_tests_id;
				}
			}
			if (!empty($laboratory_tests_array)) {
				wp_set_post_terms($prescription_id, $laboratory_tests_array, 'laboratory_tests');
			}
			$post_meta['_laboratory_tests'] = $laboratory_tests_array;
		}

		$post_meta['_patient_name'] = $patient_name;
		$post_meta['_phone'] = $phone;
		$post_meta['_age'] = $age;
		$post_meta['_address'] = $address;
		$post_meta['_location'] = $location;
		$post_meta['_gender'] = $gender;

		$post_meta['_marital_status'] = $marital_status;
		$post_meta['_childhood_illness'] = $childhood_illness;
		$post_meta['_vital_signs'] = $vital_signs;
		$post_meta['_medical_history'] = $medical_history;
		$post_meta['_medicine'] = $medicine;
		$post_meta['_diseases'] = $diseases;

		$signs_keys = !empty($vital_signs) ? array_keys($vital_signs) : array();
		$signs_keys = !empty($signs_keys) ? array_unique($signs_keys) : array();

		wp_set_post_terms($prescription_id, array($location), 'locations');
		wp_set_post_terms($prescription_id, $signs_keys, 'vital_signs');
		wp_set_post_terms($prescription_id, $childhood_illness, 'childhood_illness');
		wp_set_post_terms($prescription_id, array($marital_status), 'marital_status');
		wp_set_post_terms($prescription_id, $diseases, 'diseases');

		update_post_meta($prescription_id, '_hospital_id', $hospital_id);
		update_post_meta($prescription_id, '_medicine', $medicine);
		update_post_meta($prescription_id, '_doctor_id', $doctor_id);
		update_post_meta($prescription_id, '_booking_id', $booking_id);
		update_post_meta($prescription_id, '_patient_id', $patient_id);
		update_post_meta($prescription_id, '_myself', $myself);
		update_post_meta($prescription_id, '_detail', $post_meta);

		update_post_meta($prescription_id, '_childhood_illness', $childhood_illness);
		update_post_meta($prescription_id, '_marital_status', $marital_status);

		update_post_meta($booking_id, '_prescription_id', $prescription_id);

		$json['type'] = 'success';
		$json['message'] = esc_html__('Prescription has been updated successfully.', 'doccure');
		$json['url'] = doccure_Profile_Menu::doccure_profile_menu_link('appointment', $current_user->ID, true, 'listing', $booking_id);
		wp_send_json($json);
	}

	add_action('wp_ajax_doccure_update_prescription', 'doccure_update_prescription');
	add_action('wp_ajax_nopriv_doccure_update_prescription', 'doccure_update_prescription');
}

/**
 * Send app url
 *
 * @throws error
 * @return 
 */


if (!function_exists('doccure_calcute_price')) {

	function doccure_calcute_price()
	{

		if (function_exists('doccure_is_demo_site')) {
			doccure_is_demo_site();
		}

		if (function_exists('doccure_validate_user')) {
			doccure_validate_user();
		}
		; //if user is logged in

		//security check
		$do_check = check_ajax_referer('ajax_nonce', 'security', false);
		if ($do_check == false) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Security check failed, this could be because of your browser cache. Please clear the cache and check it againe', 'doccure');
			wp_send_json($json);
		}

		$json = array();
		$consultant_fee = !empty($_POST['consultant_fee']) ? $_POST['consultant_fee'] : 0;
		$allprices = !empty($_POST['allprices']) ? $_POST['allprices'] : '';
		$price = !empty($_POST['price']) ? $_POST['price'] : 0;

		if (!empty($allprices) && is_array($allprices)) {
			$total_price = array_sum($allprices) + $consultant_fee;
		} else {
			$allprices = "0";
			$total_price = ($allprices) + $consultant_fee;
		}

		$json['total_price'] = $total_price;
		$json['total_price_format'] = doccure_price_format($total_price, 'return');
		$json['price_format'] = doccure_price_format($price, 'return');
		$json['type'] = 'success';
		wp_send_json($json);
	}

	add_action('wp_ajax_doccure_calcute_price', 'doccure_calcute_price');
	add_action('wp_ajax_nopriv_doccure_calcute_price', 'doccure_calcute_price');
}






// *
//  * @throws error
//  * @return 
//  */
if (!function_exists('doccure_resend_verification')) {

	function doccure_resend_verification()
	{
		global $current_user;
		$json = array();

		if (function_exists('doccure_validate_user')) {
			doccure_validate_user();
		}
		; //if user is logged in

		//security check
		$do_check = check_ajax_referer('ajax_nonce', 'security', false);
		if ($do_check == false) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Security check failed, this could be because of your browser cache. Please clear the cache and check it againe', 'doccure');
			wp_send_json($json);
		}

		//Send verification code
		if (class_exists('doccure_Email_helper')) {
			if (class_exists('doccureRegisterNotify')) {
				$email_helper = new doccureRegisterNotify();

				$key_hash = md5(uniqid(openssl_random_pseudo_bytes(32)));
				update_user_meta($current_user->ID, 'confirmation_key', $key_hash);
				$protocol = is_ssl() ? 'https' : 'http';
				$verify_link = esc_url(add_query_arg(array('key' => $key_hash . '&verifyemail=' . $current_user->user_email), home_url('/', $protocol)));


				$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
				$emailData = array();
				$emailData['name'] = doccure_get_username($current_user->ID);
				;
				$emailData['email'] = $current_user->user_email;
				$emailData['site'] = $blogname;
				$emailData['verification_link'] = $verify_link;

				$email_helper->send_verification($emailData);
			}
		}
		$json['type'] = 'success';
		$json['message'] = esc_html__('Verification email has been sent to your email address', 'doccure');
		wp_send_json($json);
	}

	add_action('wp_ajax_doccure_resend_verification', 'doccure_resend_verification');
	add_action('wp_ajax_nopriv_doccure_resend_verification', 'doccure_resend_verification');
}

/**
 * Post Likes

 */
if (!function_exists('doccure_post_likes')) {

	function doccure_post_likes()
	{
		$post_id = !empty($_POST['id']) ? $_POST['id'] : '';
		$json = array();

		if (function_exists('doccure_validate_user')) {
			doccure_validate_user();
		}
		; //if user is logged in

		//security check
		$do_check = check_ajax_referer('ajax_nonce', 'security', false);
		if ($do_check == false) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Security check failed, this could be because of your browser cache. Please clear the cache and check it againe', 'doccure');
			wp_send_json($json);
		}

		if (empty($post_id)) {
			$json['type'] = 'error';
			$json['message'] = esc_html__('Post ID is required', 'doccure');
			wp_send_json($json);
		}

		$key = 'post_liked_';

		if (!isset($_COOKIE[$key . $post_id])) {
			setcookie($key . $post_id, $key, time() + (365 * 24 * 60 * 60));
			$view_key = 'post_likes';

			$count = get_post_meta($post_id, $view_key, true);

			if (empty($count)) {
				$count = 1;
				add_post_meta($post_id, $view_key, 1);
			} else {
				$count++;
				update_post_meta($post_id, $view_key, $count);
			}

			$json['html'] = sprintf(_n('<i class="ti-heart"></i>%s Like', '<i class="ti-heart"></i>%s Likes', $count, 'doccure'), $count);

			$json['type'] = 'success';
			$json['message'] = esc_html__('Post has been liked', 'doccure');
			wp_send_json($json);
		} else {
			$json['type'] = 'error';
			$json['message'] = esc_html__('You have already liked this post', 'doccure');
			wp_send_json($json);
		}
	}

	add_action('wp_ajax_doccure_post_likes', 'doccure_post_likes');
	add_action('wp_ajax_nopriv_doccure_post_likes', 'doccure_post_likes');
}	

/*New Booking Layout Special and Services here*/
	if (!function_exists('doccure_get_booking_select_service')) {

		function doccure_get_booking_select_service()
		{
			global $wpdb;
			$post_id = !empty($_POST['id']) ? intval($_POST['id']) : '';
			$doctor_id = !empty($_POST['doctor_id']) ? intval($_POST['doctor_id']) : '';
			$slot_id = !empty($_POST['slot_id']) ? intval($_POST['slot_id']) : '';
			$json = array();

			$table_name = $wpdb->prefix . "dc_schedule";
			$get_parent_doctor_id = $wpdb->get_var($wpdb->prepare(
				"SELECT parent_doctor_id FROM $table_name WHERE id = %d",
				$slot_id
			));



			if ($get_parent_doctor_id != '0') {
				$get_parent_doctor_id = $get_parent_doctor_id;
				$get_doctor_id = get_user_meta($get_parent_doctor_id, '_linked_profile', true);
			} else {

				$table_name = $wpdb->prefix . "dc_schedule";
				$doctor_user_id_new = $wpdb->get_var($wpdb->prepare(
					"SELECT doctor_id FROM $table_name WHERE id = %d",
					$slot_id
				));

				$get_doctor_id = $doctor_user_id_new;
			}


			if (function_exists('doccure_validate_user')) {
				doccure_validate_user();
			}
			; //if user is logged in

			//security check
			$do_check = check_ajax_referer('ajax_nonce', 'security', false);
			if ($do_check == false) {
				$json['type'] = 'error';
				$json['message'] = esc_html__('Security check failed, this could be because of your browser cache. Please clear the cache and check it againe', 'doccure');
				wp_send_json($json);
			}

			if (!empty($post_id)) {

				$json['consultant_fee'] = '';

				$doctor_user_id = get_post_field('post_author', $doctor_id);

				$am_consultant_fee = get_user_meta($doctor_user_id, 'consultation_fee', true);
				$consultant_fee = !empty($am_consultant_fee) ? doccure_price_format($am_consultant_fee, 'return') : doccure_price_format(0, 'return');


				if (isset($consultant_fee)) {
					// Start building the HTML
					$consultant_fee_html = '<div class="card-body_1 at-taxesfees_1 mb-0">		
					<input type="hidden" value="' . $post_id . '" name="booking_hospitals"> 
						<div class="booking-more-info">
							<h6 class="mb-3">Payment Info</h6>
							<div class="d-flex align-items-center flex-wrap rpw-gap-2 justify-content-between mb-2" id="consultant_fee">					
								<p class="mb-0">' . esc_html__('Consultation fee', 'doccure') . '</p>
								<span class="fw-medium d-block dc-consultant-fee dc-service-price" data-price="' . $am_consultant_fee . '" data-tipso="Verified user" id="service-price">' . $consultant_fee . '</span>
							</div>';

					// Add insurance discount row only if insurance option is enabled
					if (doccure_get_option('insurance_option')) {
						$consultant_fee_html .= '
							<div class="d-flex align-items-center flex-wrap rpw-gap-2 justify-content-between mb-2" id="dc-insurance-discount-row" style="display:none;">
								<p class="mb-0">' . esc_html__('Insurance amount', 'doccure') . '</p>
								<span class="fw-medium d-block dc-insurance-discount" data-amount="0" data-type="">-$0.00</span>
							</div>';
					}

					// Continue with the rest of the HTML
					$consultant_fee_html .= '
						<div class="bg-primary d-flex align-items-center flex-wrap rpw-gap-2 justify-content-between p-3 rounded at-toteltextfee">
							<h6 class="text-white" style="margin-bottom:0px;">' . esc_html__('Total', 'doccure') . '</h6>
							<h6 class="text-white" style="margin-bottom:0px;" id="dc-total-price" data-price="' . $am_consultant_fee . '">' . $consultant_fee . '</h6>
							<input type="hidden" name="original_price" id="original_price" value="' . esc_attr($am_consultant_fee) . '">
						</div>
					</div>';

					$json['consultant_fee'] = $consultant_fee_html;
				}

				$service_html = '';
				$day = strtolower(date('D'));
				$date = date('Y-m-d');
				//$reponse_slots			= doccure_get_time_slots_spaces($post_id,$day,$date);
				$reponse_slots = "";
				$norecourd_found = apply_filters('doccure_empty_records_html', 'dc-empty-articls dc-emptyholder-sm', esc_html__('There are no any sloat available.', 'doccure'), true);
				$reponse_slots = !empty($reponse_slots) ? $reponse_slots : $norecourd_found;
				$json['time_slots'] = $reponse_slots;

				$service_html = apply_filters('doccure_get_group_services_with_speciality_newbooking', $slot_id, '', 'return', 'location', $get_doctor_id);
				$json['type'] = 'success';
				$json['booking_services'] = $service_html;
				wp_send_json($json);
			} else {
				$json['type'] = 'error';
				$json['message'] = esc_html__('You need to select hospital.', 'doccure');
				wp_send_json($json);
			}
		}

		add_action('wp_ajax_doccure_get_booking_select_service', 'doccure_get_booking_select_service');
		add_action('wp_ajax_nopriv_doccure_get_booking_select_service', 'doccure_get_booking_select_service');
	}

/*New Booking Layout Special and Services here*/