<?php
/**
 * WP Courseware Units Functions.
 *
 * @package WPCW
 * @subpackage Functions
 * @since 4.3.0
 */

// Exit if accessed directly
defined( 'ABSPATH' ) || exit;

/**
 * Get Unit.
 *
 * @since 4.4.0
 *
 * @param int|bool $unit_id The Unit Id.
 *
 * @return \WPCW\Models\Unit|bool An unit object or false.
 */
function wpcw_get_unit( $unit_id = false ) {
	if ( ! did_action( 'wpcw_loaded' ) ) {
		wpcw_doing_it_wrong( __FUNCTION__, 'wpcw_get_unit should not be called before the unit object is setup.', '4.4.0' );

		return false;
	}

	return new \WPCW\Models\Unit( $unit_id );
}

/**
 * Insert Unit.
 *
 * @since 4.4.0
 *
 * @param array $data The unit data.
 *
 * @return \WPCW\Models\Unit|bool The unit object or false on failure.
 */
function wpcw_insert_unit( $data = array() ) {
	if ( ! did_action( 'wpcw_loaded' ) ) {
		wpcw_doing_it_wrong( __FUNCTION__, 'wpcw_insert_unit should not be called before the unit object is setup.', '4.4.0' );

		return false;
	}

	$unit    = new \WPCW\Models\Unit();
	$unit_id = $unit->create( $data );

	return $unit_id ? $unit : $unit_id;
}

/**
 * Get Units.
 *
 * @since 4.4.0
 *
 * @param array $args The courses query args.
 *
 * @return array The array of Course objects.
 */
function wpcw_get_units( $args = array() ) {
	return wpcw()->units->get_units( $args );
}

/**
 * Can Student Access Unit?
 *
 * @since 4.3.0
 *
 * @param int $unit_id The unit id.
 * @param int $student_id The student id.
 *
 * @return bool True if the student can access unit.
 */
function wpcw_can_student_access_unit( $unit_id, $student_id = 0 ) {
	$can_access = false;

	if ( ! $unit_id ) {
		return $can_access;
	}

	if ( ! $student_id && ! is_user_logged_in() ) {
		return $can_access;
	}

	if ( ! $student_id ) {
		$student_id = get_current_user_id();
	}

	$unit_data = WPCW_units_getUnitMetaData( $unit_id );

	if ( empty( $unit_data ) || empty( $unit_data->parent_course_id ) ) {
		return $can_access;
	}

	if ( WPCW_courses_canUserAccessCourse( $unit_data->parent_course_id, $student_id ) ) {
		$can_access = true;
	}

	return $can_access;
}