<?php
declare(strict_types=1);

namespace App\Modules\Coaches\Services;

use App\Core\App;
use App\Modules\Coaches\Models\Coach;

final class CoachService
{
    public static function createCoach(array $data, array $disciplineIds = []): Coach
    {
        if (empty($data['code'])) {
            $base = $data['full_name_en'] ?? $data['full_name_ar'] ?? 'COACH';
            $code = strtoupper(preg_replace('/[^A-Z0-9]/i', '_', $base));
            $data['code'] = 'C_' . substr($code, 0, 20) . '_' . time() % 10000;
        }
        $data['code'] = strtoupper($data['code']);

        $existing = Coach::query()->where('code', '=', $data['code'])->first();
        if ($existing) {
            $data['code'] = $data['code'] . '_' . bin2hex(random_bytes(2));
        }

        $coach = Coach::create($data);

        if (!empty($disciplineIds)) {
            self::syncDisciplines((int) $coach->id, $disciplineIds);
        }

        return $coach;
    }

    public static function syncDisciplines(int $coachId, array $disciplineIds, ?int $primaryId = null): void
    {
        $db = App::getInstance()->db();
        $db->delete('coach_disciplines', 'coach_id = ?', [$coachId]);

        foreach ($disciplineIds as $discId) {
            $db->insert('coach_disciplines', [
                'coach_id'             => $coachId,
                'discipline_id'        => (int) $discId,
                'is_primary'           => ($primaryId !== null && (int) $discId === $primaryId) ? 1 : 0,
                'specialization_level' => 'general',
            ]);
        }
    }

    public static function assignToAcademy(int $coachId, int $academyId, ?int $levelId, string $role, ?int $maxPlayers, string $from, ?string $to = null): void
    {
        $db = App::getInstance()->db();
        $db->insert('coach_academy_assignments', [
            'coach_id'      => $coachId,
            'academy_id'    => $academyId,
            'level_id'      => $levelId,
            'role'          => $role,
            'max_players'   => $maxPlayers,
            'assigned_from' => $from,
            'assigned_to'   => $to,
            'is_active'     => 1,
        ]);
    }

    public static function unassignFromAcademy(int $assignmentId): void
    {
        $db = App::getInstance()->db();
        $db->update('coach_academy_assignments', [
            'is_active'   => 0,
            'assigned_to' => date('Y-m-d'),
        ], 'id = ?', [$assignmentId]);
    }

    public static function setAvailability(int $coachId, array $slots): void
    {
        $db = App::getInstance()->db();
        $db->delete('coach_availability', 'coach_id = ?', [$coachId]);

        foreach ($slots as $slot) {
            $db->insert('coach_availability', [
                'coach_id'       => $coachId,
                'day_of_week'    => (int) $slot['day_of_week'],
                'start_time'     => $slot['start_time'],
                'end_time'       => $slot['end_time'],
                'is_available'   => 1,
                'effective_from' => $slot['effective_from'] ?? null,
                'effective_to'   => $slot['effective_to'] ?? null,
            ]);
        }
    }
}
