<?php
declare(strict_types=1);

namespace App\Modules\Sessions\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',
    ];

    public static function getForSession(int $sessionId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT sf.*, CASE WHEN sf.is_anonymous = 0 THEN p.full_name_ar ELSE 'مجهول' END AS player_name
             FROM session_feedback sf
             LEFT JOIN players p ON p.id = sf.player_id
             WHERE sf.session_id = ?
             ORDER BY sf.created_at DESC",
            [$sessionId]
        );
    }

    public static function getAverages(int $sessionId): array
    {
        $db = App::getInstance()->db();
        $row = $db->selectOne(
            "SELECT
                COUNT(*) AS total_responses,
                ROUND(AVG(rating), 1) AS avg_rating,
                ROUND(AVG(enjoyment_level), 1) AS avg_enjoyment,
                ROUND(AVG(difficulty_level), 1) AS avg_difficulty,
                SUM(energy_level = 'high') AS energy_high,
                SUM(energy_level = 'medium') AS energy_medium,
                SUM(energy_level = 'low') AS energy_low
             FROM session_feedback WHERE session_id = ?",
            [$sessionId]
        );
        return $row ?: [];
    }

    public static function hasPlayerRated(int $sessionId, int $playerId): bool
    {
        $db = App::getInstance()->db();
        $row = $db->selectOne(
            "SELECT 1 FROM session_feedback WHERE session_id = ? AND player_id = ?",
            [$sessionId, $playerId]
        );
        return $row !== null && $row !== false;
    }

    public static function getCoachSummary(int $coachId, ?string $dateFrom = null, ?string $dateTo = null): array
    {
        $db = App::getInstance()->db();
        $params = [$coachId];
        $sql = "SELECT
                    COUNT(*) AS total_responses,
                    ROUND(AVG(sf.rating), 1) AS avg_rating,
                    ROUND(AVG(sf.enjoyment_level), 1) AS avg_enjoyment,
                    ROUND(AVG(sf.difficulty_level), 1) AS avg_difficulty
                FROM session_feedback sf
                JOIN training_sessions ts ON ts.id = sf.session_id
                WHERE ts.coach_id = ?";
        if ($dateFrom) {
            $sql .= " AND ts.session_date >= ?";
            $params[] = $dateFrom;
        }
        if ($dateTo) {
            $sql .= " AND ts.session_date <= ?";
            $params[] = $dateTo;
        }
        return $db->selectOne($sql, $params) ?: [];
    }
}
