<?php
/**
 * Masteriyo course completion verification block builder.
 *
 * @since 2.6.11
 */

namespace Masteriyo\Addons\Certificate\PDF\BlockBuilders;

defined( 'ABSPATH' ) || exit;


use Masteriyo\Enums\CourseProgressStatus;
use Masteriyo\Query\CourseProgressQuery;

class MasteriyoCertificateVerificationCode extends BlockBuilder {

	/**
	 * Build and return the block HTML.
	 *
	 * @since 2.6.11
	 *
	 * @return string
	 */
	public function build() {

		$pdf               = $this->get_pdf();
		$verification_name = $pdf->is_preview() ? __( 'Certificate Verification Code', 'learning-management-system' ) : '';
		$student_id        = $pdf->get_student_id();
		$course_id         = $pdf->get_course_id();
		$block_data        = $this->get_block_data();
		$certificate_id    = masteriyo_get_course_certificate_id( $course_id );

		$certificate_verification_code = $course_id . '-' . $certificate_id . '-' . $student_id;

		if ( $student_id && $course_id ) {
			$query      = new CourseProgressQuery(
				array(
					'user_id'   => $student_id,
					'course_id' => $course_id,
					'status'    => CourseProgressStatus::COMPLETED,
				)
			);
			$progresses = $query->get_course_progress();
			$progress   = empty( $progresses ) ? null : $progresses[0];

			if ( $progress ) {
				$completed_at = $progress->get_completed_at();

			}
		}

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