<?php
namespace QuizPress\API\Controller;

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

use \QuizPress\API\Query\Questions as Questions;
use \QuizPress\API\Query\Answers as Answers;
use QuizPress\API\Query\Attempts as Query;

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 ( $quiz_type === 'survey' ) {
            // For surveys, 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 );
        } 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 );
        }

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

        return [
            'quiz_id'     => $quiz_id,
            'quiz_type'   => $quiz_type,
            'leaderboard' => $results ?: [],
        ];
    }


}