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

namespace Masteriyo\Addons\Certificate\PDF\BlockBuilders;

defined( 'ABSPATH' ) || exit;


use Masteriyo\Enums\CourseProgressStatus;
use Masteriyo\Query\CourseProgressQuery;
use chillerlan\QRCode\QRCode;
use Masteriyo\Constants;

class MasteriyoQrCode extends BlockBuilder {

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

		$pdf            = $this->get_pdf();
		$verification   = $pdf->is_preview() ? __( 'Qr 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();

				if ( $completed_at ) {
					$completion_date = gmdate( 'jmY', $completed_at->getTimestamp() );
					$data            = home_url( '?certificate-verification-id=' ) . $certificate_verification_code;
				}
			}
		}

		$style = masteriyo_array_get( $block_data, 'attrs.blockCSS', '' );
		return "<div class='masteriyo-qr-code-block' style='{$style}'><img src='" . ( isset( $data ) ? ( new QRCode() )->render( $data ) : plugins_url( 'assets\img\qrcode.png', MASTERIYO_PLUGIN_FILE ) ) . "' alt='QR Code' width='80px' /> </div>";

	}
}
