<?php
/**
 * Course final course grade result block builder.
 *
 * @since 2.14.0
 */

namespace Masteriyo\Addons\Certificate\PDF\BlockBuilders;

defined( 'ABSPATH' ) || exit;


use Masteriyo\Addons\Gradebook\Enums\GradeResultType;
use Masteriyo\Pro\Addons;

class MasteriyoCourseGradeResult 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();
		$course       = masteriyo_get_course( $pdf->get_course_id() );
		$grade_result = __( 'Course Grade Result', 'learning-management-system' );

		if ( ( new Addons() )->is_active( MASTERIYO_GRADEBOOK_ADDON_SLUG ) ) {
			$student = masteriyo_get_user( $pdf->get_student_id() );

			if ( ! is_null( $course ) && ! is_wp_error( $course ) && ! is_null( $student ) && ! is_wp_error( $student ) ) {
				$grade_item = masteriyo_get_grade_result_item( $course->get_id(), GradeResultType::COURSE, $student->get_id() );

				if ( ! is_wp_error( $grade_item ) && $grade_item ) {
					$grade_result = sprintf(
						'<span style="background: %s;">%s</span>',
						esc_attr( $grade_item->get_grade_color() ),
						esc_html( $grade_item->get_grade_name() )
					);
				}
			}

			/**
			 * Filters the course grade result displayed on the certificate.
			 *
			 * @since 2.14.0
			 *
			 * @param string $grade_result The course grade result.
			 * @param \Masteriyo\Models\Course $course The course object.
			 * @param \Masteriyo\Models\User $student The student object.
			 * @return string The filtered course grade result.
			 */
			$grade_result = apply_filters( 'masteriyo_certificate_course_grade_result', $grade_result, $course, $student );
		}

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

		return $html;
	}
}
