<?php
namespace AcademyProGroupPlus\Integration\Storeengine;

use Academy\Helper;
use AcademyProGroupPlus\Db\Models\Group;
use StoreEngine\Classes\CartItem;
use StoreEngine\Classes\Order\OrderItemProduct;
use AcademyProGroupPlus\Integration\Storeengine\Ajax\EcommerceCoursePurchaseHandler;
use AcademyProGroupPlus\Helper as GroupHelper;
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class Storeengine {
	public static function init(): void {
		if ( 'storeengine' !== $GLOBALS['academy_settings']->monetization_engine ) {
			return;
		}
		Ajax\EcommerceCoursePurchaseHandler::init();
		$instance = new self();
		add_action( 'storeengine/cart/item_update_quantity', [ $instance, 'validate' ], 10, 3 );
		// add_filter( 'storeengine/cart/item_name', [ $self, 'show_metadata' ], 999, 2 );
		add_action( 'storeengine/order/create_order_line_item', [ $instance, 'add_metadata' ], 10, 2 );
		add_action( 'storeengine/order_status_completed', [ $instance, 'add_course_to_group' ], 10, 3 );
		add_filter( 'storeengine/integrations/run_integration_outside', [ $instance, 'skip_single_purchase' ], 10, 3 );
		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 );
		add_filter( 'academy/get_courses_purchase_history', [ $instance, 'modify_courses_purchase_args' ], 10, 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( string $item_key, int $quantity, object $cart ) : void {
		if ( ! empty( $cart->cart_items[ $item_key ]->item_data['academy_group'] ?? [] ) ) {
			$product = $cart->cart_items[ $item_key ];
			$course_id = self::get_course_id_by_product_id( $product->product_id );
			$available_seats = Helper::get_available_seats( $course_id );
			if ( $product->quantity > $available_seats ) {
				// translators: %1$d is available seats %2$d is number of quantity
				throw new \Exception( esc_html( sprintf( __( 'Seat available %1$d, demanded : %2$d', 'academy-pro' ), $available_seats, $product->quantity ) ) );
			}
		}
	}

	public static function get_course_id_by_product_id( int $product_id ) : int {
		return EcommerceCoursePurchaseHandler::get_course_id( $product_id );
	}

	public function add_course_to_group( $order_id, $order ) {
		$new               = [];
		$new_names         = [];
		$existing          = [];
		$need_recalculate  = false;
		$user_id           = null;

		foreach ( $order->get_items() as $item_id => $item ) {
			if ( $item->get_meta( 'academy_group_updated' ) ) {
				continue;
			}

			$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
				);

				$order->add_order_note( $msg );
				$order->remove_item( $item_id );
				$need_recalculate = true;

				continue;
			}

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

			// Store user_id once (assuming it's the same for all items)
			if ( isset( $group_data['user_id'] ) && ! $user_id ) {
				$user_id = $group_data['user_id'];
			}

			$slug = sanitize_title( $name );

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

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

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

		add_post_meta( $course_id, 'is_academy_group_order_id', $order_id );

		// Handle new groups
		foreach ( $new as $slug => $items ) {
			$group_name = $new_names[ $slug ];

			$group_id = Group::ins()->create([
				'name'    => $group_name,
				'user_id' => $user_id,
			]);

			if ( ! $group_id ) {
				continue;
			}

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

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

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

			Group::ins()->update_course( $group_id, $data['course_id'], $data['quantity'] );
			$this->mark_group_course_as_updated( $data['item'] );
		}
	}


	public function mark_group_course_as_updated( $item ) : void {
		$item->add_meta_data( 'academy_group_updated', 1 );
		$item->save();
	}

	public function show_metadata( string $name, CartItem $cart_item ): string {
		global $wpdb;
		if ( ! empty( $cart_item->item_data['academy_group'] ?? [] ) ) {
			$type = $cart_item->item_data['academy_group']['academy_group']['type'] ?? '';
			$value = $cart_item->item_data['academy_group']['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
			}
			$name .= ', ';
			$name .= 'group_existing' === $type ? $value : $value . ' (' . __( 'will be created', 'academy-pro' ) . ') ';
		}

		return $name;
	}

	public function add_metadata( OrderItemProduct $item, CartItem $cart_item ) {
		if ( empty( $cart_item->item_data['academy_group'] ?? [] ) ) {
			return;
		}

		$item->add_meta_data( 'academy_group', $cart_item->item_data['academy_group'] );
	}

	public function skip_single_purchase( $is_run, $integrations, $order_item ) : bool {
		if ( ! empty( $order_item->get_meta( 'academy_group' ) ) ) {
			return true;
		}
		return $is_run;
	}

	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;
	}

	public function modify_courses_purchase_args( $args, $user_id ) {
		$orders  = GroupHelper::get_group_orders_by_user_id( $user_id );
		if ( is_array( $orders ) ) {
			$results = [];
			foreach ( $orders as $order ) {
				$courses = [
					'ID'        => $order->course_id,
					'title'     => get_the_title( $order->course_id ),
					'permalink' => esc_url( get_the_permalink( $order->course_id ) ),
				];
				$se_order = \StoreEngine\Utils\Helper::get_order( $order->ID );
				$price     = $se_order->get_total();
				$status    = $order->post_status;
				$results[] = [
					'ID'      => $order->ID,
					'courses' => [ $courses ],
					'price'   => \StoreEngine\Utils\Helper::get_currency_symbol( $se_order->get_currency() ) . $price,
					'status'  => \Academy\Helper::order_status_context( $status ),
					'date'    => date_i18n( get_option( 'date_format' ), strtotime( $order->post_date ) ),
				];
			}
			$args['orders'] = array_merge( $args['orders'] ?? [], $results );
		}//end if
		return $args;
	}
}
