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

        $fullGroup = $db->selectOne(
            "SELECT g.id, g.name_ar, g.code, g.current_count, g.max_capacity, g.is_full,
                    p.id as program_id, p.name_ar as program_name,
                    p.monthly_fee_member, p.monthly_fee_nonmember,
                    d.id as discipline_id, d.name_ar as discipline_name,
                    c.full_name_ar as coach_name
             FROM sa_groups g
             LEFT JOIN sa_programs p ON p.id = g.program_id
             LEFT JOIN sa_disciplines d ON d.id = p.discipline_id
             LEFT JOIN sa_coaches c ON c.id = g.coach_id
             WHERE g.id = ?",
            [$groupId]
        );

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