<?php

namespace AcademyProCertificates;

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

use Academy\Classes\Sanitizer;

class Ajax {
	public static function init() {
		$self = new self();
		add_action( 'wp_ajax_academy_pro/shortcode/certificate_verification', array( $self, 'certificate_verification_handler' ) );
		add_action( 'wp_ajax_nopriv_academy_pro/shortcode/certificate_verification', array( $self, 'certificate_verification_handler' ) );
	}

	public function certificate_verification_handler() {
		check_ajax_referer( 'academy_nonce', 'security' );
		$payload = Sanitizer::sanitize_payload( [
			'certificate_id' => 'string',
		], $_POST);

		$verification_code = $payload['certificate_id'] ?? '';

		if ( empty( $verification_code ) ) {
			wp_send_json_error(
				esc_html_e( 'Verification code is missing.', 'academy-pro' )
			);
		}

		global $wpdb;
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$comment = $wpdb->get_row( $wpdb->prepare(
			"SELECT comment_post_ID FROM $wpdb->comments 
			WHERE comment_content = %s",
			$verification_code
		) );
		// check comment
		if ( empty( $comment ) ) {
			wp_send_json_success(
				array(
					'status'     => false,
					'appendHtml' => '<p class="academy-pro_no_found_msg">' . esc_html__( 'The certificate number you entered is incorrect.', 'academy-pro' ) . '</p>',
				)
			);
		}

		$course_id = $comment->comment_post_ID;

		$certificate_id = get_post_meta( $course_id, 'academy_course_certificate_id', true );
		if ( ! $certificate_id ) {
			$certificate_id = \Academy\Helper::get_settings( 'academy_primary_certificate_id' );
		}
		$certificate_url = '<a class="academy-btn academy-btn--view-certificate" target="_blank" href="' . esc_url( add_query_arg( array( 'source' => 'certificate' ), get_the_permalink( $course_id ) ) ) . '">' . esc_html__( 'View Certificate', 'academy-pro' ) . '</a>';
		wp_send_json_success(
			array(
				'status' => true,
				'appendHtml' => $certificate_url
			)
		);
	}
}
