<?php
/**
 * ============================================
 * FILE: includes/Emails/Customer/AppointmentCancelled.php
 * Customer Appointment Cancelled Email
 * ============================================
 */

namespace RadiusTheme\RadiusBooking\Emails\Customer;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}
use RadiusTheme\RadiusBooking\Abstracts\BaseEmail;
use RadiusTheme\RadiusBooking\Models\Appointment;
use RadiusTheme\RadiusBooking\Resources\AppointmentResource;

/**
 * Class AppointmentCancelled
 *
 * Handles the "Appointment Cancelled" email notification sent to customers.
 *
 * @package RadiusTheme\RadiusBooking\Emails\Customer
 */
class AppointmentCancelled extends BaseEmail {

	/**
	 * Constructor to initialize the email properties.
	 */
	public function __construct() {
		$this->id             = 'customer_appointment_cancelled';
		$this->title          = __( 'Appointment Cancelled - Customer', 'radius-booking' );
		$this->description    = __( 'Sent to customers when their appointment is cancelled', 'radius-booking' );
		$this->tooltip        = __( 'This email is sent automatically when an appointment is cancelled', 'radius-booking' );
		$this->recipient_type = 'customer';
		$this->template_html  = 'customer/appointment-cancelled.php';
		$this->status         = 'cancelled';

		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_appointment_status_cancelled';
	}

	/**
	 * 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 The default email settings.
	 */
	public function get_default_settings() {
		return array(
			'enabled'            => true,
			'subject'            => __( 'Appointment Cancelled - {service_name}', 'radius-booking' ),
			'heading'            => __( 'Appointment Cancelled', 'radius-booking' ),
			'additional_content' => __( "Hi {customer_name},\n\nYour appointment has been cancelled.\n\nIf you have any questions or would like to reschedule, please contact us.", 'radius-booking' ),
			'footer_text'        => __( 'We hope to serve you again soon!', 'radius-booking' ),
			'button_text'        => '',
			'button_url'         => '',
			'use_queue'          => false,
			'cc_staff'           => false,
			'bcc_emails'         => array(),
			'attachments'        => array(),
		);
	}

	/**
	 * Prepare the email data for sending.
	 *
	 * This method gathers and formats the necessary data to populate
	 * the email template for a cancelled appointment notification.
	 *
	 * @since 1.0.0
	 *
	 * @param array $args The arguments passed to the trigger action.
	 *
	 * @return array|false The prepared email data array, or false on failure.
	 */
	protected function prepare_email_data( $args ) {
		if ( empty( $args[0] ) ) {
			return false;
		}
		$appointment_id = $args[0];
		$booking        = $this->get_booking( $appointment_id );

		if ( ! $booking ) {
			return false;
		}

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

		$merge_tags = array(
			'customer_name'       => $customer['name'],
			'customer_email'      => $customer['email'],
			'customer_phone'      => $customer['phone'],
			'service_name'        => $booking['service_name'],
			'staff_name'          => $booking['employee_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'              => 'Cancelled',
			'cancellation_reason' => isset( $booking['cancellation_reason'] ) ? $booking['cancellation_reason'] : '',
			'notes'               => $booking['notes'],
			'booking_url'         => get_site_url() . '/booking/',
		);

		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 and transform an appointment record by its ID.
	 *
	 * This helper method fetches an appointment using the Appointment model,
	 * and returns a transformed resource representation suitable for use in
	 * email templates or API responses.
	 *
	 * @since 1.0.0
	 *
	 * @param int|null $appointment_id Optional. The ID of the appointment to fetch.
	 *
	 * @return array|false The transformed appointment data array, or false if not found.
	 */
	private function get_booking( $appointment_id = null ) {
		$appointment = Appointment::find( $appointment_id );
		return ( new AppointmentResource() )->transform( $appointment );
	}
}
