<?php
declare(strict_types=1);

namespace App\Modules\Training\Models;

use App\Core\Model;
use App\Core\App;

class SessionFeedback extends Model
{
    protected static string $table = 'session_feedback';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = false;
    protected static bool $softDelete = false;

    protected static array $fillable = [
        'session_id',
        'player_id',
        'rating',
        'energy_level',
        'enjoyment_level',
        'difficulty_level',
        'comments_ar',
        'is_anonymous',
    ];

    /**
     * Get all feedback entries for a specific session.
     */
    public static function getForSession(int $sessionId): array
    {
        $db = App::getInstance()->db();

        return $db->select(
            "SELECT sf.*, m.name_ar AS player_name
             FROM session_feedback sf
             LEFT JOIN members m ON m.id = sf.player_id AND sf.is_anonymous = 0
             WHERE sf.session_id = ?
             ORDER BY sf.created_at DESC",
            [$sessionId]
        );
    }

    /**
     * Get average ratings for a session.
     */
    public static function getAverages(int $sessionId): array
    {
        $db = App::getInstance()->db();

        $result = $db->selectOne(
            "SELECT
                COUNT(*) as total_responses,
                AVG(rating) as avg_rating,
                AVG(enjoyment_level) as avg_enjoyment,
                AVG(difficulty_level) as avg_difficulty,
                SUM(CASE WHEN energy_level = 'high' THEN 1 ELSE 0 END) as energy_high,
                SUM(CASE WHEN energy_level = 'medium' THEN 1 ELSE 0 END) as energy_medium,
                SUM(CASE WHEN energy_level = 'low' THEN 1 ELSE 0 END) as energy_low
             FROM session_feedback
             WHERE session_id = ?",
            [$sessionId]
        );

        return $result ?: [
            'total_responses' => 0,
            'avg_rating' => 0,
            'avg_enjoyment' => 0,
            'avg_difficulty' => 0,
            'energy_high' => 0,
            'energy_medium' => 0,
            'energy_low' => 0,
        ];
    }

    /**
     * Check if a player has already rated a session.
     */
    public static function hasPlayerRated(int $sessionId, int $playerId): bool
    {
        $result = static::query()
            ->where('session_id', '=', $sessionId)
            ->where('player_id', '=', $playerId)
            ->first();

        return $result !== null && $result !== false;
    }
}
