<?php
declare(strict_types=1);

namespace App\Modules\PlayerApi\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\PlayerApi\Services\PlayerFreeTimeService;

final class FreeTimeController extends ApiController
{
    private PlayerFreeTimeService $freeTimeService;

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

    public function availableFacilities(Request $request): Response
    {
        $facilities = $this->freeTimeService->getFreeTimeFacilities();
        return $this->successResponse($facilities);
    }

    public function slots(Request $request, string $facilityId): Response
    {
        $date = $request->get('date', date('Y-m-d'));
        $slots = $this->freeTimeService->getFreeTimeSlots((int) $facilityId, $date);
        return $this->successResponse($slots);
    }

    public function enter(Request $request): Response
    {
        try {
            $data = $this->validatedJson([
                'facility_id' => 'required|numeric',
                'date' => 'nullable|string',
                'entry_time' => 'nullable|string',
                'activity_type' => 'nullable|string|in:free_swim,recreation,gym,open_play',
            ]);
        } catch (ValidationException $e) {
            return $this->errorResponse('بيانات غير صالحة', 422, $e->errors());
        }

        $player = App::getInstance()->currentPlayer();
        $result = $this->freeTimeService->recordEntry((int) $player->id, $data);

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

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