<?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\PlayerBookingService;

final class BookingController extends ApiController
{
    private PlayerBookingService $bookingService;

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

    public function facilities(Request $request): Response
    {
        $facilities = $this->bookingService->getBookableFacilities();
        return $this->successResponse($facilities);
    }

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

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

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

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

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

    public function myBookings(Request $request): Response
    {
        $player = App::getInstance()->currentPlayer();
        $page = max(1, $this->queryInt('page', 1));
        $perPage = min(50, max(1, $this->queryInt('per_page', 25)));

        $result = $this->bookingService->getPlayerBookings((int) $player->id, $page, $perPage);

        return $this->paginatedResponse(
            $result['data'],
            $result['pagination']['total'],
            $result['pagination']['current_page'],
            $result['pagination']['per_page']
        );
    }

    public function cancel(Request $request, string $id): Response
    {
        $player = App::getInstance()->currentPlayer();
        $success = $this->bookingService->cancelBooking((int) $id, (int) $player->id);

        if (!$success) {
            return $this->errorResponse('لا يمكن إلغاء هذا الحجز', 422);
        }

        return $this->successResponse(['cancelled' => true]);
    }
}
