<?php
/**
 * ============================================
 * FILE: includes/Emails/Admin/NewAppointment.php
 * Admin New Appointment Email
 * ============================================
 */

namespace RadiusTheme\RadiusBooking\Emails\Admin;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}
/**
 * Class NewAppointment
 *
 * Handles the "New Appointment" email notification sent to admin.
 *
 * @package RadiusTheme\RadiusBooking\Emails\Admin
 */

use RadiusTheme\RadiusBooking\Abstracts\BaseEmail;
use RadiusTheme\RadiusBooking\Models\Appointment;
use RadiusTheme\RadiusBooking\Resources\AppointmentResource;

/**
 * Class NewAppointment
 *
 * Handles the "New Appointment" email notification sent to admin.
 *
 * @package RadiusTheme\RadiusBooking\Emails\Admin
 */
class NewAppointment extends BaseEmail {

	/**
	 * Constructor to initialize the email properties.
	 */
	public function __construct() {
		$this->id             = 'admin_new_appointment';
		$this->title          = __( 'New Appointment - Admin', 'radius-booking' );
		$this->description    = __( 'Sent to admin when a new appointment is created', 'radius-booking' );
		$this->tooltip        = __( 'This email is sent automatically to the admin when any new appointment is created in the system', 'radius-booking' );
		$this->recipient_type = 'admin';
		$this->template_html  = 'admin/new-appointment.php';
		$this->status         = 'created';
		parent::__construct();
	}

	/**
	 * Get the unique identifier for the email.
	 *
	 * @return string
	 */
	public function get_id() {
		return $this->id;
	}

	/**
	 * Get the trigger action for the email.
	 *
	 * @return string
	 */
	public function get_trigger_action() {
		return 'radius_booking_booking_created';
	}

	/**
	 * Get the default email notification settings for new appointments.
	 *
	 * This method returns an associative array containing the default
	 * configuration options for the "New Appointment" email template.
	 *
	 * @return array
	 */
	public function get_default_settings() {
		return array(
			'enabled'            => true,
			'subject'            => __( 'New Appointment Received - {service_name}', 'radius-booking' ),
			'heading'            => __( 'New Appointment Notification', 'radius-booking' ),
			'additional_content' => __( "Hello Admin,\n\nA new appointment has been created in the system.\n\nPlease review the details below and take necessary action.", 'radius-booking' ),
			'footer_text'        => __( 'You can manage this appointment from the admin dashboard.', 'radius-booking' ),
			'button_text'        => '',
			'button_url'         => '',
			'use_queue'          => false,
			'admin_emails'       => array( get_option( 'admin_email' ) ),
			'bcc_emails'         => array(),
			'attachments'        => array(),
			'include_calendar'   => false,
		);
	}

	/**
	 * Prepare email data for sending the new appointment notification.
	 *
	 * @param array $args The arguments passed to the trigger action.
	 *
	 * @return array|false The prepared email data or false if booking not found.
	 */
	protected function prepare_email_data( $args ) {
		$booking_id     = is_object( $args[0] ) ? $args[0]->id : $args[0];
		$appointment_id = is_object( $args[0] ) ? $args[0]->get_appointment_id() : null;
		$booking        = $this->get_booking( $booking_id, $appointment_id );

		if ( ! $booking ) {
			return false;
		}

		// Only handle service bookings. Meeting and event bookings are handled
		// by Admin\NewMeeting and Admin\NewEvent so each booking type gets a
		// layout and merge tags that match its data shape.
		$booking_type = $booking['booking_type'] ?? 'service_booking';
		if ( 'service_booking' !== $booking_type ) {
			return false;
		}

		// Get admin emails from settings or default to site admin
		$admin_emails = isset( $this->settings['admin_emails'] ) && ! empty( $this->settings['admin_emails'] )
			? $this->settings['admin_emails']
			: array( get_option( 'admin_email' ) );

		$to = is_array( $admin_emails ) ? implode( ',', $admin_emails ) : $admin_emails;

		$customer     = $booking['customer']->customer_info;
		$get_currency = get_rtrb_currency_symbol();

		$merge_tags = array(
			'admin_name'       => 'Admin',
			'site_name'        => get_bloginfo( 'name' ),
			'customer_name'    => $customer['name'],
			'customer_email'   => $customer['email'],
			'customer_phone'   => $customer['phone'],
			'staff_name'       => $booking['employee_name'],
			'staff_email'      => isset( $booking['employee_email'] ) ? $booking['employee_email'] : '',
			'staff_phone'      => isset( $booking['employee_phone'] ) ? $booking['employee_phone'] : '',
			'service_name'     => $booking['service_name'],
			'booking_id'       => $booking['customer']->id,
			'booking_date'     => date_i18n( 'l, F j, Y', strtotime( $booking['appointment_date'] ) ),
			'time'             => date_i18n( 'g:i A', strtotime( $booking['start_time'] ) ),
			'duration'         => $booking['customer']->duration / 60 . ' minutes',
			'location'         => !empty($booking['location_info']['address']) ? $booking['location_info']['address'] : '' ,
			'price'            => $get_currency . number_format( ! empty( $booking['dynamic_pricing']['final_price'] ) ? $booking['dynamic_pricing']['final_price'] : $booking['customer']->price, 2 ),
			'status'           => $booking['status'] ?? 'Pending',
			'notes'            => $booking['notes'],
			'booking_url'      => admin_url( 'admin.php?page=radius-bookings&booking_id=' . $booking['customer']->id ),
			'all_bookings_url' => admin_url( 'admin.php?page=radius-bookings' ),
		);

		return array(
			'to'          => $to,
			'cc'          => array(),
			'bcc'         => isset( $this->settings['bcc_emails'] ) ? $this->settings['bcc_emails'] : array(),
			'merge_tags'  => $merge_tags,
			'data'        => $booking,
			'attachments' => array(),
		);
	}

	/**
	 * Retrieve booking details and transform them into a resource format.
	 *
	 * @param int $booking_id The ID of the booking.
	 * @param int|null $appointment_id The ID of the appointment (optional).
	 *
	 * @return array The transformed booking data.
	 */
	private function get_booking( $booking_id, $appointment_id = null ) {
		$appointment = Appointment::find( $appointment_id );

		return ( new AppointmentResource() )->transform( $appointment );
	}
}
