<?php
namespace AcademyPro;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}


class Frontend {
	public static function init() {
		$self = new self();
		$self->dispatch_hooks();
	}
	public function dispatch_hooks() {
		if ( \Academy\Helper::get_settings( 'is_expire_course_enrollment', false ) ) {
			add_action( 'academy/course/is_enrolled_before', array( $this, 'cancel_enrollment' ), 10, 2 );
		}
		add_filter( 'academy/get_course_filter_types', array( $this, 'course_filter_by_type_args' ) );
	}

	public function cancel_enrollment( $course_id, $user_id ) {
		$course_expire_enrollment = (int) get_post_meta( $course_id, 'academy_course_expire_enrollment', true );
		if ( ! $course_expire_enrollment ) {
			return;
		}
		global $wpdb;
		$expired_date = \Academy\Helper::get_time() - ( ( 60 * 60 * 24 ) * $course_expire_enrollment );

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching 
		$course_ids = $wpdb->get_col(
			$wpdb->prepare("SELECT ID FROM {$wpdb->posts}
            WHERE post_author=%d
                AND post_parent=%d
                AND post_type='academy_enrolled'
                AND post_status='completed'
                AND UNIX_TIMESTAMP(post_date)<%d", $user_id, $course_id, $expired_date)
		);

		if ( is_array( $course_ids ) && count( $course_ids ) ) {
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching 
			$wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->posts} SET post_status='cancel' WHERE ID IN (%s)", implode( ',', $course_ids ) ) );
			foreach ( $course_ids as $course_id ) {
				do_action( 'academy_pro/course/after_expired', $course_id );
			}
		}

	}

	public function course_filter_by_type_args( $filter ) {
		$filter['public'] = __( 'Public', 'academy-pro' );
		return $filter;
	}
}
