<?php
namespace local_academic_ticket_system\external;

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

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

class submit_feedback extends external_api {

    public static function execute_parameters(): external_function_parameters {
        return new external_function_parameters([
            'ticketid' => new external_value(PARAM_INT, 'Ticket ID'),
            'rating'   => new external_value(PARAM_INT, 'Rating (1-5)'),
            'comment'  => new external_value(PARAM_TEXT, 'User comment', VALUE_DEFAULT, '')
        ]);
    }

    public static function execute($ticketid, $rating, $comment) {
        global $DB, $USER;

        $params = self::validate_parameters(self::execute_parameters(), [
            'ticketid' => $ticketid,
            'rating'   => $rating,
            'comment'  => $comment
        ]);

        self::validate_context(context_system::instance());

        $ticket = $DB->get_record('local_acadtkt_tickets', ['id' => $params['ticketid']], '*', MUST_EXIST);

        $feedback = new \stdClass();
        $feedback->ticketid   = $params['ticketid'];
        $feedback->userid     = $USER->id;
        $feedback->rating     = $params['rating'];
        $feedback->comment    = $params['comment'];
        $feedback->created_at = time();

        $DB->insert_record('local_acadtkt_feedback', $feedback);

        $ticket->status = 'closed';
        $ticket->updated_at = time();
        $DB->update_record('local_acadtkt_tickets', $ticket);

        return [
            'status' => true,
            'message' => 'Feedback submitted and ticket closed'
        ];
    }

    public static function execute_returns(): external_description {
        return new external_single_structure([
            'status'  => new external_value(PARAM_BOOL, 'True on success'),
            'message' => new external_value(PARAM_TEXT, 'Status message')
        ]);
    }
}