<?php
declare(strict_types=1);

namespace App\Modules\FacilityDashboards\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\FacilityDashboards\Services\MirrorDisplayService;

class MirrorDisplayController extends Controller
{
    public function index(Request $request): Response
    {
        $facilityType = trim((string) $request->get('type', ''));
        $disciplineId = $request->get('discipline_id', '') !== '' ? (int) $request->get('discipline_id') : null;

        $states = MirrorDisplayService::getFacilityStates(
            $facilityType ?: null,
            $disciplineId
        );

        $db = App::getInstance()->db();
        $facilityTypes = $db->select(
            "SELECT DISTINCT facility_type FROM facilities WHERE is_active = 1 AND is_archived = 0 ORDER BY facility_type"
        );
        $disciplines = $db->select(
            "SELECT id, name_ar FROM sport_disciplines WHERE is_active = 1 AND is_archived = 0 ORDER BY name_ar"
        );

        return $this->view('FacilityDashboards.Views.mirror', [
            'states'        => $states,
            'facilityTypes' => $facilityTypes,
            'disciplines'   => $disciplines,
            'currentType'   => $facilityType,
            'currentDisc'   => $disciplineId,
        ]);
    }

    public function apiState(Request $request): Response
    {
        $facilityType = trim((string) $request->get('type', ''));
        $disciplineId = $request->get('discipline_id', '') !== '' ? (int) $request->get('discipline_id') : null;

        $states = MirrorDisplayService::getFacilityStates(
            $facilityType ?: null,
            $disciplineId
        );

        return $this->json([
            'states'    => $states,
            'timestamp' => date('Y-m-d H:i:s'),
            'time'      => date('H:i'),
        ]);
    }
}
