<?php

namespace Limb_Chatbot\Includes\Services\Notifications\Channels;

use Limb_Chatbot\Includes\Data_Objects\Chatbot_User;
use Limb_Chatbot\Includes\Interfaces\Notification_Channel_Interface;
use Limb_Chatbot\Includes\Services\Notifications\Notification_Envelope;

/**
 * Email notification channel.
 *
 * Sends notifications via wp_mail to the Chatbot_User's email (WP user or meta).
 *
 * @package Limb_Chatbot\Includes\Services\Notifications\Channels
 * @since 1.0.15
 */
class Email_Notification_Channel implements Notification_Channel_Interface {

	/**
	 * @inheritDoc
	 */
	public function get_channel_key(): string {
		return 'email';
	}

	/**
	 * @inheritDoc
	 */
	public function send( Chatbot_User $recipient, Notification_Envelope $envelope ): bool {
		$to = $this->get_recipient_email( $recipient );
		if ( empty( $to ) || ! is_email( $to ) ) {
			return false;
		}

		$subject = $envelope->get_subject();
		$body    = $envelope->get_body();
		$headers = $this->get_headers( $envelope );

		return (bool) wp_mail( $to, $subject, $body, $headers );
	}

	/**
	 * @inheritDoc
	 */
	public function can_deliver_to( Chatbot_User $recipient ): bool {
		$email = $this->get_recipient_email( $recipient );

		return ! empty( $email ) && is_email( $email );
	}

	/**
	 * Get email address for the chatbot user.
	 *
	 * @param  Chatbot_User  $recipient  Chatbot user.
	 *
	 * @return string|null
	 * @since 1.0.15
	 */
	private function get_recipient_email( Chatbot_User $recipient ): ?string {
		$email = $recipient->email();
		if ( is_string( $email ) ) {
			return $email;
		}

		return null;
	}

	/**
	 * Build email headers (e.g. Content-Type: text/html).
	 *
	 * @param  Notification_Envelope  $envelope  Envelope (payload may contain headers).
	 *
	 * @return array
	 * @since 1.0.15
	 */
	private function get_headers( Notification_Envelope $envelope ): array {
		$payload = $envelope->get_payload();
		$headers = $payload['headers'] ?? [];

		if ( empty( $headers ) ) {
			$content_type = $envelope->get_content_type();
			$headers[]    = 'Content-Type: ' . $content_type . '; charset=UTF-8';
		}

		return is_array( $headers ) ? $headers : [ $headers ];
	}
}
