<?php
/**
 * ============================================
 * FILE: includes/Emails/Employee/AppointmentCompleted.php
 * Employee Appointment Completed Email
 * ============================================
 */

namespace RadiusTheme\RadiusBooking\Emails\Employee;

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

/**
 * Class AppointmentCompleted
 *
 * Handles the "Appointment Completed" email notification sent to employees.
 *
 * @package RadiusTheme\RadiusBooking\Emails\Employee
 */
class AppointmentCompleted extends BaseEmail {

	/**
	 * Constructor to initialize the email properties.
	 */
	public function __construct() {
		$this->id             = 'employee_appointment_completed';
		$this->title          = __( 'Appointment Completed - Employee', 'radius-booking' );
		$this->description    = __( 'Sent to employees when an appointment is completed', 'radius-booking' );
		$this->tooltip        = __( 'This email is sent automatically when an appointment is marked as completed', 'radius-booking' );
		$this->recipient_type = 'employee';
		$this->template_html  = 'employee/appointment-completed.php';
		$this->status         = 'completed';

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

	/**
	 * Get the default email notification settings for appointment completion.
	 *
	 * This method returns an associative array containing the default
	 * configuration options for the "Appointment Completed" email template.
	 * It includes subject line, heading, body content, footer text, and
	 * additional options like queue usage, BCC, and attachments.
	 *
	 * Available placeholders in text fields:
	 * - {service_name} : The name of the service.
	 * - {staff_name}   : The name of the staff member.
	 *
	 * @since 1.0.0
	 *
	 * @return array {
	 *     @type bool     $enabled            Whether the email notification is enabled by default.
	 *     @type string   $subject            The email subject line.
	 *     @type string   $heading            The email heading/title.
	 *     @type string   $additional_content Additional message content or email body.
	 *     @type string   $footer_text        Optional custom footer text.
	 *     @type string   $button_text        Optional call-to-action button text.
	 *     @type string   $button_url         Optional call-to-action button URL.
	 *     @type bool     $use_queue          Whether to send the email using a background queue.
	 *     @type array    $bcc_emails         List of BCC (blind carbon copy) email addresses.
	 *     @type array    $attachments        List of file paths for attachments.
	 * }
	 */
	public function get_default_settings() {
		return array(
			'enabled'            => true,
			'subject'            => __( 'Appointment Completed - {service_name}', 'radius-booking' ),
			'heading'            => __( 'Appointment Completed', 'radius-booking' ),
			'additional_content' => __( "Hello {staff_name},\n\nAn appointment has been marked as completed.\n\nPlease find the details below for your records.", 'radius-booking' ),
			'footer_text'        => '',
			'button_text'        => '',
			'button_url'         => '',
			'use_queue'          => false,
			'bcc_emails'         => array(),
			'attachments'        => array(),
		);
	}

	/**
	 * Prepare and format email data for an appointment notification.
	 *
	 * This method collects all relevant appointment, customer, and service
	 * details required to populate an email notification. It builds a
	 * structured array including recipient details, merge tags, and attachments.
	 *
	 * The merge tags can be used inside the email subject, heading, or body
	 * to dynamically insert appointment data.
	 *
	 * Supported merge tags:
	 * - {staff_name}
	 * - {customer_name}
	 * - {customer_email}
	 * - {customer_phone}
	 * - {service_name}
	 * - {booking_id}
	 * - {booking_date}
	 * - {time}
	 * - {duration}
	 * - {location}
	 * - {price}
	 * - {status}
	 * - {notes}
	 * - {booking_url}
	 *
	 * @since 1.0.0
	 *
	 * @param array $args {
	 *     Arguments passed to the email trigger callback.
	 *
	 *     @type int $0 The appointment ID.
	 * }
	 *
	 * @return array|false {
	 *     Returns an array of email data if valid, otherwise false.
	 *
	 *     @type string $to            Recipient email address.
	 *     @type array  $cc            CC email addresses.
	 *     @type array  $bcc           BCC email addresses.
	 *     @type array  $merge_tags    Key-value pairs used for placeholder replacements.
	 *     @type array  $data          Raw booking data (transformed resource).
	 *     @type array  $attachments   List of attachments for the email.
	 * }
	 */
	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           = isset( $booking['employee_email'] ) ? $booking['employee_email'] : get_option( 'admin_email' );
		$customer     = $booking['customer']->customer_info;
		$get_currency = get_rtrb_currency_symbol();

		$merge_tags = array(
			'staff_name'     => $booking['employee_name'],
			'customer_name'  => $customer['name'],
			'customer_email' => $customer['email'],
			'customer_phone' => $customer['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'         => 'Completed',
			'notes'          => $booking['notes'],
			'booking_url'    => admin_url( 'admin.php?page=radius-bookings&status=completed' ),
		);

		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 );
	}
}
