<?php

class HappyForms_Task_Email_Owner extends HappyForms_Task {

	public static $event = 'email_owner';

	public function run() {
		$response = happyforms_get_message_controller()->get( $this->response_id );

		if ( ! $response ) {
			error_log( 'Response not found.' );
			return;
		}

		$form_id = $response['form_id'];
		$form = happyforms_get_form_controller()->get( $form_id );
		$conditional_controller = happyforms_get_conditional_controller();

		if ( $conditional_controller->has_conditions( $form ) ) {
			$form = happyforms_get_conditional_controller()->get( $form, $response['request'] );
		}

		if ( ! $form ) {
			error_log( 'Form not found.' );
			return;
		}

		$subject = $this->get_email_owner_confirmation_subject( $form, $response );

		if ( ! empty( $form['email_recipient'] ) && ! empty( $subject ) ) {
			// Compose an email message
			$email_message = new HappyForms_Email_Message( $response );
			$name = $form['alert_email_from_name'];
			$to = explode( ',', $form['email_recipient'] );

			$email_message->set_from_name( $name );
			$email_message->set_to( $to[0] );

			if ( count( $to ) > 1 ) {
				$email_message->set_ccs( array_slice( $to, 1 ) );
			}

			$bccs = explode( ',', $form['email_bccs'] );

			if ( count( $bccs ) > 0 ) {
				$email_message->set_bccs( $bccs );
			}

			$email_message->set_subject( $subject );

			// Add a Reply To header and a reply-and-mark-as-read link
			// if the form includes an email part
			$email_part = happyforms_get_form_controller()->get_first_part_by_type( $form, 'email' );

			if ( false !== $email_part ) {
				$part_id = $email_part['id'];
				$reply_to = happyforms_get_message_part_value( $response['parts'][$part_id], $email_part );
				$email_message->set_reply_to( $reply_to );
			}

			ob_start();
			require_once( happyforms_owner_email_template_path() );
			$content = ob_get_clean();

			$email_message->set_content( $content );
			$email_message = apply_filters( 'happyforms_email_alert', $email_message );
			$email_message->send();

			do_action( 'happyforms_email_alert_sent', $email_message );
		}
	}

	public function get_email_owner_confirmation_subject( $form, $response ) {
		$subject = $form['alert_email_subject'];
 		$subject_parts = array_filter( $form['parts'], function( $part ) {
			$use_as_subject = (
				isset( $part['use_as_subject'] )
				&& intval( $part['use_as_subject'] )
			);
 			return $use_as_subject;
		} );
		$subject_parts = array_values( $subject_parts );

 		if ( count( $subject_parts ) > 0 ) {
			$part = $subject_parts[count( $subject_parts ) - 1];
			$subject = happyforms_get_email_part_value( $response, $part, $form );
		}

 		return $subject;
	}

}
