<?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\Services\MirrorStateService;

class MirrorController extends Controller
{
    public function index(Request $request): Response
    {
        $db = App::getInstance()->db();

        $disciplines = $db->select(
            "SELECT d.id, d.name_ar, d.name_en, COUNT(f.id) as facility_count
             FROM sa_disciplines d
             INNER JOIN sa_facilities f ON f.discipline_id = d.id AND f.is_active = 1 AND f.is_archived = 0
             WHERE d.is_active = 1 AND d.is_archived = 0
             GROUP BY d.id, d.name_ar, d.name_en
             ORDER BY d.name_ar"
        );

        $facilities = $db->select(
            "SELECT f.*, d.name_ar as discipline_name
             FROM sa_facilities f
             LEFT JOIN sa_disciplines d ON d.id = f.discipline_id
             WHERE f.is_active = 1 AND f.is_archived = 0
             ORDER BY d.name_ar, f.name_ar"
        );

        $grouped = [];
        foreach ($facilities as $f) {
            $dName = $f['discipline_name'] ?? 'أخرى';
            $grouped[$dName][] = $f;
        }

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

    public function byDiscipline(Request $request, string $id): Response
    {
        $today = date('Y-m-d');
        return $this->renderDisciplineView((int) $id, $today);
    }

    public function byDisciplineDate(Request $request, string $id, string $date): Response
    {
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
            return $this->redirect('/sa/mirror')->withError('تاريخ غير صالح');
        }
        return $this->renderDisciplineView((int) $id, $date);
    }

    public function facility(Request $request, string $id): Response
    {
        $today = date('Y-m-d');
        return $this->renderFacilityView((int) $id, $today);
    }

    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);
    }

    private function renderDisciplineView(int $disciplineId, string $date): Response
    {
        $state = MirrorStateService::getMultiFacilityState($disciplineId, $date);

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

        return $this->view('SportsActivity.Views.mirror.discipline_view', [
            'discipline'     => $state['discipline'],
            'facilityStates' => $state['facilities'],
            'date'           => $date,
        ]);
    }

    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'],
        ]);
    }
}
