<?php
/**
 * ============================================
 * FILE: includes/Emails/Customer/MeetingConfirmed.php
 * Customer Meeting Confirmed 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\Models\MeetingType;
use RadiusTheme\RadiusBooking\Resources\AppointmentResource;

/**
 * Class MeetingConfirmed
 *
 * Handles the "Meeting Confirmed" email notification sent to customers.
 *
 * @package RadiusTheme\RadiusBooking\Emails\Customer
 */
class MeetingConfirmed extends BaseEmail {

	/**
	 * Constructor to initialize the email properties.
	 */
	public function __construct() {
		$this->id             = 'customer_meeting_confirmed';
		$this->title          = __( 'Meeting Confirmed - Customer', 'radius-booking' );
		$this->description    = __( 'Sent to customers when their meeting is confirmed', 'radius-booking' );
		$this->tooltip        = __( 'This email is sent automatically when a meeting is confirmed', 'radius-booking' );
		$this->recipient_type = 'customer';
		$this->template_html  = 'customer/meeting-confirmed.php';
		$this->status         = 'confirmed';

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

	/**
	 * Get the default email notification settings for meeting confirmation.
	 *
	 * @return array The default email settings.
	 */
	public function get_default_settings() {
		return array(
			'enabled'            => true,
			'subject'            => __( 'Meeting Confirmed - {meeting_type_name}', 'radius-booking' ),
			'heading'            => __( 'Your Meeting is Confirmed!', 'radius-booking' ),
			'additional_content' => __( "Hi {customer_name},\n\nGreat news! Your meeting has been confirmed.\n\nWe look forward to seeing you on {booking_date} at {time}.", 'radius-booking' ),
			'footer_text'        => __( 'If you need to reschedule or cancel, please do so as soon as possible.', 'radius-booking' ),
			'button_text'        => '',
			'button_url'         => '',
			'use_queue'          => false,
			'cc_staff'           => false,
			'bcc_emails'         => array(),
			'attachments'        => array(),
		);
	}

	/**
	 * Prepare the email data for sending.
	 *
	 * @param array $args The arguments passed to the email trigger.
	 * @return array|false The prepared email data or false on failure.
	 */
	protected function prepare_email_data( $args ) {
		if ( empty( $args[0] ) ) {
			return false;
		}
		$appointment_id = $args[0] instanceof Appointment ? $args[0]->id : $args[0];
		$booking        = $this->get_booking( $appointment_id );
		if ( ! $booking ) {
			return false;
		}

		$meeting_type = $this->get_meeting_type( $booking );

		// Get customer info safely.
		$customer = isset( $booking['customer'] ) && is_object( $booking['customer'] ) ? $booking['customer']->customer_info : null;

		if ( ! $customer ) {
			return false;
		}

		$to = $customer['email'] ?? '';

		// Get meeting link from integration (Google Meet / Zoom) or fallback to location_details.
		$ml               = isset( $booking['meeting_link'] ) ? (array) $booking['meeting_link'] : array();
		$integration_link = ! empty( $ml['join_url'] ) ? $ml['join_url'] : ( $meeting_type && ! empty( $meeting_type->location_details ) ? $meeting_type->location_details : '' );
		$ml_provider      = $ml['provider'] ?? '';

		// Get payment info.
		$payment = isset( $booking['payment'] ) ? (array) $booking['payment'] : null;

		// Prepare merge tags
		$merge_tags = array(
			'customer_name'     => $customer['name'] ?? '',
			'customer_email'    => $customer['email'] ?? '',
			'customer_phone'    => $customer['phone'] ?? '',
			'staff_name'        => $booking['employee_name'] ?? '',
			'staff_email'       => $booking['employee_email'] ?? '',
			'meeting_type_name' => $meeting_type ? $meeting_type->name : '',
			'booking_date'      => date_i18n( 'l, F j, Y', strtotime( $booking['appointment_date'] ) ),
			'time'              => date_i18n( 'g:i A', strtotime( $booking['start_time'] ) ),
			'end_time'          => date_i18n( 'g:i A', strtotime( $booking['end_time'] ?? '' ) ),
			'duration'          => $meeting_type ? $meeting_type->duration . ' minutes' : '',
			'meeting_link'      => $integration_link,
			'meeting_provider'  => $ml_provider,
			'location'          => $meeting_type ? $this->get_meeting_location( $meeting_type ) : '',
			'location_type'     => $meeting_type ? ( $meeting_type->location_type ?? '' ) : '',
			'status'            => $booking['status'] ?? '',
			'notes'             => $booking['notes'] ?? '',
			'booking_url'       => $this->get_booking_url( $booking['id'] ),
			'meeting_price'     => $payment ? ( $payment['total_amount'] ?? '0' ) : ( $meeting_type ? $meeting_type->price : '0' ),
			'payment_status'    => $payment['status'] ?? 'pending',
			'payment_method'    => $payment['payment_method'] ?? 'offline',
			'currency_symbol'   => function_exists( 'get_rtrb_currency_symbol' ) ? get_rtrb_currency_symbol() : '$',
		);

		// Add CC if needed
		$cc = array();
		if ( $this->settings['cc_staff'] && ! empty( $booking['employee_email'] ) ) {
			$cc[] = $booking['employee_email'];
		}

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

	/**
	 * Retrieve and transform the booking data for the given appointment ID.
	 *
	 * @param int|null $appointment_id The appointment ID.
	 * @return array|null The transformed booking data or null if not found.
	 */
	private function get_booking( $appointment_id = null ) {
		$appointment = Appointment::find( $appointment_id );

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

	/**
	 * Get the meeting type from booking data.
	 *
	 * @param array $booking The booking data.
	 * @return MeetingType|null The meeting type or null.
	 */
	private function get_meeting_type( $booking ) {
		$appointment = Appointment::find( $booking['id'] );
		if ( $appointment && ! empty( $appointment->meeting_type_id ) ) {
			return MeetingType::find( $appointment->meeting_type_id );
		}

		return null;
	}

	/**
	 * Get the meeting location based on the meeting type.
	 *
	 * @param MeetingType $meeting_type The meeting type.
	 * @return string The location string.
	 */
	private function get_meeting_location( $meeting_type ) {
		if ( ! empty( $meeting_type->location_type ) ) {
			switch ( $meeting_type->location_type ) {
				case 'google_meet':
					return __( 'Google Meet', 'radius-booking' );
				case 'zoom':
					return __( 'Zoom', 'radius-booking' );
				case 'in_person':
					return ! empty( $meeting_type->location_details ) ? $meeting_type->location_details : __( 'In Person', 'radius-booking' );
				case 'phone':
					return __( 'Phone Call', 'radius-booking' );
				default:
					return ! empty( $meeting_type->location_details ) ? $meeting_type->location_details : '';
			}
		}

		return '';
	}

	/**
	 * Get the booking URL for the customer.
	 *
	 * @param int $booking_id The booking ID.
	 * @return string The booking URL.
	 */
	private function get_booking_url( $booking_id ) {
		return get_site_url() . '/my-bookings/' . $booking_id;
	}
}
