<?php

namespace Groundhogg;

use Groundhogg\DB\Email_Log;
use PHPMailer\PHPMailer\PHPMailer;

class Email_Log_Item extends Base_Object {

	/**
	 * Handle post setup actions...
	 */
	protected function post_setup() {

		$int_props = [
			'retries'
		];

		foreach ( $int_props as $prop ) {
			$this->$prop = intval( $this->$prop );
		}

		$this->recipients = maybe_unserialize( $this->recipients );
		$this->headers    = maybe_unserialize( $this->headers );

	}

	/**
	 * Get the log DB
	 *
	 * @return Email_Log
	 */
	protected function get_db() {
		return get_db( 'email_log' );
	}

	/**
	 * Retry to send the email.
	 */
	public function retry() {

		// Compile headers!
		$headers = [];

		foreach ( $this->headers as $header ) {
			$headers[] = sprintf( "%s: %s", $header[0], $header[1] );
		}

		add_action( 'groundhogg/email_logger/before_create_log', [ $this, 'setup_email_logger_with_this' ] );

		// make sure the altbody is set correctly
		add_action( 'phpmailer_init', [ $this, 'set_altbody' ] );

		$result = \Groundhogg_Email_Services::send_type( $this->message_type, $this->recipients, $this->subject, $this->content, $headers );

		// make sure we remvoe altbody setting after retry
		remove_action( 'phpmailer_init', [ $this, 'set_altbody' ] );

		remove_action( 'groundhogg/email_logger/before_create_log', [ $this, 'setup_email_logger_with_this' ] );

		return $result;
	}

	/**
	 * Set the altbody if there is one
	 *
	 * @param PHPMailer $phpmailer
	 *
	 * @return void
	 */
	public function set_altbody( &$phpmailer ) {
		$phpmailer->AltBody = $this->altbody;
	}

	/**
	 * @param $logger Email_Logger
	 */
	public function setup_email_logger_with_this( $logger ) {
		$logger->set_log( $this );
	}

	/**
	 * Catch retry failed error
	 *
	 * @param $error \WP_Error
	 */
	public function catch_mail_error( $error ) {
		$this->add_error( $error );
	}

	/**
	 * Get the content type of the email from the headers
	 *
	 * @return mixed|string
	 */
	public function get_content_type() {

		$content_type_header = array_find( $this->headers, function( $header ) {
			return strtolower( $header[0] ) === 'content-type';
		} );

		if ( $content_type_header ) {
			return $content_type_header[1];
		}

		return 'text/html';
	}

	public function get_as_array() {

		$this->from_avatar = get_avatar_url( $this->from_address );

		$user = get_user_by( 'email', $this->from_address );

		$this->from_name = $user ? $user->display_name : get_bloginfo();

		// wpautop content for the email log preview
		if ( $this->get_content_type() === 'text/plain' && doing_rest() ){
			$this->content = wpautop( $this->content );
		}

		$json = parent::get_as_array(); // TODO: Change the autogenerated stub

		$json[ 'i18n' ] =[
			'service' => \Groundhogg_Email_Services::get_service_display_name( $this->email_service ),
			'type' => \Groundhogg_Email_Services::message_type_labels( $this->message_type )
		];

		return $json;
	}

}
