<?php
namespace AcademyProRestrictContentPro;

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

class Helper {
	public static function has_course_access( $course_id, $user_id = '' ): bool {
		$membership_level_ids = self::get_current_course_memberships( $course_id );
		$user_id = empty( $user_id ) ? get_current_user_id() : $user_id;
		$is_administrator = current_user_can( 'administrator' );
		$is_instructor    = \Academy\Helper::is_instructor_of_this_course( get_current_user_id(), $course_id );

		if ( $is_administrator || $is_instructor ) {
			return true;
		}

		$has_membership_access = false;

		$customer = \rcp_get_customer_by_user_id( $user_id );
		if ( ! $customer ) {
			return false;
		}

		$memberships = $customer->get_memberships( array( 'status' => array( 'active' ) ) );
		if ( empty( $memberships ) ) {
			return false;
		}

		$customer_membership_ids = [];
		foreach ( $memberships as $membership ) {
			$customer_membership_ids[] = $membership->get_object_id();
		}

		if ( array_intersect( $membership_level_ids, $customer_membership_ids ) ) {
			return true;
		}

		return $has_membership_access;
	}

	public static function get_current_course_memberships( $course_id ) {
		return get_post_meta( $course_id, 'academy_rcp_membership_levels', true );
	}

	public static function get_customer_membership_levels( $membership_level_id ) {
		$levels = rcp_get_membership_levels( [
			'id' => $membership_level_id,
			'status' => 'active'
		] );
		return ! empty( $levels ) && isset( $levels[0] ) ? $levels[0] : '';
	}

	public static function is_inactive_in_membership_levels( $membership_level_id ) {
		return ! empty( rcp_get_membership_levels( [
			'id' => $membership_level_id,
			'status' => 'inactive'
		] ) );
	}

	public static function get_active_subscribers_by_membership_id( $membership_level_id ) {
		if ( ! $membership_level_id ) {
			return 0;
		}
		global $wpdb;
		$table = $wpdb->prefix . 'rcp_memberships';
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$total_active_members = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(id) FROM $table WHERE status = %s AND object_id = %d", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
				'active', $membership_level_id
			)
		);
		return intval( $total_active_members );
	}
}
