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

        $unscheduledGroups = $db->select(
            "SELECT g.id, g.code, g.name_ar, p.name_ar as program_name
             FROM sa_groups g
             JOIN sa_programs p ON p.id = g.program_id
             WHERE g.status = 'active' AND g.is_archived = 0
             AND NOT EXISTS (
                 SELECT 1 FROM sa_group_schedule gs WHERE gs.group_id = g.id AND gs.is_active = 1
             )
             ORDER BY g.name_ar"
        );

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

    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
    {
        $db = App::getInstance()->db();
        $facility = $db->selectOne(
            "SELECT facility_type FROM sa_facilities WHERE id = ? AND is_active = 1 AND is_archived = 0",
            [$facilityId]
        );

        if ($facility && $facility['facility_type'] === 'pool') {
            return $this->redirect('/sa/mirror/pool/' . $facilityId . '?date=' . $date);
        }

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

    public function poolMirror(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();
        $date = trim((string) $request->get('date', date('Y-m-d')));

        $facility = \App\Modules\SportsActivity\Services\PoolGridService::getFacility((int) $id);
        if (!$facility) {
            return $this->redirect('/sa/mirror')->withError('المرفق غير موجود');
        }

        $slots = \App\Modules\SportsActivity\Services\PoolGridService::getTimeSlots($facility);

        $groups = $db->select(
            "SELECT g.id, g.code, g.name_ar, g.current_count, g.max_capacity,
                    c.full_name_ar as coach_name, p.name_ar as program_name
             FROM sa_groups g
             LEFT JOIN sa_coaches c ON c.id = g.coach_id
             LEFT JOIN sa_programs p ON p.id = g.program_id
             WHERE g.status = 'active' AND g.is_archived = 0
             ORDER BY g.name_ar",
            []
        );

        $allPools = $db->select(
            "SELECT id, name_ar FROM sa_facilities WHERE is_active = 1 AND is_archived = 0 AND facility_type = 'pool' ORDER BY name_ar",
            []
        );

        return $this->view('SportsActivity.Views.pool-grid.manage', [
            'facility' => $facility,
            'slots'    => $slots,
            'groups'   => $groups,
            'date'     => $date,
            'allPools' => $allPools,
        ]);
    }
}
