<?php
namespace AcademyProGroupPlus\Integration\Storeengine\Ajax;

use Academy\Classes\Sanitizer;
use Academy\Helper;
use AcademyProGroupPlus\Db\Models\Group;
use StoreEngine\Utils\Formatting;
use StoreEngine\Utils\Helper as StoreEngineHelper;
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
class EcommerceCoursePurchaseHandler {

	public static function init() {
		$instance = new self();
		add_filter( 'academy_pro/group_plus/storeengine/product_data', [ $instance, 'product_data' ], 10, 2 );
		add_action( 'academy_pro/group_plus/storeengine/add_to_cart', [ $instance, 'add_to_cart' ] );
		add_action( 'academy_pro/group_plus/storeengine/get_price', [ $instance, 'get_price' ] );
	}

	public function product_data( array $data, int $course_id ) : array {
		if ( ! class_exists( StoreEngineHelper::class ) ) {
			return [];
		}
		$prices = 0;
		$r_price = 0;
		$s_price = 0;
		$sym = '';
		$product_id = 0;

		$product = current( \StoreEngine\Utils\Helper::get_integration_repository_by_id( 'storeengine/academylms', $course_id ) );

		if ( $product ) {
			$prices  = $product->price;
			$r_price = $prices ? $prices->get_compare_price() : '';
			$s_price = $prices ? $prices->get_price() : '';
			$sym        = StoreEngineHelper::get_currency_symbol( Formatting::get_currency() );
			$product_id = $product->integration->get_product_id();
		}

		return [
			'product_id' => $product_id,
			'r_price'    => $r_price,
			's_price'    => $s_price,
			'sym'        => $sym,
		];
	}

	public function add_to_cart( $payload_data ) : void {
		global $wpdb;
		if ( ! class_exists( StoreEngineHelper::class ) ) {
			wp_send_json_error( [
				'message' => __( 'StoreEngine is not activated.', 'academy-pro' )
			], 500 );
		}
		$payload = Sanitizer::sanitize_payload( [
			'product_id'       => 'integer',
			'quantity'         => 'integer',
			'type'             => 'string',
			'group_name'       => 'string',
			'group_id'         => 'integer',
		], $payload_data );

		$product_id = abs( intval( $payload['product_id'] ?? 0 ) );
		$quantity   = abs( intval( $payload['quantity'] ?? 0 ) );
		$course_id = static::get_course_id( $product_id ) ?? get_the_ID();
		if ( empty( $course_id ) ) {
			wp_send_json_error( [
				'message' => __( 'Course not available.', 'academy-pro' ),
			], 400 );
		}

		$errors = [];
		$available_seats = Helper::get_available_seats( $course_id );
		if (
			( $available_seats ) < $quantity
		) {
			// translators: %d is available seats
			$errors['quantity'][] = $available_seats > 0 ? sprintf( __( 'Only %d seats available..', 'academy-pro' ), $available_seats ) : __( 'No seats available..', 'academy-pro' );
			wp_send_json_error( [
				'message' => __( 'Errors.', 'academy-pro' ),
				'errors'  => $errors
			], 400 );
		}

		if (
			0 === $quantity
		) {
			$errors['quantity'][] = __( 'Quantity must be greater than 0.', 'academy-pro' );
		}

		if (
				empty( $payload['type'] ?? '' )
			) {
			$errors['type'][] = __( 'Please select existing group or create new.', 'academy-pro' );
		}

		if (
				count( $errors['type'] ?? [] ) == 0 &&
				! in_array( $payload['type'] ?? '', [ 'new_group', 'group_existing' ] )
			) {
			$errors['type'][] = __( 'Please select existing group or create new.', 'academy-pro' );
		}

		if (
				( $payload['type'] ?? '' ) == 'new_group' &&
				empty( $payload['group_name'] ?? '' )
			) {
			$errors['group_name'][] = __( 'Please enter a group name.', 'academy-pro' );
		}
			$group_id = $payload['group_id'] ?? 0;
		if (
				( $payload['type'] ?? '' ) == 'group_existing' &&
				empty( $group_id )
			) {
			$errors['group_id'][] = __( 'Please select a group.', 'academy-pro' );
		}
		$is_existing_group = 'group_existing' === ( $payload['type'] ?? '' ) ? true : false;
		$user_id = get_current_user_id();
		if ( $is_existing_group &&
				! (
					current_user_can( 'manage_options' ) ||
					Group::ins()->is_group_organizer( $user_id, $group_id )
				)
			) {
			$errors['group_id'][] = __( 'Please select a valid group.', 'academy-pro' );
		}

		if ( count( $errors ) > 0 ) {
			wp_send_json_error([
				'message' => __( 'Errors.', 'academy-pro' ),
				'errors'  => array_unique( $errors )
			], 400);
		}

		$product = StoreEngineHelper::get_product( $product_id );
		if ( $product ) {
			$price = $product->get_prices()[0] ?? null;
			if ( ! empty( $price ) ) {
				$is_added = StoreEngineHelper::cart()->add_product_to_cart( $price->get_id(), $quantity, 0, [], [
					'academy_group' => [
						'type'    => $payload['type'],
						'name' => 'group_existing' === $payload['type'] ? $payload['group_id'] : $payload['group_name'],
						'user_id' => $user_id,
						$payload['type'] => 'group_existing' === $payload['type'] ? $payload['group_id'] : $payload['group_name']
					],
				]);

				if ( true === $is_added ) {
					wp_send_json_error([
						'message' => __( 'Product is added to cart!', 'academy-pro' ),
						'cart_url' => StoreEngineHelper::get_cart_url()
					], 200);
				}
			}
		}

		wp_send_json_error([
			'message' => __( 'Error.', 'academy-pro' ),
		], 500);
	}


	public function get_price( $payload_data ) : void {
		if ( ! class_exists( StoreEngineHelper::class ) ) {
			wp_send_json_error( [
				'message' => __( 'StoreEngine is not activated.', 'academy-pro' )
			], 500 );
		}

		$payload = Sanitizer::sanitize_payload([
			'product_id'       => 'integer',
		], $payload_data);

		$product_id = abs( intval( $payload['product_id'] ?? 0 ) );

		if ( empty( static::get_course_id( $product_id ) ) ) {
			wp_send_json_error([
				'message' => __( 'Product must be a course.', 'academy-pro' )
			], 400);
		}

		$product = StoreEngineHelper::get_product( $product_id );
		if ( $product ) {
			$prices = $product->get_prices()[0] ?? null;
			if ( ! empty( $prices ) ) {
				wp_send_json_error([
					'message'    => __( 'Product price', 'academy-pro' ),
					'unit_price' => $prices->get_price()
				], 200);
			}
		}

		wp_send_json_error([
			'message' => __( 'Error.', 'academy-pro' ),
		], 500);
	}

	public static function get_course_id( int $product_id ) : ?int {
		global $wpdb;
		$course_id = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT integration_id from {$wpdb->prefix}storeengine_integrations 
				WHERE product_id = %d AND provider = %s ORDER BY id DESC",
				$product_id,
				'storeengine/academylms'
			)
		);
		return empty( $course_id ) ? null : absint( $course_id );
	}
}
