<?php

namespace local_academic_ticket_system\external;

use core_external\external_api;
use core_external\external_function_parameters;
use core_external\external_multiple_structure;
use core_external\external_single_structure;
use core_external\external_value;
use core_external\external_description;

defined('MOODLE_INTERNAL') || die();

class get_admin_report extends external_api {

    public static function execute_parameters(): external_function_parameters {
        return new external_function_parameters([]);
    }

    public static function execute() {
        global $DB;
        self::validate_context(\context_system::instance());

        $sql = "SELECT u.id, u.firstname, u.lastname, 
                       (SELECT COUNT(t.id) FROM {local_acadtkt_tickets} t WHERE t.assigned_to = u.id AND t.status = 'closed') as resolved_count,
                       (SELECT AVG(f.rating) FROM {local_acadtkt_feedback} f JOIN {local_acadtkt_tickets} t2 ON f.ticketid = t2.id WHERE t2.assigned_to = u.id) as avg_rating
                FROM {user} u
                WHERE u.id IN (SELECT DISTINCT assigned_to FROM {local_acadtkt_tickets} WHERE assigned_to > 0)";

        $records = $DB->get_records_sql($sql);
        $result = [];
        foreach ($records as $r) {
            $result[] = [
                'fullname' => $r->firstname . ' ' . $r->lastname,
                'resolved' => (int)$r->resolved_count,
                'rating' => $r->avg_rating ? round($r->avg_rating, 1) : 0
            ];
        }
        return $result;
    }

    public static function execute_returns(): external_description {
        return new external_multiple_structure(
            new external_single_structure([
                'fullname' => new external_value(PARAM_TEXT, 'Admin Name'),
                'resolved' => new external_value(PARAM_INT, 'Tickets Resolved'),
                'rating' => new external_value(PARAM_FLOAT, 'Average Rating')
            ])
        );
    }
}