<?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\PoolGridService;

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

        $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
             AND f.facility_type = 'pool'
             ORDER BY f.name_ar",
            []
        );

        if (count($facilities) === 1) {
            return $this->redirect('/sa/pool-grid/' . $facilities[0]['id']);
        }

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

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

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

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