<?php
namespace QuizPress\API\Controller;

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


class Leaderboard extends \WP_REST_Controller {

	public static function init() {
		$self            = new self();
		$self->namespace = QUIZPRESS_PLUGIN_SLUG . '/v1';
		$self->rest_base = 'attempts';
		add_action( 'rest_api_init', array( $self, 'register_routes' ) );
	}

	public function register_routes() {
		register_rest_route( $this->namespace, '/leaderboard/(?P<quiz_id>\d+)', [
			'methods'             => 'GET',
			'callback'            => [ $this, 'get_leaderboard_response' ],
			'permission_callback' => function() {
				return current_user_can( 'manage_options' );
			},
			'args' => [
				'quiz_id' => [
					'description' => __( 'Quiz ID to retrieve leaderboard for.', 'quizpress' ),
					'type'        => 'integer',
					'required'    => true,
				],
				'limit' => [
					'description' => __( 'Number of users to return.', 'quizpress' ),
					'type'        => 'integer',
					'required'    => false,
					'default'     => 10,
				],
			],
		]);
	}

	public function get_leaderboard_response( $request ) {
		global $wpdb;

		$quiz_id = intval( $request['quiz_id'] );
		$limit   = intval( $request['limit'] ?? 10 );

		// Get quiz type (normal or survey)
		$quiz_type = get_post_meta( $quiz_id, 'quizpress_quiz_type', true );

		if ( ! $quiz_type ) {
			return new \WP_Error( 'invalid_quiz', __( 'Quiz not found or invalid type.', 'quizpress' ), [ 'status' => 404 ] );
		}

		if ( in_array( $quiz_type, [ 'survey', 'poll' ], true ) ) {
			// For surveys and polls, just show participation
			$query = $wpdb->prepare("
                SELECT a.user_id, u.display_name, COUNT(a.attempt_id) AS attempts
                FROM {$wpdb->prefix}quizpress_attempts a
                JOIN {$wpdb->users} u ON a.user_id = u.ID
                WHERE a.quiz_id = %d
                GROUP BY a.user_id
                ORDER BY attempts DESC
                LIMIT %d
            ", $quiz_id, $limit );

			$analytics_query = $wpdb->prepare("
                SELECT 
                    aa.question_id,
                    q.question_title,
                    aa.answer,
                    COUNT(*) AS answer_count,
                    COUNT(DISTINCT a.attempt_id) AS attempts_count,
                    COUNT(DISTINCT a.user_id) AS users_count
                FROM {$wpdb->prefix}quizpress_attempt_answers aa
                INNER JOIN {$wpdb->prefix}quizpress_attempts a 
                    ON aa.attempt_id = a.attempt_id
                INNER JOIN {$wpdb->prefix}quizpress_questions q
                    ON aa.question_id = q.question_id
                WHERE a.quiz_id = %d
                GROUP BY aa.question_id, aa.answer
                ORDER BY aa.question_id, answer_count DESC
            ", $quiz_id );
		} else {
			// For normal quizzes, rank by best score
			$query = $wpdb->prepare("
                SELECT a.user_id, u.display_name, MAX(a.earned_marks) AS best_score, COUNT(a.attempt_id) AS attempts
                FROM {$wpdb->prefix}quizpress_attempts a
                JOIN {$wpdb->users} u ON a.user_id = u.ID
                WHERE a.quiz_id = %d
                GROUP BY a.user_id
                ORDER BY best_score DESC
                LIMIT %d
            ", $quiz_id, $limit );
		}//end if

		 // GET ANALYTICS (ONLY FOR POLL & SURVEY)
		$analytics = [];
		$summary   = [];

		if ( in_array( $quiz_type, [ 'survey', 'poll' ], true ) ) {

			$analytics_query = $wpdb->prepare("
                SELECT 
                    aa.question_id,
                    q.question_title,
                    aa.answer,
                    COUNT(*) AS answer_count
                FROM {$wpdb->prefix}quizpress_attempt_answers aa
                INNER JOIN {$wpdb->prefix}quizpress_attempts a 
                    ON aa.attempt_id = a.attempt_id
                INNER JOIN {$wpdb->prefix}quizpress_questions q
                    ON aa.question_id = q.question_id
                WHERE a.quiz_id = %d
                GROUP BY aa.question_id, aa.answer
                ORDER BY aa.question_id, answer_count DESC
            ", $quiz_id );

			$rows = $wpdb->get_results( $analytics_query );

			$total_responses = 0;

			foreach ( $rows as $row ) {
				$qid = (int) $row->question_id;

				if ( ! isset( $analytics[ $qid ] ) ) {
					$analytics[ $qid ] = [
						'question_id'    => $qid,
						'question_title' => $row->question_title,
						'total_answers'  => 0,
						'options'        => [],
					];
				}

				$count = (int) $row->answer_count;

				$analytics[ $qid ]['options'][] = [
					'label' => $row->answer,
					'count' => $count,
				];

				$analytics[ $qid ]['total_answers'] += $count;
				$total_responses += $count;
			}//end foreach

			foreach ( $analytics as &$question ) {
				foreach ( $question['options'] as &$option ) {
					$option['percentage'] = round(
						( $option['count'] / max( 1, $question['total_answers'] ) ) * 100,
						2
					);
				}
			}

			$summary = [
				'total_questions' => count( $analytics ),
				'total_responses' => $total_responses,
			];
		}//end if

		$results = $wpdb->get_results( $query );// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

		return [
			'quiz_id'     => $quiz_id,
			'quiz_type'   => $quiz_type,
			'leaderboard' => $results ?: [],
			'analytics'   => array_values( $analytics ),
			'summary'     => $summary,
		];
	}


}
