<?php

namespace GemBoards\Emails;

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

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


class MentionUserComment extends EmailNotification {

	protected function setup() {
		$this->subject = __( 'You\'re mentioned on task comment', 'gemboards' );
		/* translators: 1: Task title, 2: Board Title */
		$this->message = __( 'mentioned you on %1$s task\'s comment of %2$s board.', '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['comment_id'] ) ) {
			return;
		}
		$comment_id = absint($notification_meta['comment_id']);
		$comment    = get_comment( $comment_id );
		if ( ! $comment ) {
			return;
		}

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

		$board = $card->get_board();
		if ( ! $board ) {
			return;
		}
		$board_url = home_url() . '/' . Helper::get_settings('path', 'workspace') . '/boards/' . $board->get_id();

		$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>", "<a target='_blank' href='" . esc_url( $board_url ) . "'>{$board->get_title()}</a>" ) . '<div class="gemboards_email_comment">' . wp_kses_post($comment->comment_content) . '</div>',
		] );

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