<?php
/**
 * Masteriyo Co-Instructors Name block builder.
 *
 * @since 2.14.0
 */

namespace Masteriyo\Addons\Certificate\PDF\BlockBuilders;

defined( 'ABSPATH' ) || exit;


use Masteriyo\Pro\Addons;

class MasteriyoCoInstructorsName 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();
		$co_instructors_names = __( 'Co-Instructors Names', 'learning-management-system' );
		$name_format          = masteriyo_array_get( $block_data, 'attrs.nameFormat', 'fullname' );

		if ( ( new Addons() )->is_active( MASTERIYO_MULTIPLE_INSTRUCTORS_ADDON_SLUG ) ) {

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

			if ( ! is_wp_error( $course ) && ! is_null( $course ) ) {
				$co_instructors   = (array) $course->get_meta( '_additional_authors', false );
				$instructors_list = array();

				if ( ! empty( $co_instructors ) ) {
					foreach ( $co_instructors as $co_instructor_id ) {
						$instructor = masteriyo_get_user( $co_instructor_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 ) {
								$instructors_list[] = $full_name;
							} elseif ( 'first-name' === $name_format ) {
								$instructors_list[] = $instructor->get_first_name();
							} elseif ( 'last-name' === $name_format ) {
								$instructors_list[] = $instructor->get_last_name();
							} elseif ( 'display-name' === $name_format ) {
								$instructors_list[] = $instructor->get_display_name();
							} else {
								$instructors_list[] = $full_name;
							}
						}
					}
				}

				if ( ! empty( $instructors_list ) ) {
					$co_instructors_names = implode( ', ', $instructors_list );
				}

				/**
				 * Filter co-instructors names before using.
				 *
				 * @since 2.14.0
				 *
				 * @param string $co_instructors_names Co-instructors names.
				 * @param string $name_format Name format.
				 * @param array $co_instructors List of co-instructor objects.
				 */
				$co_instructors_names = apply_filters( 'masteriyo_certificate_co_instructors_names', $co_instructors_names, $name_format, $co_instructors );
			}
		}

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