<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Controllers\Api;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;

class GroupQuickCreateApiController extends Controller
{
    public function create(Request $request): Response
    {
        $db = App::getInstance()->db();
        $employee = App::getInstance()->currentEmployee();

        $programId = (int) $request->post('program_id', 0);
        $nameAr = trim((string) $request->post('name_ar', ''));

        if ($programId < 1) {
            return $this->json(['success' => false, 'error' => 'البرنامج مطلوب']);
        }

        $program = $db->selectOne(
            "SELECT p.id, p.name_ar, p.max_capacity, p.discipline_id, d.name_ar as discipline_name
             FROM sa_programs p LEFT JOIN sa_disciplines d ON d.id = p.discipline_id
             WHERE p.id = ? AND p.is_active = 1",
            [$programId]
        );
        if (!$program) {
            return $this->json(['success' => false, 'error' => 'البرنامج غير موجود']);
        }

        if ($nameAr === '') {
            $count = (int) ($db->selectOne(
                "SELECT COUNT(*) as c FROM sa_groups WHERE program_id = ?",
                [$programId]
            )['c'] ?? 0);
            $nameAr = $program['name_ar'] . ' — مجموعة ' . ($count + 1);
        }

        $code = 'GRP-' . strtoupper(substr(md5((string) microtime(true)), 0, 6));

        $groupId = $db->insert('sa_groups', [
            'code'          => $code,
            'name_ar'       => $nameAr,
            'program_id'    => $programId,
            'coach_id'      => null,
            'max_capacity'  => (int) ($program['max_capacity'] ?? 20),
            'current_count' => 0,
            'is_full'       => 0,
            'status'        => 'active',
            'is_archived'   => 0,
            'created_at'    => date('Y-m-d H:i:s'),
            'updated_at'    => date('Y-m-d H:i:s'),
            'created_by'    => $employee ? (int) $employee->id : null,
        ]);

        return $this->json([
            'success' => true,
            'group'   => [
                'id'              => $groupId,
                'name_ar'         => $nameAr,
                'code'            => $code,
                'program_id'      => $programId,
                'program_name'    => $program['name_ar'],
                'discipline_name' => $program['discipline_name'] ?? '',
                'max_capacity'    => (int) ($program['max_capacity'] ?? 20),
                'current_count'   => 0,
            ],
        ]);
    }
}
