<?php
namespace QuizPress\API\Controller;

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



class Analytics 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, '/analytics', [
			'methods'             => 'GET',
			'callback'            => array( $this, 'get_global_analytics' ),
			'permission_callback' => function() {
				return current_user_can( 'manage_options' ); // admin only
			},
		]);
	}

	public function get_global_analytics() {
		global $wpdb;

		$attempts_table = $wpdb->prefix . 'quizpress_attempts';
		$meta_table     = $wpdb->prefix . 'postmeta';
		$quiz_table     = $wpdb->prefix . 'posts';
		// ---- Basic Totals ----
		$total_quizzes = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(ID)
                FROM $quiz_table
                WHERE post_type = %s
                AND post_status = %s",
				'quizpress_quiz', 'publish'
			),
		);

		$total_attempts = $wpdb->get_var( "SELECT COUNT(attempt_id) FROM $attempts_table" );// phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter

		$total_users = $wpdb->get_var( "
            SELECT COUNT(DISTINCT user_id)
            FROM $attempts_table
        " );

		// ---- Averages ----
		$average_attempts_per_quiz = $wpdb->get_var( "
            SELECT COUNT(attempt_id) / COUNT(DISTINCT quiz_id)
            FROM $attempts_table
        " );

		$average_score = $wpdb->get_var( "
            SELECT AVG(earned_marks)
            FROM $attempts_table
        " );

		// ---- Quiz Type Breakdown ----
		$quiz_type_counts = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT meta_value AS quiz_type, COUNT(post_id) AS total
                FROM $meta_table
                WHERE meta_key = %s            
                GROUP BY meta_value",
				'quizpress_quiz_type'
			),
		);

		// ---- Global Leaderboard ----
		$global_leaderboard = $wpdb->get_results( "
            SELECT a.user_id, u.display_name, SUM(a.earned_marks) AS total_score, COUNT(a.attempt_id) AS attempts
            FROM $attempts_table a
            JOIN {$wpdb->users} u ON a.user_id = u.ID
            GROUP BY a.user_id
            ORDER BY total_score DESC
            LIMIT 10
        " );

		// ---- Top Performing Quizzes ----
		$top_quizzes = $wpdb->get_results( "
            SELECT a.quiz_id, p.post_title, AVG(a.earned_marks) AS avg_score, COUNT(a.attempt_id) AS attempts
            FROM $attempts_table a
            JOIN $quiz_table p ON a.quiz_id = p.ID
            WHERE p.post_type = 'quizpress_quiz'
            GROUP BY a.quiz_id
            ORDER BY avg_score DESC
            LIMIT 10
        " );

		return [
			'summary' => [
				'total_quizzes'            => (int) $total_quizzes,
				'total_attempts'           => (int) $total_attempts,
				'total_users'              => (int) $total_users,
				'average_attempts_per_quiz' => round( $average_attempts_per_quiz, 2 ),
				'average_score'            => round( $average_score, 2 ),
			],
			'quiz_type_breakdown' => $quiz_type_counts ?: [],
			'top_users'           => $global_leaderboard ?: [],
			'top_quizzes'         => $top_quizzes ?: [],
		];
	}
}
