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

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

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

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

		$product_id = (int) get_post_meta( $course_id, 'academy_course_product_id', true );
		$product = wc_get_product( $product_id );
		if ( $product ) {
			$sym = get_woocommerce_currency_symbol();
			$r_price = $product->get_regular_price();
			$s_price = $product->get_sale_price();
		}
		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 ( ! function_exists( 'WC' ) ) {
			wp_send_json_error([
				'message' => __( 'WooCommerce 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 ) );

		if ( ! self::is_academy_product( $product_id ) ) {
			wp_send_json_error([
				'message' => __( 'Product ID is invalid or not linked to any course.', 'academy-pro' )
			], 400);
		}

		$query = "SELECT c.ID FROM {$wpdb->posts} c
            INNER JOIN {$wpdb->postmeta} pm
                ON pm.post_id = c.ID
            WHERE 
                c.post_type = 'academy_courses' AND 
                pm.meta_key = 'academy_course_product_id' AND 
                pm.meta_value = %d";

		$course_id = $wpdb->get_var( $wpdb->prepare( $query, $product_id ) ) ?? ''; // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		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 (
				0 === count( $errors['type'] ?? [] ) &&
				! 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'] ?? '';
		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'  => $errors
			], 400);
		}

		$is_added = WC()->cart->add_to_cart($product_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 ( $is_added ) {
			wp_send_json_error([
				'message' => __( 'Product is added to cart!', 'academy-pro' ),
				'cart_url' => wc_get_cart_url()
			], 200);
		}

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


	public function get_price( $payload_data ) : void {
		if ( ! function_exists( 'WC' ) ) {
			wp_send_json_error([
				'message' => __( 'WooCommerce is not activated.', 'academy-pro' )
			], 500);
		}
		$payload = Sanitizer::sanitize_payload([
			'product_id'       => 'integer',
		], $payload_data);

		$product_id = $payload['product_id'] ?? 0;

		if ( ! self::is_academy_product( $product_id ) ) {
			wp_send_json_error([
				'message' => __( 'Product ID is invalid or not linked to any course.', 'academy-pro' )
			], 400);
		}
		$product = wc_get_product( $product_id );
		if ( $product ) {
			wp_send_json_error([
				'message'    => __( 'Product price', 'academy-pro' ),
				'unit_price' => $product->get_regular_price()
			], 200);
		}

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

	public function is_academy_product( $product_id ) {
		global $wpdb;

		if ( empty( $product_id ) ) {
			return false;
		}

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$linked_course = $wpdb->get_col(
			$wpdb->prepare(
				"SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = %s AND meta_value = %d",
				'academy_course_product_id',
				$product_id
			)
		);
		$is_academy_flagged = get_post_meta( $product_id, '_academy_product', true );
		if ( $linked_course && ! $is_academy_flagged ) {
			return false;
		}
		return true;
	}

}
