<?php
namespace QuizPressCertificates;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}


use QuizPress\Helper;
use QuizPressCertificates\Helper as CertificateHelper;

class Frontend {
	public static function init() {
		$self = new self();
		add_filter( 'template_include', array( $self, 'download_certificate' ), 40 );
		add_action( 'template_include', array( $self, 'preview_certificate' ) );
	}

	public function download_certificate( $template ) {
		if ( get_query_var( 'source' ) === 'qp-certificate' &&  ! empty( $_GET[ 'quiz_id' ] )  ) {
			add_filter( 'ablocks/is_allow_block_inline_assets', '__return_true' );	
			$quiz_id = $_GET[ 'quiz_id' ] ? intval( sanitize_text_field( wp_unslash( $_GET[ 'quiz_id' ] ) ) ) : 0;

			$certificate_id = Helper::get_settings( 'quizpress_primary_certificate_id' );
			if ( ! $certificate_id ) {
				wp_die( esc_html_e( 'Sorry, no primary certificate found', 'quizpress' ) );
				exit;
			}
			$certificate_template_id = apply_filters( 'quizpress_certificates/certificate_template_id', $certificate_id, $quiz_id );
			$student_id = apply_filters( 'quizpress_certificates/certificate_student_id', get_current_user_id() );
			CertificateHelper::render_certificate( $quiz_id, $certificate_template_id, $student_id );
		}
		return $template;
	}
	public function preview_certificate( $template ) {
		if ( is_singular( 'qp_certificate' ) && ! is_admin() ) {
			add_filter( 'ablocks/is_allow_block_inline_assets', '__return_true' );
			add_filter( 'ablocks/is_enabled_assets_generation', '__return_false' );

			$certificate_preview_id = get_the_id();
			$quiz_id = CertificateHelper::get_last_quiz_id();

			if ( ! $quiz_id ) {
				wp_die( esc_html_e( 'Sorry, you have no quiz.', 'quizpress' ) );
				exit;
			}


			CertificateHelper::render_certificate( $quiz_id, $certificate_preview_id, get_current_user_id() );

		}//end if

		return $template;
	}
}
