<?php
namespace QuizPressCertificates;

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

use QuizPressCertificates\PDF\Generator;

class Helper {

	public static function render_certificate( $quiz_id, $template_id, $student_id, $verification_id = '' ) {
		if ( ! get_option( 'quizpress_mpdf_fonts_downloaded', false ) ) {
			self::send_notice( __( 'Please download the fonts before generating the PDF.', 'quizpress' ) );
		}

		$certificate = get_post( $template_id );

		if ( empty( $certificate->post_content ) ) {
			return;
		}

		$user_data = get_userdata( $student_id );
		$fname = $user_data->first_name ?? '';
		$lname = $user_data->last_name ?? '';
		$student_name = $user_data->display_name ?? '';

		// Set student name if first and last names are available
		if ( ! empty( $fname ) && ! empty( $lname ) ) {
			$student_name = $fname . ' ' . $lname;
		}

		// Optional values, set to empty strings if data is unavailable
		$quiz = get_post( $quiz_id );
		$quiz_title = $quiz->post_title;
		$quiz_place = get_bloginfo( 'name' ) ?? 'Quiz Place Missing';

		$quiz_attempt = \QuizPress\API\Query\Attempts::get_attempts_by_quiz_and_user_id( $quiz_id, $student_id );
		$completion_date  = ( $quiz_attempt && 'passed' === $quiz_attempt[0]->attempt_status ) ? date_i18n( get_option( 'date_format' ), strtotime( $quiz_attempt[0]->attempt_ended_at ) ) : __( 'Completion Date Missing', 'quizpress' ); // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date
		$total_questions = count( \QuizPress\API\Query\Questions::get_questions_by_quid_id( $quiz_id, $student_id ) );
		// Replace dynamic placeholders with available values or default messages
		$certificate_template_dynamic_code_args = apply_filters( 'quizpress_certificates/template_dynamic_codes', [ '{{learner}}', '{{quiz_title}}', '{{quiz_place}}', '{{completion_date}}', '{{total_questions}}' ] );
		$certificate_template_dynamic_variable_args = apply_filters( 'quizpress_certificates/template_dynamic_codes_variables', [ $student_name, $quiz_title, $quiz_place, $completion_date, $total_questions ], $student_id, $quiz_id );
		$certificate_template = str_replace(
			$certificate_template_dynamic_code_args,
			$certificate_template_dynamic_variable_args,
			$certificate->post_content
		);

		$blocks = parse_blocks( $certificate_template );
		if ( ! empty( $blocks ) && 'ablocks/academy-certificate' === $blocks[0]['blockName'] ) {
			$attrs = $blocks[0]['attrs'];
			$pageSize = $attrs['pageSize'] ?? 'A4';
			$pageOrientation = $attrs['pageOrientation'] ?? 'L';
		}

		// Extract CSS from block content
		$cssContent = '';
		if ( ! empty( $blocks ) ) {
			foreach ( $blocks as $block ) {
				$htmlContent = apply_filters( 'the_content', render_block( $block ) );
				preg_match_all( '/<style>(.*?)<\/style>/is', $htmlContent, $matches );
				if ( ! empty( $matches[1] ) ) {
					foreach ( $matches[1] as $cssBlock ) {
						$cssContent .= $cssBlock;
					}
				}
			}
		}

		// Sanitize CSS content
		$cssContent = str_replace( '>', ' ', $cssContent );

		// Generate PDF preview
		$certificate_pdf = new Generator( $quiz_id, $student_id, $certificate_template, $cssContent, $pageSize, $pageOrientation );
		return $certificate_pdf->preview_certificate( get_the_title( $quiz_id ) );
	}

	protected static function send_notice( string $message ) {
		?>
		<p>
			<?php echo esc_html( $message ); ?>
			<a href="<?php echo esc_attr( home_url() ); ?>">Back to Home</a>
		</p>
		<?php
		exit;
	}

	public static function necessary_certificates() {
		$default_certificates = array(
			array(
				'title' => esc_html__( 'Certificate 1', 'quizpress' ),
				'file' => 'certificates/dummy-certificate/certificate-1.php',
			),
			array(
				'title' => esc_html__( 'Certificate 2', 'quizpress' ),
				'file' => 'certificates/dummy-certificate/certificate-2.php',
			),
			array(
				'title' => esc_html__( 'Certificate 3', 'quizpress' ),
				'file' => 'certificates/dummy-certificate/certificate-3.php',
			),
			array(
				'title' => esc_html__( 'Certificate 4', 'quizpress' ),
				'file' => 'certificates/dummy-certificate/certificate-4.php',
			),
			array(
				'title' => esc_html__( 'Certificate 5', 'quizpress' ),
				'file' => 'certificates/dummy-certificate/certificate-5.php',
			),
			array(
				'title' => esc_html__( 'Certificate 6', 'quizpress' ),
				'file' => 'certificates/dummy-certificate/certificate-6.php',
			),
			array(
				'title' => esc_html__( 'Certificate 7', 'quizpress' ),
				'file' => 'certificates/dummy-certificate/certificate-7.php',
			),
		);

		return $default_certificates;
	}

	public static function get_last_quiz_id() {
		global $wpdb;
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$results = $wpdb->get_col( "
			SELECT MAX(ID) FROM {$wpdb->prefix}posts
			WHERE post_type LIKE 'quizpress_quiz'
			AND post_status = 'publish'"
		);
		return reset( $results );
	}
}
