<?php
declare(strict_types=1);

namespace App\Modules\PlaygroundAdmin\Controllers;

use App\Core\Controller;
use App\Core\App;
use App\Core\Request;
use App\Core\Response;
use App\Modules\PlaygroundAdmin\Services\PlaygroundMirrorService;

final class PlaygroundMirrorController extends Controller
{
    private PlaygroundMirrorService $mirrorService;

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

    public function mirror(Request $request, string $id): Response
    {
        $this->authorize('playground.view');
        $date = date('Y-m-d');
        return $this->renderMirror((int) $id, $date);
    }

    public function mirrorDate(Request $request, string $id, string $date): Response
    {
        $this->authorize('playground.view');
        return $this->renderMirror((int) $id, $date);
    }

    public function mirrorState(Request $request, string $id): Response
    {
        $this->authorize('playground.view');
        $date = $request->get('date', date('Y-m-d'));
        $state = $this->mirrorService->getMirrorState((int) $id, $date);
        return $this->json($state);
    }

    private function renderMirror(int $playgroundId, string $date): Response
    {
        $db = App::getInstance()->db();
        $playground = $db->selectOne("SELECT * FROM playground_configurations WHERE id = ?", [$playgroundId]);

        if (!$playground) {
            return $this->redirect('/playgrounds')->withError('الملعب غير موجود');
        }

        $state = $this->mirrorService->getMirrorState($playgroundId, $date);

        return $this->view('PlaygroundAdmin.Views.mirror', [
            'playground' => $playground,
            'date' => $date,
            'state' => $state,
        ]);
    }
}
