<?php

namespace GemBoards\Emails;

use GemBoards\Classes\EmailNotification;
use GemBoards\Utils\Helper;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
} // if accessed directly, exit


class TaskStageChanged extends EmailNotification {

	protected function setup() {
		$this->subject = __( 'Task has been moved', 'gemboards' );
		/* translators: 1: Task title, 2: Old stage, 3: New stage. */
		$this->message = __( 'has moved task %1$s from %2$s to %3$s.', 'gemboards' );
	}

	public function send_mail() {
		$notification = $this->notification;
		$task_id      = $notification->get_object_id();
		$from_user_id = $notification->get_from_user_id();

		$from_user = get_user( $from_user_id );
		if ( ! $from_user ) {
			return;
		}

		$notification_meta = $notification->get_notification_meta();
		if ( ! isset( $notification_meta['old_column_id'], $notification_meta['new_column_id'] ) ) {
			return;
		}

		$old_column = Helper::get_column( $notification_meta['old_column_id'] );
		if ( ! $old_column ) {
			return;
		}
		$new_column = Helper::get_column( $notification_meta['new_column_id'] );
		if ( ! $new_column ) {
			return;
		}

		$card = Helper::get_card_by_task_id($task_id);
		if ( ! $card ) {
			return;
		}

		$task_title = get_the_title( $card->get_task_id() );
		$task_url   = home_url() . '/' . Helper::get_settings('path', 'workspace') . '/boards/' . $card->get_board_id() . '/?task_id=' . $task_id;

		$avatar_url = get_avatar_url( $from_user->user_email );
		$email_body = Helper::get_email_body( 'notification', [
			'avatar_url'        => $avatar_url,
			'user_display_name' => $from_user->display_name,
			'message'           => sprintf( $this->message, "<a target='_blank' href='" . esc_url($task_url) . "'>$task_title</a>", "<strong>{$old_column->get_title()}</strong>", "<strong>{$new_column->get_title()}</strong>" ),
		] );

		$headers = [ 'Content-Type: text/html; charset=UTF-8' ];
		wp_mail( $this->user->user_email, wp_specialchars_decode( $this->subject ), $email_body, $headers );
	}
}
