<?php
/**
 * Masteriyo instructor name block builder.
 *
 * @since 2.14.0
 */

namespace Masteriyo\Addons\Certificate\PDF\BlockBuilders;

defined( 'ABSPATH' ) || exit;


class MasteriyoInstructorName extends BlockBuilder {

	/**
	 * Build and return the block HTML.
	 *
	 * @since 2.14.0
	 *
	 * @return string
	 */
	public function build() {
		$pdf             = $this->get_pdf();
		$block_data      = $this->get_block_data();
		$instructor_name = __( 'Instructor Name', 'learning-management-system' );
		$name_format     = masteriyo_array_get( $block_data, 'attrs.nameFormat', 'fullname' );

		$course = masteriyo_get_course( $pdf->get_course_id() );

		if ( ! is_wp_error( $course ) && ! is_null( $course ) ) {
			$instructor = masteriyo_get_user( $course->get_author_id() );

			if ( ! is_null( $instructor ) && ! is_wp_error( $instructor ) ) {
				$full_name = trim( sprintf( '%s %s', $instructor->get_first_name(), $instructor->get_last_name() ) );

				if ( 'fullname' === $name_format ) {
					$instructor_name = $full_name;
				} elseif ( 'first-name' === $name_format ) {
					$instructor_name = $instructor->get_first_name();
				} elseif ( 'last-name' === $name_format ) {
					$instructor_name = $instructor->get_last_name();
				} elseif ( 'display-name' === $name_format ) {
					$instructor_name = $instructor->get_display_name();
				} else {
					$instructor_name = $full_name;
				}
			}

			/**
			 * Filter instructor name before using.
			 *
			 * @since 2.14.0
			 *
			 * @param string $instructor_name Instructor name.
			 * @param string $name_format Name format.
			 * @param \Masteriyo\Models\User $instructor Instructor object.
			 */
			$instructor_name = apply_filters( 'masteriyo_certificate_instructor_name', $instructor_name, $name_format, $instructor );
		}

		$html  = $block_data['innerHTML'];
		$html  = str_replace( '{{masteriyo_instructor_name}}', $instructor_name, $html );
		$html .= '<style>' . masteriyo_array_get( $block_data, 'attrs.blockCSS', '' ) . '</style>';
		return $html;
	}
}
