<?php
declare(strict_types=1);

namespace App\Modules\Sessions\Services;

use App\Core\App;
use App\Core\EventBus;
use App\Modules\Sessions\Models\SessionFeedback;

class SessionFeedbackService
{
    public static function submitFeedback(array $data): int
    {
        $sessionId = (int) $data['session_id'];
        $playerId = (int) $data['player_id'];

        if (SessionFeedback::hasPlayerRated($sessionId, $playerId)) {
            throw new \RuntimeException('تم إرسال التقييم مسبقاً', 400);
        }

        $db = App::getInstance()->db();
        $db->insert('session_feedback', [
            'session_id'       => $sessionId,
            'player_id'        => $playerId,
            'rating'           => max(1, min(5, (int) ($data['rating'] ?? 3))),
            'energy_level'     => in_array($data['energy_level'] ?? '', ['low', 'medium', 'high']) ? $data['energy_level'] : 'medium',
            'enjoyment_level'  => max(1, min(5, (int) ($data['enjoyment_level'] ?? 3))),
            'difficulty_level' => max(1, min(5, (int) ($data['difficulty_level'] ?? 3))),
            'comments_ar'      => $data['comments_ar'] ?? null,
            'is_anonymous'     => !empty($data['is_anonymous']) ? 1 : 0,
            'created_at'       => date('Y-m-d H:i:s'),
        ]);

        $feedbackId = (int) $db->selectOne("SELECT LAST_INSERT_ID() AS id")['id'];

        EventBus::dispatch('session.feedback_submitted', [
            'feedback_id' => $feedbackId,
            'session_id'  => $sessionId,
            'player_id'   => $playerId,
            'rating'      => (int) ($data['rating'] ?? 3),
        ]);

        return $feedbackId;
    }

    public static function getSessionReport(int $sessionId): array
    {
        return [
            'averages' => SessionFeedback::getAverages($sessionId),
            'feedback' => SessionFeedback::getForSession($sessionId),
        ];
    }

    public static function getFeedbackTrend(int $groupId, int $limit = 20): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT ts.session_date,
                    ROUND(AVG(sf.rating), 1) AS avg_rating,
                    COUNT(sf.id) AS responses
             FROM session_feedback sf
             JOIN training_sessions ts ON ts.id = sf.session_id
             WHERE ts.group_id = ?
             GROUP BY ts.session_date
             ORDER BY ts.session_date DESC
             LIMIT ?",
            [$groupId, $limit]
        );
    }
}
