<?php
namespace AcademyProScorm\Lesson;

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() {
		$this->student_id = is_int( $id = get_current_user_id() ) ? $id : 0;
	}
	public static function init() : void {
		$self = new self();
		add_action( 'rest_api_init', [ $self, 'course_progress_endpoint' ] );
	}

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

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

	public function get_data_key( int $course_id, int $lesson_id ) : string {
		return "academy_scrom_course_{$course_id}_lesson_{$lesson_id}_progress";
	}

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

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

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

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

		update_user_meta(
			$this->student_id,
			$this->get_data_key( absint( $request['course_id'] ), absint( $request['lesson_id'] ) ),
			$data
		);

		return $this->get_data( absint( $request['course_id'] ), absint( $request['lesson_id'] ) );
	}
}
