<?php
namespace AcademyProCourseBundle;

use stdClass;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}


class Ajax {
	public static function init() {
		$self = new self();
		add_action( 'wp_ajax_academy_pro_course_bundle/admin/get_courses', array( $self, 'get_course' ) );
		add_action( 'wp_ajax_academy_pro_course_bundle/get_paid_courses', array( $self, 'get_paid_courses' ) );

		( new Ajax\Woocommerce() )->dispatch_actions();
	}

	public function get_course() {
		check_ajax_referer( 'academy_nonce', 'security' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die();
		}

		$course_id = ! empty( $_POST['course_id'] ) ? absint( $_POST['course_id'] ) : 0;

		if ( ! $course_id ) {
			wp_send_json_error();
		}

		$engine = \Academy\Helper::get_settings( 'monetization_engine' );
		$course     = get_post( $course_id );
		$woo_product_id = absint( get_post_meta( $course_id, 'academy_course_product_id', true ) );
		$store_product_id = absint( get_post_meta( $course_id, 'academy_store_product', true ) );

		if ( $woo_product_id && 'woocommerce' === $engine ) {
			$product       = wc_get_product( $woo_product_id );
			$sale_price    = $product->get_sale_price();
			$regular_price = $product->get_regular_price();
			if ( $sale_price ) {
				$course->sale_price = $sale_price;
			}

			if ( $regular_price ) {
				$course->regular_price = $regular_price;
			}
		}

		$thumbnail_id      = get_post_thumbnail_id( $course_id );
		$course->image_src = $thumbnail_id ?
			wp_get_attachment_image_src( $thumbnail_id, 'medium' )[0] :
			ACADEMY_ASSETS_URI . '/images/thumbnail-placeholder.png';

		$course->author = \Academy\Helper::get_addon_active_status( 'multi_instructor' ) ? \Academy\Helper::get_instructors_by_course_id( absint( $course->id ) ) :
				\Academy\Helper::get_instructor_by_author_id( absint( $course->id ) );

		$course->meta = new stdClass();
		if ( $store_product_id && 'storeengine' === $engine ) {
			$integrations = \StoreEngine\Utils\Helper::get_integration_repository_by_id( 'storeengine/academylms', $course_id );
			$prices = [];
			foreach ( $integrations as $integration ) {
				$prices[] = [
					'price_type' => $integration->price->get_type(),
					'regular_price' => $integration->price->get_compare_price(),
					'sale_price' => $integration->price->get_price(),
				];
			}
			$course->store_prices = $prices;
		}
		$course->meta->academy_course_expire_enrollment        = get_post_meta( $course_id, 'academy_course_expire_enrollment', true );
		$course->meta->academy_course_type                     = get_post_meta( $course_id, 'academy_course_type', true );
		$course->meta->academy_course_product_id               = get_post_meta( $course_id, 'academy_course_product_id', true );
		$course->meta->academy_store_product                   = get_post_meta( $course_id, 'academy_store_product', true );
		$course->meta->academy_course_max_students             = get_post_meta( $course_id, 'academy_course_max_students', true );
		$course->meta->academy_course_language                 = get_post_meta( $course_id, 'academy_course_language', true );
		$course->meta->academy_course_difficulty_level         = get_post_meta( $course_id, 'academy_course_difficulty_level', true );
		$course->meta->academy_course_benefits                 = get_post_meta( $course_id, 'academy_course_benefits', true );
		$course->meta->academy_course_requirements             = get_post_meta( $course_id, 'academy_course_requirements', true );
		$course->meta->academy_course_audience                 = get_post_meta( $course_id, 'academy_course_audience', true );
		$course->meta->academy_course_materials_included       = get_post_meta( $course_id, 'academy_course_materials_included', true );
		$course->meta->academy_is_enabled_course_qa            = get_post_meta( $course_id, 'academy_is_enabled_course_qa', true );
		$course->meta->academy_is_enabled_course_announcements = get_post_meta( $course_id, 'academy_is_enabled_course_announcements', true );
		$course->meta->academy_course_duration                 = get_post_meta( $course_id, 'academy_course_duration', true );
		$course->meta->academy_course_intro_video              = get_post_meta( $course_id, 'academy_course_intro_video', true );
		$course->meta->academy_course_curriculum               = get_post_meta( $course_id, 'academy_course_curriculum', true );

		wp_send_json_success( $course );
	}

	public function get_paid_courses() {
		check_ajax_referer( 'academy_nonce', 'security' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die();
		}

		global $wpdb;
		$engine = \Academy\Helper::get_settings( 'monetization_engine' );
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$paid_courses = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT
					ID AS value,
					post_title label
				FROM
					{$wpdb->posts} post
				INNER JOIN
					{$wpdb->postmeta} meta
				ON
					meta.post_id = post.ID
				AND
					meta.meta_key = %s
				AND
					meta.meta_value = %s
				AND
					post.post_status = %s",
				'academy_course_type',
				'paid',
				'publish'
			)
		);
		$response = [];
		if ( is_array( $paid_courses ) && count( $paid_courses ) ) {
			foreach ( $paid_courses as $paid_course ) {
				if ( 'woocommerce' === $engine && class_exists( 'WooCommerce' ) ) {
					$is_woo_product = $this->is_woocommerce_product( (int) $paid_course->value );
					if ( $is_woo_product ) {
						$response[] = array(
							'label' => $paid_course->label,
							'value' => (int) $paid_course->value
						);
					}
				} elseif ( 'storeengine' === $engine && class_exists( \StoreEngine::class ) ) {
					$response[] = array(
						'label' => $paid_course->label,
						'value' => (int) $paid_course->value
					);
				}
			}
		}//end if
		wp_send_json_success( $response );
	}

	public function is_woocommerce_product( $course_id ) {
		$product_id = get_post_meta( $course_id, 'academy_course_product_id', true );
		$post_type = get_post_type( $product_id );

		return ( 'product' === $post_type );
	}
}
