<?php

namespace SmartSlotAppointmentScheduler;

if (! defined('ABSPATH')) {
	exit;
}

if (! class_exists('\SmartSlotAppointmentScheduler\Send_Mail')) {
	/**
	 * Class to send appointment confirmation mails.
	 */
	class Send_Mail {
		private $to_email;
		private $user_name;
		private $token;
		private $appointment_date;
		private $appointment_time;
		private $category_id;

		/**
		 * Values assigned.
		 */
		public function __construct($data) {
			$this->to_email         = sanitize_email($data['email']);
			$this->user_name        = sanitize_text_field($data['first_name'] . ' ' . $data['last_name']);
			$this->token            = sanitize_text_field($data['token_number']);
			$this->appointment_date = sanitize_text_field($data['appointment_date']);
			$this->appointment_time = sanitize_text_field($data['appointment_time']);

			$this->trigger_email();
		}

		/**
		 * Get template from option field and update the values.
		 */
		public static function get_template($data) {
			$email_body = get_option('booking_schedule_email_content');

			if (empty($email_body)) {
				$email_body = 'Hi {name}, your appointment is on {date_time} and your token is {token_number}.';
			}

			$email_body = str_replace('{name}', $data['first_name'], $email_body);
			$email_body = str_replace('{date_time}', $data['date'], $email_body);
			$email_body = str_replace('{token_number}', $data['token_number'], $email_body);

			return $email_body;
		}

		/**
		 * HTML template for the email template.
		 */
		private function email_template() {
			$email_footer  = get_option('booking_schedule_appintment_email_footer');
			$email_subject = get_option('booking_schedule_appintment_email_subject');
			$sender_name   = get_option(
				'booking_schedule_sender_name',
				get_bloginfo('name')
			);

			$booked_time    = $this->appointment_date . ' ' . $this->appointment_time;
			$timestamp      = strtotime($booked_time);
			$formatted_date = wp_date('F j, Y g:i a', $timestamp);

			ob_start();
			?>
			<!DOCTYPE html>
			<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
			<head>
				<meta charset="UTF-8" />
				<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
				<title><?php echo esc_html($email_subject); ?></title>
			</head>
			<body style="margin:0; padding:0; font-family: Arial, sans-serif; background-color: #f4f4f4;">
				<table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f4f4f4;">
					<tr>
						<td style="align:center">
							<table width="600" cellpadding="0" cellspacing="0" style="background-color: #ffffff; margin-top: 30px; border-radius: 8px; overflow: hidden;">
								<!-- Header -->
								<tr>
									<td style="background-color: #d21d00; padding: 20px; color: #ffffff; text-align: center;">
										<h1 style="margin: 0; font-size: 24px;"><?php echo esc_html($email_subject); ?></h1>
										<p style="margin: 5px 0 0; font-size: 16px;">
											<?php
											/* translators: %s: Site or sender name. */
											echo esc_html(
												sprintf(
													/* translators: %s: Site or sender name. */
													__(
														'Thank you for booking with %s',
														'smartslot-appointment-scheduler'
													),
													$sender_name
												)
											);
											?>
										</p>
									</td>
								</tr>

								<!-- Body Content -->
								<tr>
									<td style="padding: 30px;">
										<?php
										echo wp_kses_post(
											self::get_template(
												[
													'first_name'   => $this->user_name,
													'date'         => $formatted_date,
													'token_number' => $this->token,
												]
											)
										);
										?>
									</td>
								</tr>

								<!-- Footer -->
								<?php if (! empty($email_footer)) : ?>
								<tr>
									<td style="background-color: #f0f0f0; padding: 20px; font-size: 13px; color: #666; text-align: center;">
										<?php echo wp_kses_post($email_footer); ?>
									</td>
								</tr>
								<?php endif; ?>
							</table>
						</td>
					</tr>
				</table>
			</body>
			</html>
			<?php

			return ob_get_clean();
		}

		/**
		 * Get category names from term IDs.
		 *
		 * @param array|string $category_id Term ID array or JSON-encoded string.
		 * @return array List of category names.
		 */
		private function get_term($category_id) {
			$category_names = [];

			// Decode if JSON string.
			if (! is_array($category_id)) {
				$category_id = json_decode($category_id, true);
			}

			if (! is_array($category_id)) {
				return $category_names;
			}

			foreach ($category_id as $id) {
				$term = get_term((int) $id);

				if ($term && ! is_wp_error($term)) {
					$category_names[] = $term->name;
				}
			}

			return $category_names;
		}

		/**
		 * Function to trigger mail.
		 */
		private function trigger_email() {
			$to = $this->to_email;
			$email_header = get_option('booking_schedule_appintment_email_from');
			$sender_name  = get_option(
				'booking_schedule_sender_name',
				get_bloginfo('name')
			);
			$email_subject = get_option('booking_schedule_appintment_email_subject');

			$message = $this->email_template();

			$headers = [
				'Content-Type: text/html; charset=UTF-8',
				'From: ' . $sender_name . ' <' . $email_header . '>',
			];

			wp_mail($to, $email_subject, $message, $headers);
		}
	}
}
