<?php
declare(strict_types=1);

namespace App\Modules\TrainerPortal\Controllers\Api;

use App\Core\ApiController;
use App\Core\App;
use App\Core\Request;
use App\Core\Response;
use App\Core\Exceptions\ValidationException;
use App\Modules\TrainerPortal\Services\CoachDayOffService;

final class DayOffController extends ApiController
{
    private CoachDayOffService $dayOffService;

    public function __construct(Request $request)
    {
        parent::__construct();
        $this->request = $request;
        $this->dayOffService = new CoachDayOffService();
    }

    public function request(Request $request): Response
    {
        try {
            $data = $this->validatedJson([
                'date' => 'required|string',
                'reason' => 'nullable|string|max:500',
            ]);
        } catch (ValidationException $e) {
            return $this->errorResponse('بيانات غير صالحة', 422, $e->errors());
        }

        $coach = App::getInstance()->currentCoach();
        $result = $this->dayOffService->requestDayOff((int) $coach->id, $data['date'], $data['reason'] ?? null);

        if (isset($result['error'])) {
            return $this->errorResponse($result['error'], 422);
        }

        return $this->successResponse($result, 201);
    }

    public function myRequests(Request $request): Response
    {
        $coach = App::getInstance()->currentCoach();
        $requests = $this->dayOffService->getMyRequests((int) $coach->id);
        return $this->successResponse($requests);
    }

    public function requestDetails(Request $request, string $id): Response
    {
        $coach = App::getInstance()->currentCoach();
        $details = $this->dayOffService->getRequestDetails((int) $id, (int) $coach->id);

        if (!$details) {
            return $this->errorResponse('الطلب غير موجود', 404);
        }

        return $this->successResponse($details);
    }
}
