<?php
/**
 * GFB Email Notification Class
 *
 * @package GFB.
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

if ( ! class_exists( 'APBGF_Email' ) ) {
	
	class APBGF_Email {       
		/**
		 * Instance
		 *
		 * @var $instance
		 */
		private static $instance = null;

		public static $header = array();

		public static $email_templates = array();

		public static $apbgf_setting = array();

		/**
		*
		* The function is added in v2.4.0 to add new templates of email.
		* @var $apbgf_email_templates holds old templates.
		*/
		private function __add_new_template( $apbgf_email_templates ) {
			if ( !isset( $apbgf_email_templates['template_9'] ) && !isset( $apbgf_email_templates['template_10'] ) ) {
				$apbgf_email_templates['template_9'] = array(
					'id' => 9,
					'title' => __('Email reminder to staff about appointment', 'appointment-and-booking-for-gravity-forms'),
					'subject' => 'Reminder Notification About Appointment',
					'message' => wpautop( stripslashes( 'Dear {staff_name},
This is a reminder email to inform you about an upcoming appointment for you. For reference, here\'s the appointment information:

Client Name: {client_name} Date: {appointment_date}
Time: {appointment_time}
Service: {service_name}
Staff: {staff_name}
Thank You.

Sincerely,
{company_name} , {company_phone}
{company_email}
{company_website}' ) ),
					'switch' => 'disabled',
					'day' => '1'
				);

				$apbgf_email_templates['template_10'] = array(
					'id' => 10,
					'title' => __('Email reminder to customer about appointment', 'appointment-and-booking-for-gravity-forms'),
					'subject' => 'Reminder Notification About Appointment',
					'message' => wpautop( stripslashes('Dear {client_name},

This is a reminder email to inform you about an upcoming appointment with {staff_name}. For reference, here\'s the appointment information:

Date: {appointment_date}
Time: {appointment_time}
Service: {service_name}
Staff: {staff_name}

Sincerely,
{company_name} , {company_phone}
{company_email}
{company_website}')),
					'switch' => 'disabled',
					'day' => '1'
				);
			}

			return $apbgf_email_templates;
		}

		/**
		 * Init the Dependencies.
		 */
		private function __construct() {

			$apbgf_email_templates = get_option('apbgf_email_templates', array());

			if ( is_array( $apbgf_email_templates ) && count( $apbgf_email_templates ) > 0 ) {

				$apbgf_email_templates = $this->__add_new_template($apbgf_email_templates);
				self::$email_templates = $apbgf_email_templates;

			} else {

				self::$email_templates = array(
					'template_1' => array(
						'id' => 1,
						'title' => __('Email to customer about appointment confirmation', 'appointment-and-booking-for-gravity-forms'),
						'subject' => 'Notification About Appointment Confirmation',
						'message' => wpautop( stripslashes('Dear {client_name},

	This is just an email to confirm your appointment with {staff_name}. For reference, here\'s the appointment information:

	Date: {appointment_date}
	Time: {appointment_time}
	Service: {service_name}
	Staff: {staff_name}

	Sincerely,
	{company_name} , {company_phone}
	{company_email}
	{company_website}')),
						'switch' => 'disabled'
					),
					'template_2' => array(
						'id' => 2,
						'title' => __('Email to customer about visit confirmation', 'appointment-and-booking-for-gravity-forms'),
						'subject' => 'Thank You For Visit',
						'message' => wpautop( stripslashes('Dear {client_name},

	This is to thank you for your visit at our place. We hope that you were satisfied with our services.
	If any issue or query, you are free to call us. Thank You.

	Sincerely,
	{company_name} , {company_phone}
	{company_email}
	{company_website}')),
						'switch' => 'disabled'
					),
					'template_3' => array(
						'id' => 3,
						'title' => __('Email to customer about appointment cancellation', 'appointment-and-booking-for-gravity-forms'),
						'subject' => 'Notification About Appopintment Cancellation',
						'message' => wpautop( stripslashes('Dear {client_name},

	This is just an email to inform you that your appointment with {staff_name} has been cancelled. For reference, here\'s the appointment information:

	Date: {appointment_date}
	Time: {appointment_time}
	Service: {service_name}
	Staff: {staff_name} .
	We regret about your inconvenience from our side.
	Thank You

	Sincerely,
	{company_name} , {company_phone}
	{company_email}
	{company_website}')),
						'switch' => 'disabled'
					),
					'template_4' => array(
						'id' => 4,
						'title' => __('Email to admin about customer visit', 'appointment-and-booking-for-gravity-forms'),
						'subject' => 'Notification About Customer Visit',
						'message' => wpautop( stripslashes('Dear Administrator,

	This is an email inform you about cancallation about the appointment with {staff_name}. For reference, here\'s the appointment information:

	Client Name: {client_name} Date: {appointment_date}
	Time: {appointment_time}
	Service: {service_name}
	Staff: {staff_name}.
	Thank You

	Sincerely,
	{company_name} , {company_phone}
	{company_email}
	{company_website}')),
						'switch' => 'disabled'
					),
					'template_5' => array(
						'id' => 5,
						'title' => __('Email to admin about appointment request', 'appointment-and-booking-for-gravity-forms'),
						'subject' => 'Notification About Appointment Request',
						'message' => wpautop( stripslashes('Dear Administrator,

	This is an email to inform you about a new appointment request. For reference, here\'s the appointment information:

	Client Name: {client_name} Date: {appointment_date}
	Time: {appointment_time}
	Service: {service_name}
	Staff: {staff_name}
	Thank You.

	Sincerely,
	{company_name} , {company_phone}
	{company_email}
	{company_website}')),
						'switch' => 'disabled'
					),
					'template_6' => array(
						'id' => 6,
						'title' => __('Email to admin about appointment cancellation', 'appointment-and-booking-for-gravity-forms'),
						'subject' => 'Notification About Appointment Cancellation',
						'message' => wpautop( stripslashes('Dear Administrator,

	This is an email to inform you about an appointment has been cancelled. For reference, here\'s the appointment information:

	Client Name: {client_name} Date: {appointment_date}
	Time: {appointment_time}
	Service: {service_name}
	Staff: {staff_name}
	Thank You.

	Sincerely,
	{company_name} , {company_phone}
	{company_email}
	{company_website}')),
						'switch' => 'disabled'
					),
					'template_7' => array(
						'id' => 7,
						'title' => __('Email to staff about appointment cancellation', 'appointment-and-booking-for-gravity-forms'),
						'subject' => 'Notification About Appointment Cancellation',
						'message' => wpautop( stripslashes('Dear {staff_name},

	This is an email to inform you about an appointment has been cancelled. For reference, here\'s the appointment information:

	Client Name: {client_name} Date: {appointment_date}
	Time: {appointment_time}
	Service: {service_name}
	Staff: {staff_name}
	Thank You.

	Sincerely,
	{company_name} , {company_phone}
	{company_email}
	{company_website}')),
						'switch' => 'disabled'
					),
					'template_8' => array(
						'id' => 8,
						'title' => __('Email to staff about appointment request', 'appointment-and-booking-for-gravity-forms'),
						'subject' => 'Notification About Appointment Request',
						'message' => wpautop( stripslashes( 'Dear {staff_name},
	This is an email to inform you about a new appointment request for you. For reference, here\'s the appointment information:

	Client Name: {client_name} Date: {appointment_date}
	Time: {appointment_time}
	Service: {service_name}
	Staff: {staff_name}
	Thank You.

	Sincerely,
	{company_name} , {company_phone}
	{company_email}
	{company_website}' ) ),
						'switch' => 'disabled'
					),                  
				);

				self::$email_templates = $this->__add_new_template(self::$email_templates);
			
			}

			add_action('apbgf_before_settings_menu', array( $this, 'register_menu' ));

			self::$apbgf_setting = APBGF_Setting::get_settings();

			if ( isset(self::$apbgf_setting['apbgf_sender_name']) && isset(self::$apbgf_setting['apbgf_sender_email']) && ! empty(trim(self::$apbgf_setting['apbgf_sender_name'])) && ! empty(trim(self::$apbgf_setting['apbgf_sender_email']) ) ) {
				self::$header = array( 'Content-Type: text/html; charset=UTF-8', 'From: ' . self::$apbgf_setting['apbgf_sender_name'] . ' <' . self::$apbgf_setting['apbgf_sender_email'] . '>' );
			} else {
				self::$header = array( 'Content-Type: text/html; charset=UTF-8', 'From: ' . esc_attr( get_bloginfo( 'name' ) ) . ' <' . esc_attr( get_option( 'admin_email' ) ) . '>' );
			}

			add_action('wp_ajax_apbgf_email_template_settings', array( $this, 'apbgf_email_template_settings' ) );


			// echo '<pre>';
			// print_r( self::$email_templates );
			// echo '</pre>';
		}


		public function apbgf_email_template_settings() {

			check_ajax_referer( 'appointment-and-booking-for-gravity-forms', 'nonce' );

			$apbgf_email_templates = get_option('apbgf_email_templates', array());
			$apbgf_email_templates = $this->__add_new_template($apbgf_email_templates);

			$response = array(
				'message' => esc_html__( 'Email Notification not saved.', 'appointment-and-booking-for-gravity-forms' ),
				'status'  => 'error'
			);          

			// Do not process the whole request; pull only expected keys per template, sanitized
			$pro_template_ids = apply_filters( 'apbgf_pro_email_templates_ids_setting', array( 2, 4, 5, 6, 7, 8, 9 ));
			foreach ( self::$email_templates as $key => $template ) {   
				
				if (in_array( $template['id'], $pro_template_ids)) {

					$apbgf_email_templates[ $key ]['id'] = $template['id'];
					$apbgf_email_templates[ $key ]['title'] = $template['title'];
					$apbgf_email_templates[ $key ]['subject'] = $template['subject'];
					$apbgf_email_templates[ $key ]['message'] = $template['message'];
					$apbgf_email_templates[ $key ]['switch'] = 'disabled';
					if ( isset( $apbgf_email_templates[ $key ]['day'] ) ) {
						$apbgf_email_templates[ $key ]['day'] = 1;
					}

				} else {

					$apbgf_email_templates[ $key ]['id']    = $template['id'];
					$apbgf_email_templates[ $key ]['title'] = $template['title'];
					// subject_X
					$subject_key = 'subject_' . $template['id'];
					$subject_val = isset( $_POST[ $subject_key ] ) ? sanitize_text_field( wp_unslash( $_POST[ $subject_key ] ) ) : '';
					$apbgf_email_templates[ $key ]['subject'] = $subject_val;
					// message_X (allow safe HTML)
					$message_key = 'message_' . $template['id'];
					$message_val = isset( $_POST[ $message_key ] ) ? wp_kses_post( wp_unslash( $_POST[ $message_key ] ) ) : '';
					$apbgf_email_templates[ $key ]['message'] = $message_val;
					// switch_X only enabled/disabled
					$switch_key = 'switch_' . $template['id'];
					$switch_val = isset( $_POST[ $switch_key ] ) ? sanitize_text_field( wp_unslash( $_POST[ $switch_key ] ) ) : 'disabled';
					$apbgf_email_templates[ $key ]['switch'] = in_array( $switch_val, array( 'enabled', 'disabled' ), true ) ? $switch_val : 'disabled';
					// day_X integer if exists for reminder templates
					if ( isset( $apbgf_email_templates[ $key ]['day'] ) ) {
						$day_key = 'day_' . $template['id'];
						$day_val = isset( $_POST[ $day_key ] ) ? absint( $_POST[ $day_key ] ) : 1;
						$apbgf_email_templates[ $key ]['day'] = max( 1, $day_val );
					}
				}
			}

			update_option('apbgf_email_templates', $apbgf_email_templates );            
			$response['message'] = __('Email Notification saved successfully', 'appointment-and-booking-for-gravity-forms');
			$response['status'] = 'success';
			$response['settings'] = $apbgf_email_templates;

			echo wp_json_encode( $response );
			wp_die();
		}

		public function apbgf_codes() {
			
			return apply_filters( 'apbgf_codes', array(
				'{appointment_date}'    => esc_html__( 'date of appointment', 'appointment-and-booking-for-gravity-forms' ),
				'{appointment_time}'    => esc_html__( 'time of appointment', 'appointment-and-booking-for-gravity-forms' ),
				'{booking_ref_number}'  => esc_html__( 'booking reference number of appointment', 'appointment-and-booking-for-gravity-forms' ),
				'{client_email}'        => esc_html__( 'email of client', 'appointment-and-booking-for-gravity-forms' ),
				'{client_name}'         => esc_html__( 'name of client', 'appointment-and-booking-for-gravity-forms' ),
				'{client_phone}'        => esc_html__( 'contact no of client', 'appointment-and-booking-for-gravity-forms' ),
				'{company_address}'     => esc_html__( 'address of company', 'appointment-and-booking-for-gravity-forms' ),
				'{company_name}'        => esc_html__( 'name of company', 'appointment-and-booking-for-gravity-forms' ),
				'{company_email}'       => esc_html__( 'company email', 'appointment-and-booking-for-gravity-forms' ),
				'{company_phone}'       => esc_html__( 'company phone', 'appointment-and-booking-for-gravity-forms' ),
				'{company_website}'     => esc_html__( 'company website', 'appointment-and-booking-for-gravity-forms' ),
				'{service_name}'        => esc_html__( 'name of service', 'appointment-and-booking-for-gravity-forms' ),
				'{staff_name}'          => esc_html__( 'name of staff', 'appointment-and-booking-for-gravity-forms' ),
				'{total_slot}'          => esc_html__( 'total no. of slots', 'appointment-and-booking-for-gravity-forms' ),
				'{total_price}'         => esc_html__( 'total price of booking', 'appointment-and-booking-for-gravity-forms' ),
				'{sender_name}'         => esc_html__( 'sender name', 'appointment-and-booking-for-gravity-forms' ),
				'{sender_email}'        => esc_html__( 'sender email', 'appointment-and-booking-for-gravity-forms' )
			) );
		}

		public function register_menu() {
			add_submenu_page(
				'appointment-and-booking-for-gravity-forms',
				__( 'Email Notifications - Gravity Booking', 'appointment-and-booking-for-gravity-forms' ),
				__( 'Email Notifications', 'appointment-and-booking-for-gravity-forms' ),
				'manage_options',
				'apbgf-email',
				array( get_class($this), 'apbgf_email_templates' ),
				10
			);
		}

		public static function apbgf_email_templates() {
			if ( file_exists( get_stylesheet_directory() . '/gf-bookings/views/admin/email-templates.php' ) ) {
				require_once get_stylesheet_directory() . '/gf-bookings/views/admin/email-templates.php';
			} else {
				require_once APBGF_ADMIN_VIEW_PATH . 'email-templates.php';
			}

			// Add global PRO popup modal on the Email Notifications page, reusing the shared SVG artwork.
			if ( defined( 'APBGF_IMAGE_URL' ) ) {
				$apbgf_pro_popup_img = APBGF_IMAGE_URL . 'ProPopup.svg';
				$apbgf_pricing_url   = 'https://gravitybooking.com/pricing/?utm_source=plugin&utm_medium=email';
				if ( $apbgf_pro_popup_img ) {
					?>
					<div id="apbgf-pro-modal" class="apbgf-pro-modal" style="display:none;">
						<div class="apbgf-pro-modal-backdrop" style="position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:100000;"></div>
						<div class="apbgf-pro-modal-inner" style="position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);z-index:100001;max-width:640px;width:100%;overflow:hidden;border-radius:8px;">
							<div class="apbgf-pro-modal-content" style="position:relative;">
								<img src="<?php echo esc_url( $apbgf_pro_popup_img ); ?>" alt="<?php esc_attr_e( 'Upgrade to Pro', 'appointment-and-booking-for-gravity-forms' ); ?>" style="display:block;width:100%;height:auto;" />
								<a href="<?php echo esc_url( $apbgf_pricing_url ); ?>" target="_blank" rel="noopener noreferrer"
								   aria-label="<?php esc_attr_e( 'Buy Gravity Bookings', 'appointment-and-booking-for-gravity-forms' ); ?>"
								   style="position:absolute;left:31%;top:69%;width:38%;height:15%;background:transparent;border:none;outline:none;box-shadow:none;cursor:pointer;text-indent:-9999px;overflow:hidden;">
									<?php esc_html_e( 'Buy Gravity Bookings', 'appointment-and-booking-for-gravity-forms' ); ?>
								</a>
								<button type="button" class="apbgf-pro-modal-close-area" aria-label="<?php esc_attr_e( 'Close', 'appointment-and-booking-for-gravity-forms' ); ?>" style="position:absolute;top:0;right:0;width:15%;height:12%;background:transparent;border:none;outline:none;box-shadow:none;cursor:pointer;z-index:2;"></button>
							</div>
						</div>
					</div>
					<script type="text/javascript">
						(function() {
							function apbgfReady(fn) {
								if (document.readyState === 'loading') {
									document.addEventListener('DOMContentLoaded', fn);
								} else {
									fn();
								}
							}
							apbgfReady(function() {
								var modal     = document.getElementById('apbgf-pro-modal');
								if (!modal) { return; }
								var closeArea = modal.querySelector('.apbgf-pro-modal-close-area');
								var backdrop  = modal.querySelector('.apbgf-pro-modal-backdrop');

								function closeModal(e) {
									if (e) {
										e.preventDefault();
									}
									modal.style.display = 'none';
									document.body.classList.remove('apbgf-modal-open');
								}

								if (closeArea) {
									closeArea.addEventListener('click', closeModal);
								}
								if (backdrop) {
									backdrop.addEventListener('click', closeModal);
								}
							});
						})();
					</script>
					<?php
				}
			}
		}

		public static function get_appointment_details_formatted( $appointment_id, $type = 'staff' ) {

			$data = array();
			$staff_id = get_post_meta( $appointment_id, 'staff_id', true );         
			$customer_id = get_post_meta( $appointment_id, 'apbgf_user', true );
			$customer_phone = get_post_meta( $customer_id, 'phone', true);
			$location_id = get_post_meta( $appointment_id, 'location_id', true );
			$service_id = get_post_meta( $appointment_id, 'service_id', true );
			$time = get_post_meta( $appointment_id, 'time', true );            
			$time = apply_filters('apbgf_appointment_time_format', $time );           
			$formatted_date = '';
			$date = get_post_meta( $appointment_id, 'date', true );
			if ( is_array($date) && count($date) > 0 ) {
				foreach ( $date as $k => $date ) {
					if ( $k > 0 ) {
						$formatted_date .= '<br/>'; 
					}
					$formatted_date .= apply_filters('apbgf_appointment_date_format', $date);
				}
			} else {
				$formatted_date = apply_filters('apbgf_appointment_date_format', $date);
			}

			$cost = get_post_meta( $appointment_id, 'cost', true );
			$total_price = apbgf_price_format( $cost );
			$total_slot = get_post_meta( $appointment_id, 'slot', true );
			$status = get_post_meta( $appointment_id, 'status', true );
			$staff_name = get_the_title($staff_id);
			$customer_user_id = get_post_meta($appointment_id, 'wp_user', true);
			$staff_user_id = get_post_meta($staff_id, 'wp_user', true);
			$staff_userdata = get_userdata( $staff_user_id );
			if ( $staff_userdata ) {
				$staff_email = $staff_userdata->user_email;
			} else {
				$staff_email = '';
			}

			$customer_userdata = get_userdata( $customer_user_id );
			if ( $customer_userdata ) {
				$customer_email = $customer_userdata->user_email;
			} else {
				$customer_email = $customer_userdata->user_email;
			}
			
			$customer_name = $customer_userdata->first_name . ' ' . $customer_userdata->last_name;
			$location_name = ( 'all' != $location_id ) ? get_the_title($location_id) : '';
			$service_name = ( 'all' != $service_id ) ? get_the_title($service_id) : '';            

			$data['booking_ref_number'] = $appointment_id;
			$data['customer_user_id'] = $customer_user_id;            
			$data['staff_user_id'] = $staff_user_id;
			$data['staff_id'] = $staff_id;            
			$data['location_id'] = $location_id;
			$data['service_id'] = $service_id;
			$data['location_name'] = $location_name;
			$data['service_name'] = $service_name;
			$data['staff_name'] = $staff_name;
			$data['staff_email'] = $staff_email;
			$data['customer_name'] = $customer_name;
			$data['customer_email'] = $customer_email;
			$data['customer_phone'] = $customer_phone;   
			$data['date'] = $formatted_date;
			$data['time'] = $time;
			$data['status'] = $status;
			$data['total_price'] = $total_price;
			$data['total_slot'] = $total_slot;
			$data['company_addr'] = self::$apbgf_setting['apbgf_company_address'];
			$data['compnay_name'] = self::$apbgf_setting['apbgf_company_name'];
			$data['company_email'] = self::$apbgf_setting['apbgf_company_email'];
			$data['company_phone'] = self::$apbgf_setting['apbgf_company_number'];
			$data['company_website'] = self::$apbgf_setting['apbgf_company_website_url'];
			$data['sender_name'] = self::$apbgf_setting['apbgf_sender_name'];
			$data['sender_email'] = self::$apbgf_setting['apbgf_sender_email'];
			$data['footer'] = apply_filters('apbgf_email_template_footer', '');

			return apply_filters('apbgf_get_appointment_details_formatted', $data);
		}

		public static function send_reminder_notification( $template_id = '', $send_to = '' ) {

			$template_switch  = self::$email_templates[ $template_id ]['switch'];         

			if ( empty($send_to) || empty($template_id) || 'disabled' == $template_switch ) {
				return false;
			}

			$day = isset(self::$email_templates[ $template_id ]['day']) && ! empty(self::$email_templates[ $template_id ]['day']) ? self::$email_templates[ $template_id ]['day'] : 1;

			// Use WordPress timezone
			$timezone_string = apbgf_timezone_string(); // e.g., 'Pacific/Auckland'
			$datetime_zone = new DateTimeZone( $timezone_string );

			$current_datetime = new DateTime( 'now', $datetime_zone );
			$future_datetime  = clone $current_datetime;
			$future_datetime->modify( "+$day days" );

			$current_date = $current_datetime->format( 'Y-m-d' );
			$future_date  = $future_datetime->format( 'Y-m-d' );       

			$appointments = APBGF_Appointment::apbgf_appointments_by_date( $future_date );

			if ( is_array( $appointments ) && count($appointments) > 0 ) {              

				foreach ( $appointments as $appointment_id ) {
					
					$data = self::get_appointment_details_formatted($appointment_id);                   
			
					if ( 'staff' == $send_to ) {
						$to_email = $data['staff_email'];
					}

					if ( 'customer' == $send_to ) {
						$to_email = $data['customer_email'];
					}

					if ( 'admin' == $send_to ) {
						$to_email = apply_filters('apbgf_booking_notification_to_admin', get_option('admin_email'));
					}
						
					$template_title   = self::$email_templates[ $template_id ]['title'];
					$template_subject = self::$email_templates[ $template_id ]['subject'];
					$template_message = self::$email_templates[ $template_id ]['message'];

					$template_message = str_replace('{appointment_date}', $data['date'], $template_message);
					$template_message = str_replace('{appointment_time}', $data['time'], $template_message);
					$template_message = str_replace('{booking_ref_number}', $data['booking_ref_number'], $template_message);
					$template_message = str_replace('{client_email}', $data['customer_email'], $template_message);
					$template_message = str_replace('{client_name}', $data['customer_name'], $template_message);
					$template_message = str_replace('{client_phone}', $data['customer_phone'], $template_message);
					$template_message = str_replace('{company_address}', $data['company_addr'], $template_message);
					$template_message = str_replace('{company_name}', $data['compnay_name'], $template_message);
					$template_message = str_replace('{company_email}', $data['company_email'], $template_message);
					$template_message = str_replace('{company_phone}', $data['company_phone'], $template_message);
					$template_message = str_replace('{company_website}', $data['company_website'], $template_message);
					$template_message = str_replace('{location_name}', $data['location_name'], $template_message);
					$template_message = str_replace('{service_name}', $data['service_name'], $template_message);
					$template_message = str_replace('{staff_name}', $data['staff_name'], $template_message);
					$template_message = str_replace('{total_slot}', $data['total_slot'], $template_message);
					$template_message = str_replace('{total_price}', $data['total_price'], $template_message);          
					$template_message = str_replace('{sender_name}', $data['sender_name'], $template_message);
					$template_message = str_replace('{sender_email}', $data['sender_email'], $template_message);

					$template_message = apply_filters('apbgf_email_template_message', $template_message, $data);
					
					ob_start();
					if ( file_exists( get_stylesheet_directory() . '/gf-bookings/views/frontend/email-template.php' ) ) {
						require_once get_stylesheet_directory() . '/gf-bookings/views/frontend/email-template.php';
					} else {
						require APBGF_VIEW_PATH . 'email-template.php';
					}           
					$message = ob_get_clean();
					
					wp_mail( $to_email, $template_subject, $message, self::$header );
				}
			}           
		}

		public static function send_notification( $appointment_id = '', $template_id = '', $send_to = '' ) {

			$template_switch  = self::$email_templates[ $template_id ]['switch'];         

			if ( empty($send_to) || empty($appointment_id) || empty($template_id) || 'disabled' == $template_switch ) {
				return false;
			}

			$data = self::get_appointment_details_formatted($appointment_id);           
			
			if ( 'staff' == $send_to ) {
				$to_email = $data['staff_email'];
			}

			if ( 'customer' == $send_to ) {
				$to_email = apply_filters('apbgf_booking_notification_to_customer', $data['customer_email'], $template_id, $data);
			}

			if ( 'admin' == $send_to ) {
				$to_email = apply_filters('apbgf_booking_notification_to_admin', get_option('admin_email'));
			}
				
			$template_title   = self::$email_templates[ $template_id ]['title'];
			$template_subject = self::$email_templates[ $template_id ]['subject'];
			$template_message = self::$email_templates[ $template_id ]['message'];

			$template_message = str_replace('{appointment_date}', $data['date'], $template_message);
			$template_message = str_replace('{appointment_time}', $data['time'], $template_message);
			$template_message = str_replace('{booking_ref_number}', $data['booking_ref_number'], $template_message);
			$template_message = str_replace('{client_email}', $data['customer_email'], $template_message);
			$template_message = str_replace('{client_name}', $data['customer_name'], $template_message);
			$template_message = str_replace('{client_phone}', $data['customer_phone'], $template_message);
			$template_message = str_replace('{company_address}', $data['company_addr'], $template_message);
			$template_message = str_replace('{company_name}', $data['compnay_name'], $template_message);
			$template_message = str_replace('{company_email}', $data['company_email'], $template_message);
			$template_message = str_replace('{company_phone}', $data['company_phone'], $template_message);
			$template_message = str_replace('{company_website}', $data['company_website'], $template_message);
			$template_message = str_replace('{location_name}', $data['location_name'], $template_message);
			$template_message = str_replace('{service_name}', $data['service_name'], $template_message);
			$template_message = str_replace('{staff_name}', $data['staff_name'], $template_message);
			$template_message = str_replace('{total_slot}', $data['total_slot'], $template_message);
			$template_message = str_replace('{total_price}', $data['total_price'], $template_message);          
			$template_message = str_replace('{sender_name}', $data['sender_name'], $template_message);
			$template_message = str_replace('{sender_email}', $data['sender_email'], $template_message);

			$template_message = apply_filters('apbgf_email_template_message', $template_message, $data);
			
			ob_start();
			if ( file_exists( get_stylesheet_directory() . '/gf-bookings/views/frontend/email-template.php' ) ) {
				require_once get_stylesheet_directory() . '/gf-bookings/views/frontend/email-template.php';
			} else {
				require APBGF_VIEW_PATH . 'email-template.php';
			}           
			$message = ob_get_clean();
			
			return wp_mail( $to_email, $template_subject, $message, self::$header );            
		}

		public static function new_staff_notification( $user_id, $body, $pass ) {

			/* EMAIL NOTIFICATION STARTS */
			$userdata = get_userdata( $user_id );
			if ( $userdata ) {
				$to_email = $userdata->user_email;
				/**              
				 * GFB filter.
				 * 
				 * @since 1.0.0
				 */
				$subject = apply_filters( 'apbgf_new_staff_email_subject', __( 'New Staff Notification', 'appointment-and-booking-for-gravity-forms' ) );
				
				// Translators: %1$s %2$s, %3$s %4$s %5$s %6$s: %7$s %8$s %9$s %10$s to their strings respectively.
				$message = sprintf( '%1$s %2$s, %3$s %4$s %5$s %6$s: %7$s %8$s %9$s: %10$s %11$s %12$s: <a href="' . admin_url('edit.php?post_type=apbgf-staff') . '">%13$s</a>', __('Dear', 'appointment-and-booking-for-gravity-forms'), esc_attr( $userdata->display_name ), '<br />', esc_attr($body), '<br />', __('Email', 'appointment-and-booking-for-gravity-forms'), esc_attr($userdata->user_email), '<br />', __('Password', 'appointment-and-booking-for-gravity-forms'), esc_attr( $pass ), '<br/>', __('Login URL', 'appointment-and-booking-for-gravity-forms'), __('Click here to login', 'appointment-and-booking-for-gravity-forms') );

				/**              
				 * GFB filter.
				 * 
				 * @since 1.0.0
				 */
				$message = apply_filters( 'apbgf_new_staff_email_message', $message);

				// sending notification email to registered user for fundraiser role.
				return wp_mail( $to_email, $subject, $message, self::$header );
			}

			return false;           
		}

		public static function new_customer_notification( $user_id, $body, $pass ) {

			/* EMAIL NOTIFICATION STARTS */
			$userdata = get_userdata( $user_id );
			if ( $userdata ) {
				$to_email = $userdata->user_email;
				/**              
				 * GFB filter.
				 * 
				 * @since 1.0.0
				 */
				$subject = apply_filters( 'apbgf_new_customer_email_subject', __( 'New Customer Notification', 'appointment-and-booking-for-gravity-forms' ) );
				
				// Translators: %1$s %2$s, %3$s %4$s %5$s %6$s: %7$s %8$s %9$s %10$s to their strings respectively.
				$message = sprintf( '%1$s %2$s, %3$s %4$s %5$s %6$s: %7$s %8$s %9$s: %10$s %11$s %12$s: <a href="' . esc_url( wp_login_url() ) . '">%13$s</a>', __('Dear', 'appointment-and-booking-for-gravity-forms'), esc_attr( $userdata->display_name ), '<br />', esc_attr($body), '<br />', __('Email', 'appointment-and-booking-for-gravity-forms'), esc_attr($userdata->user_email), '<br />', __('Password', 'appointment-and-booking-for-gravity-forms'), esc_attr( $pass ), '<br/>', __('Login URL', 'appointment-and-booking-for-gravity-forms'), __('Click here to login', 'appointment-and-booking-for-gravity-forms') );

				/**              
				 * GFB filter.
				 * 
				 * @since 1.0.0
				 */
				$message = apply_filters( 'apbgf_new_customer_email_message', $message);
				
				return wp_mail( $to_email, $subject, $message, self::$header );
			}

			return false;           
		}


		/**
		 * Singleton Class Instatnce.
		 */
		public static function get_instance() {
			if ( null === self::$instance ) {
				self::$instance = new APBGF_Email();
			}

			return self::$instance;
		}
	}

	global $apbgfEmail;

	$apbgfEmail = APBGF_Email::get_instance();
}
