<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\SportsActivity\Models\Facility;
use App\Modules\SportsActivity\Services\MirrorStateService;

class MirrorController extends Controller
{
    /**
     * List all active facilities with links to mirror views.
     */
    public function index(Request $request): Response
    {
        $facilities = Facility::getActive();

        return $this->view('SportsActivity.Views.mirror.index', [
            'facilities' => $facilities,
        ]);
    }

    /**
     * Mirror view for a facility on today's date.
     */
    public function facility(Request $request, string $id): Response
    {
        $today = date('Y-m-d');
        return $this->renderFacilityView((int) $id, $today);
    }

    /**
     * Mirror view for a facility on a specific date.
     */
    public function facilityDate(Request $request, string $id, string $date): Response
    {
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
            return $this->redirect('/sa/mirror/' . $id)->withError('تاريخ غير صالح');
        }
        return $this->renderFacilityView((int) $id, $date);
    }

    /**
     * Render the facility mirror grid.
     */
    private function renderFacilityView(int $facilityId, string $date): Response
    {
        $state = MirrorStateService::getFacilityState($facilityId, $date);

        if (isset($state['error'])) {
            return $this->redirect('/sa/mirror')->withError($state['error']);
        }

        return $this->view('SportsActivity.Views.mirror.facility_view', [
            'facility' => $state['facility'],
            'units'    => $state['units'],
            'grid'     => $state['grid'],
            'slots'    => $state['slots'],
            'date'     => $state['date'],
        ]);
    }
}
