<?php
declare(strict_types=1);

namespace App\Modules\TrainerPortal\Services;

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

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

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

    public function getAvailableRequests(int $coachId): array
    {
        return $this->db->select(
            "SELECT dor.id, dor.coach_id, dor.request_date, dor.affected_sessions_json, dor.created_at,
                    c.name_ar as coach_name
             FROM coach_day_off_requests dor
             INNER JOIN coaches c ON c.id = dor.coach_id
             WHERE dor.status = 'pending' AND dor.coach_id != ? AND dor.replacement_coach_id IS NULL
             AND dor.request_date >= CURDATE()
             ORDER BY dor.request_date ASC",
            [$coachId]
        );
    }

    public function volunteer(int $requestId, int $volunteerCoachId): array
    {
        $request = $this->db->selectOne(
            "SELECT * FROM coach_day_off_requests WHERE id = ? AND status = 'pending' AND replacement_coach_id IS NULL",
            [$requestId]
        );

        if (!$request) {
            return ['error' => 'الطلب غير متاح أو تم تغطيته بالفعل'];
        }

        if ((int) $request['coach_id'] === $volunteerCoachId) {
            return ['error' => 'لا يمكنك التطوع لتغطية إجازتك الخاصة'];
        }

        $conflict = $this->db->selectOne(
            "SELECT id FROM training_sessions
             WHERE coach_id = ? AND session_date = ? AND status = 'scheduled'",
            [$volunteerCoachId, $request['request_date']]
        );

        if ($conflict) {
            return ['error' => 'لديك تدريب في نفس اليوم، لا يمكنك التطوع'];
        }

        $this->db->update('coach_day_off_requests', [
            'replacement_coach_id' => $volunteerCoachId,
            'replacement_volunteered_at' => date('Y-m-d H:i:s'),
            'status' => 'covered',
            'updated_at' => date('Y-m-d H:i:s'),
        ], 'id = ?', [$requestId]);

        $affectedSessions = json_decode($request['affected_sessions_json'] ?? '[]', true);
        foreach ($affectedSessions as $session) {
            $this->db->update('training_sessions', [
                'coach_id' => $volunteerCoachId,
            ], 'id = ? AND status = ?', [(int) $session['id'], 'scheduled']);
        }

        $volunteerCoach = $this->db->selectOne("SELECT name_ar FROM coaches WHERE id = ?", [$volunteerCoachId]);
        $originalCoach = $this->db->selectOne("SELECT name_ar FROM coaches WHERE id = ?", [(int) $request['coach_id']]);

        EventBus::dispatch('coach.replacement_confirmed', [
            'original_coach_id' => (int) $request['coach_id'],
            'original_coach_name' => $originalCoach['name_ar'] ?? '',
            'replacement_coach_id' => $volunteerCoachId,
            'replacement_name' => $volunteerCoach['name_ar'] ?? '',
            'request_id' => $requestId,
            'request_date' => $request['request_date'],
        ]);

        return [
            'success' => true,
            'message' => 'تم تأكيد التطوع كبديل بنجاح',
        ];
    }
}
