<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Controllers\Api;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Modules\SportsActivity\Services\PoolGridService;

class PoolGridApiController extends Controller
{
    public function state(Request $request, string $id): Response
    {
        $date = $request->get('date', date('Y-m-d'));

        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
            return $this->json(['error' => 'تاريخ غير صالح'], 400);
        }

        $state = PoolGridService::getGridState((int) $id, $date);

        if (isset($state['error'])) {
            return $this->json(['error' => $state['error']], 404);
        }

        return $this->json($state);
    }

    public function assign(Request $request, string $id): Response
    {
        $body = $request->jsonBody();
        $date = trim((string) ($body['date'] ?? ''));
        $action = trim((string) ($body['action'] ?? ''));
        $cells = $body['cells'] ?? [];
        $groupId = !empty($body['group_id']) ? (int) $body['group_id'] : null;
        $notes = trim((string) ($body['notes'] ?? ''));

        if (!$date || !$action || empty($cells)) {
            return $this->json(['error' => 'بيانات ناقصة'], 400);
        }

        $result = PoolGridService::bulkAssign((int) $id, $date, $action, $cells, $groupId, $notes ?: null);

        return $this->json($result, $result['success'] ? 200 : 422);
    }

    public function clear(Request $request, string $id): Response
    {
        $body = $request->jsonBody();
        $date = trim((string) ($body['date'] ?? ''));
        $cells = $body['cells'] ?? [];

        if (!$date || empty($cells)) {
            return $this->json(['error' => 'بيانات ناقصة'], 400);
        }

        $result = PoolGridService::bulkClear((int) $id, $date, $cells);

        return $this->json($result);
    }
}
