<?php
declare(strict_types=1);

namespace App\Modules\Coaches\Models;

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

class Coach extends Model
{
    protected static string $table = 'coaches';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = true;
    protected static bool $autoTrackAuthor = true;

    protected static array $fillable = [
        'code',
        'full_name_ar',
        'full_name_en',
        'national_id',
        'phone',
        'email',
        'date_of_birth',
        'gender',
        'photo_path',
        'bio_ar',
        'certifications_json',
        'employment_type',
        'employee_id',
        'max_players_default',
        'hourly_rate',
        'session_rate',
        'monthly_rate',
        'payment_model',
        'is_active',
    ];

    public static function getEmploymentTypes(): array
    {
        return [
            'staff'     => 'موظف (عقد دائم)',
            'contract'  => 'متعاقد',
            'freelance' => 'حر (فريلانس)',
        ];
    }

    public static function getPaymentModels(): array
    {
        return [
            'per_session'   => 'بالحصة',
            'per_player'    => 'بعدد اللاعبين',
            'monthly_fixed' => 'راتب شهري ثابت',
            'hybrid'        => 'مختلط (ثابت + حوافز)',
        ];
    }

    public static function getRoles(): array
    {
        return [
            'head_coach' => 'مدرب أول',
            'coach'      => 'مدرب',
            'assistant'  => 'مدرب مساعد',
        ];
    }

    public static function getSessionTypes(): array
    {
        return [
            'private'     => 'خاص (فردي)',
            'small_group' => 'مجموعة صغيرة (2-5)',
            'group'       => 'مجموعة (6-15)',
            'team'        => 'فريق (16+)',
        ];
    }

    public function getCertifications(): array
    {
        $raw = $this->certifications_json;
        if (empty($raw)) {
            return [];
        }
        $decoded = json_decode($raw, true);
        return is_array($decoded) ? $decoded : [];
    }

    public function getDisciplines(): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT cd.*, sd.name_ar AS discipline_name, sd.icon AS discipline_icon
             FROM coach_disciplines cd
             LEFT JOIN sport_disciplines sd ON sd.id = cd.discipline_id
             WHERE cd.coach_id = ?
             ORDER BY cd.is_primary DESC, sd.name_ar ASC",
            [(int) $this->id]
        );
    }

    public function getAcademyAssignments(): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT caa.*, a.name_ar AS academy_name, al.name_ar AS level_name
             FROM coach_academy_assignments caa
             LEFT JOIN academies a ON a.id = caa.academy_id
             LEFT JOIN academy_levels al ON al.id = caa.level_id
             WHERE caa.coach_id = ? AND caa.is_active = 1
             ORDER BY caa.assigned_from DESC",
            [(int) $this->id]
        );
    }

    public function getAvailability(): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT * FROM coach_availability
             WHERE coach_id = ? AND is_available = 1
             AND (effective_from IS NULL OR effective_from <= CURDATE())
             AND (effective_to IS NULL OR effective_to >= CURDATE())
             ORDER BY day_of_week ASC, start_time ASC",
            [(int) $this->id]
        );
    }

    public static function allActive(): array
    {
        return static::query()
            ->where('is_active', '=', 1)
            ->orderBy('full_name_ar', 'ASC')
            ->get();
    }

    public static function search(array $filters, int $perPage = 25, int $page = 1): array
    {
        $query = static::query();

        if (!empty($filters['q'])) {
            $search = '%' . $filters['q'] . '%';
            $query = $query->whereRaw(
                '(`full_name_ar` LIKE ? OR `full_name_en` LIKE ? OR `code` LIKE ? OR `phone` LIKE ?)',
                [$search, $search, $search, $search]
            );
        }

        if (!empty($filters['employment_type'])) {
            $query = $query->where('employment_type', '=', $filters['employment_type']);
        }

        if (!empty($filters['payment_model'])) {
            $query = $query->where('payment_model', '=', $filters['payment_model']);
        }

        if (isset($filters['is_active']) && $filters['is_active'] !== '') {
            $query = $query->where('is_active', '=', (int) $filters['is_active']);
        }

        $query = $query->orderBy('full_name_ar', 'ASC');

        return $query->paginate($perPage, $page);
    }

    public static function getByDiscipline(int $disciplineId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT c.* FROM coaches c
             INNER JOIN coach_disciplines cd ON cd.coach_id = c.id
             WHERE cd.discipline_id = ? AND c.is_active = 1 AND c.is_archived = 0
             ORDER BY c.full_name_ar ASC",
            [$disciplineId]
        );
    }
}
