<?php
declare(strict_types=1);

namespace App\Modules\PlayerAffairs\Models;

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

class PlayerInjury extends Model
{
    protected static string $table = 'player_injuries';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;
    protected static bool $autoTrackAuthor = true;

    protected static array $fillable = [
        'player_id',
        'discipline_id',
        'injury_type',
        'body_part',
        'severity',
        'description_ar',
        'occurred_date',
        'occurred_during',
        'session_id',
        'tournament_match_id',
        'diagnosed_by',
        'diagnosis_ar',
        'treatment_ar',
        'estimated_recovery_days',
        'actual_recovery_date',
        'status',
        'restricted_activities_json',
        'follow_up_date',
        'medical_report_document_id',
        'clearance_document_id',
        'cleared_by',
        'cleared_at',
        'notes',
        'reported_by',
    ];

    public static function getInjuryTypes(): array
    {
        return [
            'muscle'     => 'عضلية',
            'bone'       => 'عظام',
            'joint'      => 'مفاصل',
            'ligament'   => 'أربطة',
            'concussion' => 'ارتجاج',
            'skin'       => 'جلدية',
            'other'      => 'أخرى',
        ];
    }

    public static function getSeverities(): array
    {
        return [
            'minor'    => 'بسيطة',
            'moderate' => 'متوسطة',
            'severe'   => 'شديدة',
            'critical' => 'حرجة',
        ];
    }

    public static function getStatuses(): array
    {
        return [
            'active'     => 'نشطة',
            'recovering' => 'في التعافي',
            'recovered'  => 'تم الشفاء',
            'chronic'    => 'مزمنة',
        ];
    }

    public static function getBodyParts(): array
    {
        return [
            'head'          => 'الرأس',
            'neck'          => 'الرقبة',
            'shoulder'      => 'الكتف',
            'upper_arm'     => 'أعلى الذراع',
            'elbow'         => 'الكوع',
            'forearm'       => 'الساعد',
            'wrist'         => 'المعصم',
            'hand'          => 'اليد',
            'chest'         => 'الصدر',
            'back'          => 'الظهر',
            'abdomen'       => 'البطن',
            'hip'           => 'الورك',
            'thigh'         => 'الفخذ',
            'knee'          => 'الركبة',
            'shin'          => 'الساق',
            'ankle'         => 'الكاحل',
            'foot'          => 'القدم',
            'other'         => 'أخرى',
        ];
    }

    public static function getOccurredDuringOptions(): array
    {
        return [
            'training'    => 'تدريب',
            'match'       => 'مباراة',
            'warmup'      => 'إحماء',
            'outside'     => 'خارج النادي',
            'other'       => 'أخرى',
        ];
    }

    public static function getSeverityColor(string $severity): string
    {
        $colors = [
            'minor'    => '#059669',
            'moderate' => '#D97706',
            'severe'   => '#DC2626',
            'critical' => '#7C2D12',
        ];
        return $colors[$severity] ?? '#6B7280';
    }

    public static function getStatusColor(string $status): string
    {
        $colors = [
            'active'     => '#DC2626',
            'recovering' => '#D97706',
            'recovered'  => '#059669',
            'chronic'    => '#7C3AED',
        ];
        return $colors[$status] ?? '#6B7280';
    }

    /**
     * Get all injuries for a specific player.
     */
    public static function getForPlayer(int $playerId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT pi.*, p.full_name_ar AS player_name, sd.name_ar AS discipline_name
             FROM player_injuries pi
             LEFT JOIN players p ON p.id = pi.player_id
             LEFT JOIN sport_disciplines sd ON sd.id = pi.discipline_id
             WHERE pi.player_id = ?
             ORDER BY pi.occurred_date DESC",
            [$playerId]
        );
    }

    /**
     * Get all active (unresolved) injuries.
     */
    public static function getActive(): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT pi.*, p.full_name_ar AS player_name, sd.name_ar AS discipline_name
             FROM player_injuries pi
             LEFT JOIN players p ON p.id = pi.player_id
             LEFT JOIN sport_disciplines sd ON sd.id = pi.discipline_id
             WHERE pi.status IN ('active', 'recovering')
             ORDER BY pi.occurred_date DESC"
        );
    }

    /**
     * Search injuries with filters and pagination.
     */
    public static function search(array $filters, int $perPage = 25, int $page = 1): array
    {
        $db = App::getInstance()->db();

        $where = ['1=1'];
        $params = [];

        if (!empty($filters['player_id'])) {
            $where[] = 'pi.player_id = ?';
            $params[] = (int) $filters['player_id'];
        }

        if (!empty($filters['status'])) {
            $where[] = 'pi.status = ?';
            $params[] = $filters['status'];
        }

        if (!empty($filters['severity'])) {
            $where[] = 'pi.severity = ?';
            $params[] = $filters['severity'];
        }

        if (!empty($filters['injury_type'])) {
            $where[] = 'pi.injury_type = ?';
            $params[] = $filters['injury_type'];
        }

        if (!empty($filters['discipline_id'])) {
            $where[] = 'pi.discipline_id = ?';
            $params[] = (int) $filters['discipline_id'];
        }

        if (!empty($filters['date_from'])) {
            $where[] = 'pi.occurred_date >= ?';
            $params[] = $filters['date_from'];
        }

        if (!empty($filters['date_to'])) {
            $where[] = 'pi.occurred_date <= ?';
            $params[] = $filters['date_to'];
        }

        if (!empty($filters['q'])) {
            $search = '%' . $filters['q'] . '%';
            $where[] = '(p.full_name_ar LIKE ? OR pi.description_ar LIKE ? OR pi.diagnosis_ar LIKE ?)';
            $params[] = $search;
            $params[] = $search;
            $params[] = $search;
        }

        $whereClause = implode(' AND ', $where);

        // Count total
        $countSql = "SELECT COUNT(*) as total FROM player_injuries pi LEFT JOIN players p ON p.id = pi.player_id WHERE {$whereClause}";
        $countRow = $db->selectOne($countSql, $params);
        $total = (int) ($countRow['total'] ?? 0);

        // Pagination
        $lastPage = max(1, (int) ceil($total / $perPage));
        $page = min($page, $lastPage);
        $offset = ($page - 1) * $perPage;

        // Fetch data
        $dataSql = "SELECT pi.*, p.full_name_ar AS player_name, sd.name_ar AS discipline_name
                    FROM player_injuries pi
                    LEFT JOIN players p ON p.id = pi.player_id
                    LEFT JOIN sport_disciplines sd ON sd.id = pi.discipline_id
                    WHERE {$whereClause}
                    ORDER BY pi.occurred_date DESC
                    LIMIT {$perPage} OFFSET {$offset}";
        $data = $db->select($dataSql, $params);

        return [
            'data'       => $data,
            'pagination' => [
                'current_page' => $page,
                'last_page'    => $lastPage,
                'per_page'     => $perPage,
                'total'        => $total,
            ],
        ];
    }

    /**
     * Get restricted activities JSON decoded.
     */
    public function getRestrictedActivities(): array
    {
        $raw = $this->restricted_activities_json;
        if (empty($raw)) {
            return [];
        }
        $decoded = json_decode($raw, true);
        return is_array($decoded) ? $decoded : [];
    }
}
