<?php
/**
 * ============================================
 * FILE: includes/Emails/Admin/NewMeeting.php
 * Admin New Meeting Email
 * ============================================
 *
 * @package RadiusTheme\RadiusBooking\Emails\Admin
 */

namespace RadiusTheme\RadiusBooking\Emails\Admin;

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 NewMeeting
 *
 * Handles the "New Meeting" email notification sent to admin when a new
 * meeting booking is created.
 *
 * @package RadiusTheme\RadiusBooking\Emails\Admin
 */
class NewMeeting extends BaseEmail {

	/**
	 * Constructor to initialize the email properties.
	 */
	public function __construct() {
		$this->id             = 'admin_new_meeting';
		$this->title          = __( 'New Meeting - Admin', 'radius-booking' );
		$this->description    = __( 'Sent to admin when a new meeting booking is created', 'radius-booking' );
		$this->tooltip        = __( 'This email is sent automatically to the admin when any new meeting booking is created in the system', 'radius-booking' );
		$this->recipient_type = 'admin';
		$this->template_html  = 'admin/new-meeting.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 meeting bookings.
	 *
	 * @return array
	 */
	public function get_default_settings() {
		return array(
			'enabled'            => true,
			'subject'            => __( 'New Meeting Booking - {meeting_type_name}', 'radius-booking' ),
			'heading'            => __( 'New Meeting Notification', 'radius-booking' ),
			'additional_content' => __( "Hello Admin,\n\nA new meeting booking has been created in the system.\n\nPlease review the details below and take necessary action.", 'radius-booking' ),
			'footer_text'        => __( 'You can manage this meeting 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 meeting notification.
	 *
	 * @param array $args The arguments passed to the trigger action.
	 *
	 * @return array|false The prepared email data or false if booking not found
	 *                     or booking is not a meeting.
	 */
	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 meeting bookings. The stored booking_type for a meeting
		// is 'meeting' (set explicitly in MeetingBookingService); service rows
		// fall through to the DB column default 'service_booking'.
		$booking_type = $booking['booking_type'] ?? 'service_booking';
		if ( 'meeting' !== $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();

		// Meeting type lookup (for duration, price, location type fallback).
		$meeting_type = null;
		if ( ! empty( $booking['meeting_type_id'] ) ) {
			$meeting_type = MeetingType::find( $booking['meeting_type_id'] );
		}

		// Meeting link from Zoom/Google Meet integration, fallback to
		// meeting type's own location_details (e.g. static Zoom link).
		$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 : '' );
		$meeting_provider = $ml['provider'] ?? '';

		$duration_minutes = isset( $booking['customer']->duration )
			? intval( $booking['customer']->duration ) / 60
			: ( $meeting_type ? (int) $meeting_type->duration : 0 );

		// Resolve meeting price. Order: dynamic-pricing snapshot → customer.price
		// (>0 only; meetings normally store 0 here since there's no row in
		// employees_services) → meeting_type.price → 0.
		$customer_price = (float) ( $booking['customer']->price ?? 0 );
		if ( ! empty( $booking['dynamic_pricing']['final_price'] ) ) {
			$price_value = (float) $booking['dynamic_pricing']['final_price'];
		} elseif ( $customer_price > 0 ) {
			$price_value = $customer_price;
		} elseif ( $meeting_type ) {
			$price_value = (float) $meeting_type->price;
		} else {
			$price_value = 0.0;
		}

		$merge_tags = array(
			'admin_name'        => 'Admin',
			'site_name'         => get_bloginfo( 'name' ),
			'customer_name'     => $customer['name'] ?? '',
			'customer_email'    => $customer['email'] ?? '',
			'customer_phone'    => $customer['phone'] ?? '',
			'host_name'         => $booking['employee_name'] ?? '',
			'host_email'        => $booking['employee_email'] ?? '',
			'meeting_type_name' => $booking['meeting_type_name'] ?? ( $meeting_type ? $meeting_type->name : '' ),
			'booking_id'        => $booking['customer']->id ?? '',
			'booking_date'      => ! empty( $booking['appointment_date'] ) ? date_i18n( 'l, F j, Y', strtotime( $booking['appointment_date'] ) ) : '',
			'time'              => ! empty( $booking['start_time'] ) ? date_i18n( 'g:i A', strtotime( $booking['start_time'] ) ) : '',
			'end_time'          => ! empty( $booking['end_time'] ) ? date_i18n( 'g:i A', strtotime( $booking['end_time'] ) ) : '',
			'duration'          => $duration_minutes ? $duration_minutes . ' ' . __( 'minutes', 'radius-booking' ) : '',
			'timezone'          => wp_timezone_string(),
			'meeting_link'      => $integration_link,
			'meeting_provider'  => $meeting_provider,
			'location_type'     => $meeting_type ? ( $meeting_type->location_type ?? '' ) : '',
			'price'             => $get_currency . number_format( $price_value, 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|null The transformed booking data.
	 */
	private function get_booking( $booking_id, $appointment_id = null ) {
		$appointment = Appointment::find( $appointment_id );
		if ( ! $appointment ) {
			return null;
		}
		return ( new AppointmentResource() )->transform( $appointment );
	}
}