<?php
declare(strict_types=1);

namespace App\Modules\PoolManagement\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Modules\PoolManagement\Models\PoolConfiguration;
use App\Modules\PoolManagement\Services\PoolGridService;
use App\Modules\PoolManagement\Services\PoolOccupancyOptimizer;

class PoolGridController extends Controller
{
    public function grid(Request $request, string $id): Response
    {
        $pool = PoolConfiguration::find((int) $id);
        if (!$pool) {
            return $this->redirect('/pool')->withError('حمام السباحة غير موجود');
        }

        $date = trim((string) $request->get('date', date('Y-m-d')));
        $gridState = PoolGridService::getGridState((int) $id, $date);
        $utilization = PoolOccupancyOptimizer::getUtilizationMetrics((int) $id, $date, $date);

        return $this->view('PoolManagement.Views.grid', [
            'pool'        => $pool,
            'gridState'   => $gridState,
            'utilization' => $utilization,
            'date'        => $date,
            'bookingTypes'=> PoolConfiguration::getBookingTypes(),
        ]);
    }

    public function apiState(Request $request, string $id): Response
    {
        $date = trim((string) $request->get('date', date('Y-m-d')));
        $gridState = PoolGridService::getGridState((int) $id, $date);

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