<?php
namespace AcademyProScorm;

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

use WP_REST_Request;
class ProgressTracker {
	protected array $fields = [
		'current',
		'lessons',
		'status',
		'time',
		'score'
	];
	protected int $student_id;
	public function __construct() {
		$id = get_current_user_id();
		$this->student_id = is_int( $id ) ? $id : 0;
	}
	public static function init() : void {
		$self = new self();
		add_action( 'rest_api_init', [ $self, 'course_progress_endpoint' ] );

		add_filter(
			"academy/topic_completed_by_student_id_{$self->student_id}",
			[ $self, 'topic_completed' ],
			10,
			3
		);
		add_filter(
			'academy/count_total_topics_in_course',
			[ $self, 'total_topics_in_course' ],
			10,
			2
		);
		add_filter(
			'academy/count_total_topics_in_curriculums',
			[ $self, 'total_topics_in_course' ],
			10,
			2
		);
		add_filter(
			'academy/get_course_analytics',
			[ $self, 'add_scrom_course_topic_info' ],
			10,
			2
		);
	}

	public function course_progress_endpoint() : void {
		$namespace = ACADEMY_PRO_PLUGIN_SLUG . '/v1';
		register_rest_route(
			$namespace,
			'/scorm_course_progress/(?P<course_id>[\d-]+)/',
			array(
				'methods'             => 'GET',
				'permission_callback' => '__return_true',
				'callback'            => array( $this, 'scorm_get_course_progress' ),
			)
		);

		register_rest_route(
			$namespace,
			'/scorm_course_progress/(?P<course_id>[\d-]+)/',
			array(
				'methods'             => 'POST',
				'permission_callback' => '__return_true',
				'callback'            => array( $this, 'scorm_update_course_progress' ),
			)
		);
	}

	public function total_topics_in_course( int $completed, int $course_id ) : int {
		$data = $this->get_data( $course_id );
		$lessons = count(
			array_filter(
				explode( ',', $data['lessons'] ?? '' ), fn( string $value ) => in_array( $value, [ '0', '1' ], true )
			)
		);
		if (
			empty( get_post_meta( $course_id, '_academy_course_builder_scorm_file', true ) ) ||
			0 === empty( $data ) ||
			0 === $lessons
		) {
			return $completed;
		}
		return $lessons;
	}

	public function add_scrom_course_topic_info( $response, $course_id ) {
		$is_array = is_array( $response );

		$scorm_file = get_post_meta( $course_id, '_academy_course_builder_scorm_file', true );
		if ( empty( $scorm_file ) ) {
			if ( $is_array ) {
				$response['is_scorm_file_added'] = false;
			} else {
				$response->is_scorm_file_added = false;
			}
			return $response;
		}

		$data           = $this->get_data( $course_id );
		$lesson_values  = explode( ',', $data['lessons'] ?? '' );

		$total_topics     = count( array_filter( $lesson_values, fn( $v ) => in_array( $v, [ '0', '1' ], true ) ) );
		$completed_topics = count( array_filter( $lesson_values, fn( $v ) => '1' === $v ) );

		if ( $is_array ) {
			$response['scorm_total_topics']     = $total_topics;
			$response['scorm_completed_topics'] = $completed_topics;
			$response['is_scorm_file_added']    = true;
		} else {
			$response->scorm_total_topics     = $total_topics;
			$response->scorm_completed_topics = $completed_topics;
			$response->number_of_lessons      = $total_topics;
			$response->is_scorm_file_added    = true;
		}

		return $response;
	}

	public function topic_completed( int $topics, int $course_id, int $student_id ) : int {
		$data = $this->get_data( $course_id );
		$lessons = count(
			array_filter( explode( ',', $data['lessons'] ?? '' ), fn( string $value ) => in_array( $value, [ '1' ], true ) )
		);
		if (
			empty( get_post_meta( $course_id, '_academy_course_builder_scorm_file', true ) ) ||
			0 === $student_id ||
			0 === empty( $data ) ||
			0 === $lessons
		) {
			return $topics;
		}
		return $lessons;
	}

	public function get_data_key( int $course_id ) : string {
		return "academy_scrom_{$course_id}_course_progress";
	}

	public function get_data( int $course_id ) : array {
		$data = get_user_meta(
			$this->student_id,
			$this->get_data_key( $course_id ),
			true
		);
		return is_array( $data ) ? $data : [];
	}

	public function scorm_get_course_progress( WP_REST_Request $request ) : array {
		$params = $request->get_params();
		return apply_filters( 'academy_pro/scorm/get_course_progress',
			$this->get_data( $request['course_id'] )
		);
	}

	public function scorm_update_course_progress( WP_REST_Request $request ) : array {
		$data = apply_filters(
			'academy_pro/scorm/update_course_progress',
			$this->get_data( $request['course_id'] )
		);

		foreach ( $this->fields as $field ) {
			if ( isset( $request[ $field ] ) ) {
				$data[ $field ] = $request[ $field ];
			}
		}

		update_user_meta(
			$this->student_id,
			$this->get_data_key( $request['course_id'] ),
			$data
		);
		return $this->get_data( $request['course_id'] );
	}
}
