<?php
declare(strict_types=1);

namespace App\Modules\Training\Services;

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

class SessionFeedbackService
{
    /**
     * Submit feedback for a session.
     */
    public static function submitFeedback(array $data): array
    {
        $sessionId = (int) ($data['session_id'] ?? 0);
        $playerId = (int) ($data['player_id'] ?? 0);

        if ($sessionId <= 0 || $playerId <= 0) {
            return ['success' => false, 'message' => 'بيانات غير صالحة'];
        }

        // Check if already rated
        if (SessionFeedback::hasPlayerRated($sessionId, $playerId)) {
            return ['success' => false, 'message' => 'تم تقييم هذه الحصة مسبقاً'];
        }

        $rating = max(1, min(5, (int) ($data['rating'] ?? 3)));
        $energyLevel = in_array($data['energy_level'] ?? '', ['low', 'medium', 'high'])
            ? $data['energy_level']
            : 'medium';
        $enjoymentLevel = max(1, min(5, (int) ($data['enjoyment_level'] ?? 3)));
        $difficultyLevel = max(1, min(5, (int) ($data['difficulty_level'] ?? 3)));
        $commentsAr = trim((string) ($data['comments_ar'] ?? ''));
        $isAnonymous = !empty($data['is_anonymous']) ? 1 : 0;

        $feedback = SessionFeedback::create([
            'session_id'       => $sessionId,
            'player_id'        => $playerId,
            'rating'           => $rating,
            'energy_level'     => $energyLevel,
            'enjoyment_level'  => $enjoymentLevel,
            'difficulty_level' => $difficultyLevel,
            'comments_ar'      => $commentsAr ?: null,
            'is_anonymous'     => $isAnonymous,
        ]);

        EventBus::dispatch('session.feedback_submitted', [
            'feedback_id' => $feedback->id ?? null,
            'session_id'  => $sessionId,
            'player_id'   => $playerId,
            'rating'      => $rating,
        ]);

        return ['success' => true, 'message' => 'تم إرسال التقييم بنجاح'];
    }

    /**
     * Get a session feedback report (averages + individual entries).
     */
    public static function getSessionReport(int $sessionId): array
    {
        return [
            'averages' => SessionFeedback::getAverages($sessionId),
            'entries'  => SessionFeedback::getForSession($sessionId),
        ];
    }

    /**
     * Get feedback summary for a coach over a date range.
     */
    public static function getCoachFeedbackSummary(int $coachId, string $dateFrom, string $dateTo): array
    {
        $db = App::getInstance()->db();

        $summary = $db->selectOne(
            "SELECT
                COUNT(sf.id) as total_feedback,
                COUNT(DISTINCT s.id) as total_sessions,
                AVG(sf.rating) as avg_rating,
                AVG(sf.enjoyment_level) as avg_enjoyment,
                AVG(sf.difficulty_level) as avg_difficulty,
                SUM(CASE WHEN sf.energy_level = 'high' THEN 1 ELSE 0 END) as energy_high,
                SUM(CASE WHEN sf.energy_level = 'medium' THEN 1 ELSE 0 END) as energy_medium,
                SUM(CASE WHEN sf.energy_level = 'low' THEN 1 ELSE 0 END) as energy_low
             FROM session_feedback sf
             INNER JOIN sessions s ON s.id = sf.session_id
             WHERE s.coach_id = ?
               AND s.session_date BETWEEN ? AND ?",
            [$coachId, $dateFrom, $dateTo]
        );

        $bySession = $db->select(
            "SELECT s.id, s.session_date, s.start_time,
                    COUNT(sf.id) as feedback_count,
                    AVG(sf.rating) as avg_rating
             FROM sessions s
             INNER JOIN session_feedback sf ON sf.session_id = s.id
             WHERE s.coach_id = ?
               AND s.session_date BETWEEN ? AND ?
             GROUP BY s.id, s.session_date, s.start_time
             ORDER BY s.session_date DESC",
            [$coachId, $dateFrom, $dateTo]
        );

        return [
            'summary'    => $summary ?: [],
            'by_session' => $bySession,
        ];
    }

    /**
     * Get feedback trend for a group (averages per session over time).
     */
    public static function getFeedbackTrend(int $groupId): array
    {
        $db = App::getInstance()->db();

        return $db->select(
            "SELECT s.session_date,
                    COUNT(sf.id) as feedback_count,
                    AVG(sf.rating) as avg_rating,
                    AVG(sf.enjoyment_level) as avg_enjoyment,
                    AVG(sf.difficulty_level) as avg_difficulty
             FROM sessions s
             INNER JOIN session_feedback sf ON sf.session_id = s.id
             WHERE s.group_id = ?
             GROUP BY s.session_date
             ORDER BY s.session_date ASC
             LIMIT 30",
            [$groupId]
        );
    }
}
