<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Models;

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

class Coach extends Model
{
    protected static string $table = 'sa_coaches';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = true;
    protected static bool $dispatchEvents = 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', 'coach_type', 'academy_id', 'employee_id', 'payment_model',
        'hourly_rate', 'session_rate', 'monthly_rate',
        'max_groups', 'is_active', 'branch_id',
    ];

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

    public static function getCoachTypeOptions(): array
    {
        return [
            'independent'   => 'مدرب مستقل',
            'academy'       => 'مدرب أكاديمية',
            'club_employee' => 'موظف نادي',
        ];
    }

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

    public function getDisciplines(): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT cd.*, d.name_ar as discipline_name, d.code as discipline_code
             FROM sa_coach_disciplines cd
             JOIN sa_disciplines d ON d.id = cd.discipline_id
             WHERE cd.coach_id = ?
             ORDER BY cd.specialization_level = 'primary' DESC",
            [$this->id]
        );
    }

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

    public static function findByCode(string $code): ?static
    {
        $row = static::query()->where('code', '=', $code)->first();
        if ($row === null) {
            return null;
        }
        $instance = new static($row);
        $instance->exists = true;
        return $instance;
    }
}
