<?php
declare(strict_types=1);

namespace App\Modules\PlayerApi\Controllers\Api;

use App\Core\ApiController;
use App\Core\App;
use App\Core\Request;
use App\Core\Response;

final class SportBrowseController extends ApiController
{
    public function __construct(Request $request)
    {
        parent::__construct();
        $this->request = $request;
    }

    public function listSports(Request $request): Response
    {
        $db = App::getInstance()->db();

        $sports = $db->select(
            "SELECT id, name_ar, name_en, category, description_ar, is_active
             FROM sport_disciplines WHERE is_active = 1 AND is_archived = 0
             ORDER BY name_ar"
        );

        return $this->successResponse($sports);
    }

    public function listGroups(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();
        $disciplineId = (int) $id;

        $filters = [];
        $params = [$disciplineId];
        $where = ['tg.discipline_id = ?', 'tg.is_active = 1', 'tg.is_archived = 0', 'tg.is_full = 0'];

        if ($request->get('level_id')) {
            $where[] = 'tg.level_id = ?';
            $params[] = (int) $request->get('level_id');
        }
        if ($request->get('coach_id')) {
            $where[] = 'tg.coach_id = ?';
            $params[] = (int) $request->get('coach_id');
        }
        if ($request->get('day_of_week')) {
            $where[] = 'tg.day_of_week = ?';
            $params[] = $request->get('day_of_week');
        }
        if ($request->get('group_type')) {
            $where[] = 'tg.group_type = ?';
            $params[] = $request->get('group_type');
        }
        if ($request->get('gender')) {
            $where[] = 'tg.gender_restriction = ?';
            $params[] = $request->get('gender');
        }

        $whereClause = implode(' AND ', $where);

        $groups = $db->select(
            "SELECT tg.id, tg.name_ar, tg.group_type, tg.day_of_week, tg.start_time, tg.end_time,
                    tg.min_capacity, tg.max_capacity, tg.current_count, tg.gender_restriction,
                    tg.age_from, tg.age_to, tg.pricing_tier,
                    c.name_ar as coach_name,
                    f.name_ar as facility_name,
                    al.name_ar as level_name
             FROM training_groups tg
             LEFT JOIN coaches c ON c.id = tg.coach_id
             LEFT JOIN facilities f ON f.id = tg.facility_id
             LEFT JOIN academy_levels al ON al.id = tg.level_id
             WHERE {$whereClause}
             ORDER BY tg.day_of_week, tg.start_time",
            $params
        );

        return $this->successResponse($groups);
    }

    public function groupDetails(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();
        $groupId = (int) $id;

        $group = $db->selectOne(
            "SELECT tg.*, c.name_ar as coach_name, c.phone as coach_phone,
                    f.name_ar as facility_name, f.facility_type,
                    al.name_ar as level_name,
                    a.name_ar as academy_name
             FROM training_groups tg
             LEFT JOIN coaches c ON c.id = tg.coach_id
             LEFT JOIN facilities f ON f.id = tg.facility_id
             LEFT JOIN academy_levels al ON al.id = tg.level_id
             LEFT JOIN academies a ON a.id = tg.academy_id
             WHERE tg.id = ? AND tg.is_archived = 0",
            [$groupId]
        );

        if (!$group) {
            return $this->errorResponse('المجموعة غير موجودة', 404);
        }

        $pricing = $db->selectOne(
            "SELECT member_rate, non_member_rate
             FROM activity_pricing
             WHERE entity_type = 'discipline' AND entity_id = ? AND is_active = 1
             AND (effective_from IS NULL OR effective_from <= CURDATE())
             AND (effective_to IS NULL OR effective_to >= CURDATE())
             ORDER BY effective_from DESC LIMIT 1",
            [$group['discipline_id']]
        );

        $group['pricing'] = $pricing;
        $group['available_spots'] = max(0, (int) $group['max_capacity'] - (int) $group['current_count']);

        return $this->successResponse($group);
    }
}
