<?php
declare(strict_types=1);

namespace App\Modules\TrainerPortal\Services;

use App\Core\App;
use App\Core\EventBus;

final class CoachDayOffService
{
    private \App\Core\Database $db;

    public function __construct()
    {
        $this->db = App::getInstance()->db();
    }

    public function requestDayOff(int $coachId, string $date, ?string $reason): array
    {
        $existing = $this->db->selectOne(
            "SELECT id FROM coach_day_off_requests WHERE coach_id = ? AND request_date = ? AND status NOT IN ('rejected')",
            [$coachId, $date]
        );

        if ($existing) {
            return ['error' => 'لديك طلب إجازة لهذا اليوم بالفعل'];
        }

        $affectedSessions = $this->db->select(
            "SELECT ts.id, ts.group_id, ts.start_time, ts.end_time, tg.name_ar as group_name
             FROM training_sessions ts
             INNER JOIN training_groups tg ON tg.id = ts.group_id
             WHERE ts.coach_id = ? AND ts.session_date = ? AND ts.status = 'scheduled'",
            [$coachId, $date]
        );

        $this->db->insert('coach_day_off_requests', [
            'coach_id' => $coachId,
            'request_date' => $date,
            'reason_ar' => $reason,
            'status' => 'pending',
            'affected_sessions_json' => json_encode($affectedSessions, JSON_UNESCAPED_UNICODE),
        ]);

        $requestId = (int) $this->db->selectOne("SELECT LAST_INSERT_ID() as id")['id'];

        $coach = $this->db->selectOne("SELECT name_ar FROM coaches WHERE id = ?", [$coachId]);

        EventBus::dispatch('coach.day_off_requested', [
            'coach_id' => $coachId,
            'coach_name' => $coach['name_ar'] ?? '',
            'request_id' => $requestId,
            'request_date' => $date,
            'affected_sessions' => count($affectedSessions),
        ]);

        return [
            'id' => $requestId,
            'affected_sessions' => count($affectedSessions),
        ];
    }

    public function getMyRequests(int $coachId): array
    {
        return $this->db->select(
            "SELECT id, request_date, reason_ar, status, replacement_coach_id,
                    replacement_volunteered_at, reviewed_at, admin_notes, created_at
             FROM coach_day_off_requests
             WHERE coach_id = ?
             ORDER BY created_at DESC",
            [$coachId]
        );
    }

    public function getRequestDetails(int $requestId, int $coachId): ?array
    {
        $request = $this->db->selectOne(
            "SELECT dor.*, c.name_ar as replacement_name
             FROM coach_day_off_requests dor
             LEFT JOIN coaches c ON c.id = dor.replacement_coach_id
             WHERE dor.id = ? AND dor.coach_id = ?",
            [$requestId, $coachId]
        );

        if ($request && $request['affected_sessions_json']) {
            $request['affected_sessions'] = json_decode($request['affected_sessions_json'], true);
        }

        return $request;
    }
}
