<?php
namespace AcademyProGroupPlus\Integration\Woocommerce;

use Academy\Helper;
use AcademyProGroupPlus\Db\Models\Group;
use AcademyProGroupPlus\Helper as GroupHelper;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
final class Woocommerce {
	public static function init(): void {
		if ( 'woocommerce' !== $GLOBALS['academy_settings']->monetization_engine ) {
			return;
		}
		Ajax\EcommerceCoursePurchaseHandler::init();
		$instance = new self();
		add_action( 'woocommerce_before_calculate_totals', [ $instance, 'validate' ], 10, 1 );

		add_filter( 'woocommerce_get_item_data', [ $instance, 'show_metadata' ], 10, 2 );

		add_action( 'woocommerce_checkout_create_order_line_item', [ $instance, 'add_metadata' ], 10, 4 );
		add_action( 'woocommerce_order_status_completed', [ $instance, 'add_course_to_group' ], 10, 1 );

		add_filter( 'academy/templates/single_course/enroll_form', [ $instance, 'modify_add_to_cart_button' ], 11, 2 );
		add_filter( 'academy/template/loop/footer_form', [ $instance, 'modify_loop_price_args' ], 11, 2 );
	}

	public function get_user_id( $order ) : ?int {
		$email = $order->get_billing_email();
		$user_id  = $order->get_user_id();
		if ( $user_id ) {
			return $user_id;
		}
		if ( ! email_exists( $email ) ) {
			$username = strstr( $email, '@', true ) . wp_rand( 100, 1000 );
			$password = wp_generate_password( 12, false );
			$user_id  = wp_create_user( $username, $password, $email );
			if ( is_wp_error( $user_id ) ) {
				return null;
			}
			wp_new_user_notification( $user_id, null, 'both' );

		}
		return $user_id;
	}

	public function validate( $cart ) {
		foreach ( $cart->get_cart() as $cart_key => $item ) {
			if ( empty( get_post_meta( $item['product_id'], '_academy_product', true ) ) ) {
				continue;
			}
			$course_id = self::get_course_id_by_product_id( $item['product_id'] );
			$available_seats = Helper::get_available_seats( $course_id );

			$item['data']->set_stock_quantity( $available_seats );
		}

	}

	public static function get_course_id_by_product_id( $product_id ) : int {
		global $wpdb;
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		return $wpdb->get_var(
			$wpdb->prepare(
				"SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = %s  AND meta_value = %d  limit 1",
				'academy_course_product_id',
				$product_id
			)
		);
	}

	public function add_course_to_group( $order_id ) {
		$order = wc_get_order( $order_id );

		if ( ! $order ) {
			return;
		}

		$new               = [];
		$new_names         = [];
		$existing          = [];
		$need_recalculate  = false;
		$user_id           = null;

		foreach ( $order->get_items() as $item_id => $item ) {
			$group_data = $item->get_meta( 'academy_group' );

			if ( empty( $group_data ) ) {
				continue;
			}

			$course_id = self::get_course_id_by_product_id( $item->get_product_id() );
			$available_seats = Helper::get_available_seats( $course_id );
			$quantity = $item->get_quantity();
			if ( $available_seats < $quantity ) {
				$msg = sprintf(
					// translators: %1$s is product name, %2$s is available seats, %3$s is quantity
					__( 'Insufficient seats, %1$s is removed from order. Available seats: %2$s, demanded: %3$s', 'academy-pro' ),
					$item->get_product()->get_name(),
					$available_seats,
					$quantity
				);

				wc_add_notice( $msg, 'error' );
				$order->add_order_note( $msg );
				$order->remove_item( $item_id );
				$need_recalculate = true;

				continue;
			}

			$type = $group_data['type'] ?? '';
			$name = $group_data['name'] ?? '';

			if ( 'new_group' === $type ) {
				$slug = sanitize_title( $name );
				$new[ $slug ][] = [
					'course_id' => $course_id,
					'quantity'  => $quantity,
				];
				$new_names[ $slug ] = $name;
			} else {
				$existing[] = [
					'course_id' => $course_id,
					'group_id'  => $name,
					'quantity'  => $quantity,
				];
			}

			if ( isset( $group_data['user_id'] ) ) {
				$user_id = $group_data['user_id'];
			}
		}//end foreach

		if ( ! $new && ! $existing ) {
			return;
		}

		if ( $need_recalculate ) {
			$order->calculate_totals();
		}

		add_post_meta( $order_id, 'is_academy_order_for_course', $course_id );
		add_post_meta( $order_id, 'academy_order_for_course_id_' . $course_id, 0 );

		// Handle new group creations
		foreach ( $new as $slug => $items ) {
			$group_id = Group::ins()->create([
				'name'    => $new_names[ $slug ],
				'user_id' => $user_id,
			]);

			if ( ! $group_id ) {
				continue;
			}

			foreach ( $items as $item ) {
				Group::ins()->update_course( $group_id, $item['course_id'], $item['quantity'] );
				Group::ins()->add_organizer( $group_id, $this->get_user_id( $order ) );
			}
		}

		// Handle existing groups
		foreach ( $existing as $item ) {
			$group_id = $item['group_id'];

			if ( empty( Group::ins()->get_by_id( $group_id ) ) ) {
				continue;
			}

			$current_seats = GroupHelper::get_seats( $user_id, $item['course_id'] );
			$total_seats = $current_seats + (int) $item['quantity'];

			Group::ins()->update_course( $group_id, $item['course_id'], $total_seats );
		}
	}


	public function show_metadata( $item_data, $cart_item ) {
		global $wpdb;
		if ( array_key_exists( 'academy_group', $cart_item ) ) {

			$type = $cart_item['academy_group']['type'] ?? '';
			$value = $cart_item['academy_group'][ $type ] ?? '';

			if ( 'group_existing' === $type ) {
				$table = $wpdb->prefix . ACADEMY_PLUGIN_SLUG . '_groups';
				$query = "SELECT name FROM {$table} 
                    WHERE id = %d";

				$value = $wpdb->get_var( $wpdb->prepare( $query, $value ) ) ?? '';// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
			}

			$item_data[] = [
				'key' => __( 'Group Name', 'academy-pro' ),
				'value' => 'group_existing' === $type ? $value : $value . ' (' . __( 'will be created', 'academy-pro' ) . ') ',
			];
		}
		return $item_data;
	}

	public function add_metadata( $item, $cart_item_key, $values, $order ) {
		if ( array_key_exists( 'academy_group', $values ) ) {
			$item->update_meta_data( 'academy_group', $values['academy_group'] );
		}
	}

	public function modify_add_to_cart_button( $args, $course_id ) {
		$current_user_id = get_current_user_id();

		if ( ! empty( GroupHelper::is_organizer( $current_user_id, $course_id ) ) ) {
			ob_start();
			Helper::get_template( 'single-course/enroll/continue.php', [ 'course_id' => $course_id ] );
			return ob_get_clean(); // Returns a string
		}

		return $args;
	}

	public function modify_loop_price_args( $args, $course_id ) {
		if ( GroupHelper::is_organizer( get_current_user_id(), $course_id ) ) {
			$continue_learning = apply_filters(
				'academy/templates/start_course_url',
				Helper::get_start_course_permalink( $course_id ),
				$course_id
			);
			ob_start();
			?>
			<div class="academy-widget-enroll__continue">
				<a class="academy-btn academy-btn--bg-purple" href="<?php echo esc_url( $continue_learning ); ?>">
					<?php echo esc_html__( 'Start Course', 'academy' ); ?>
				</a>
			</div>
			<?php
			return ob_get_clean();
		}

		return $args;
	}
}
