<?php
class ProfessionalChatGroup
{
    public static function forProfessional(int $professionalId): array
    {
        Database::migrate();
        $stmt = Database::pdo()->prepare("SELECT g.*,
                (SELECT COUNT(*) FROM professional_chat_group_members gm2 WHERE gm2.group_id=g.id) AS member_count
            FROM professional_chat_groups g
            INNER JOIN professional_chat_group_members gm ON gm.group_id=g.id
            WHERE gm.professional_id=?
            ORDER BY g.id DESC");
        $stmt->execute([$professionalId]);
        return $stmt->fetchAll();
    }

    public static function countForProfessional(int $professionalId): int
    {
        Database::migrate();
        $stmt=Database::pdo()->prepare('SELECT COUNT(*) FROM professional_chat_group_members WHERE professional_id=?');
        $stmt->execute([$professionalId]);
        return (int)$stmt->fetchColumn();
    }

    public static function findForProfessional(int $groupId, int $professionalId): ?array
    {
        Database::migrate();
        $stmt=Database::pdo()->prepare("SELECT g.* FROM professional_chat_groups g
            INNER JOIN professional_chat_group_members gm ON gm.group_id=g.id
            WHERE g.id=? AND gm.professional_id=? LIMIT 1");
        $stmt->execute([$groupId,$professionalId]);
        return $stmt->fetch() ?: null;
    }

    public static function canAccess(int $groupId, int $professionalId): bool
    {
        return self::findForProfessional($groupId,$professionalId)!==null;
    }

    public static function members(int $groupId): array
    {
        Database::migrate();
        $stmt=Database::pdo()->prepare("SELECT p.id,p.name,p.type,p.profile_photo_path,p.internal_code
            FROM professional_chat_group_members gm
            INNER JOIN professionals p ON p.id=gm.professional_id
            WHERE gm.group_id=? AND p.is_active=1 ORDER BY p.name");
        $stmt->execute([$groupId]);
        return $stmt->fetchAll();
    }

    public static function create(int $ownerId, string $name, array $memberIds): array
    {
        Database::migrate();
        $name=trim($name);
        if($name==='') return ['ok'=>false,'message'=>'Informe o nome do grupo de instrutores.'];
        if(mb_strlen($name)>180) return ['ok'=>false,'message'=>'O nome do grupo é muito grande.'];
        $memberIds=array_values(array_unique(array_filter(array_map('intval',$memberIds))));
        if(!in_array($ownerId,$memberIds,true)) $memberIds[]=$ownerId;
        $pdo=Database::pdo();
        try{
            $pdo->beginTransaction();
            $valid=[];
            if($memberIds){
                $marks=implode(',',array_fill(0,count($memberIds),'?'));
                $stmt=$pdo->prepare("SELECT id FROM professionals WHERE is_active=1 AND id IN ({$marks})");
                $stmt->execute($memberIds);
                $valid=array_map('intval',array_column($stmt->fetchAll(),'id'));
            }
            if(!in_array($ownerId,$valid,true)){
                $pdo->rollBack();
                return ['ok'=>false,'message'=>'Instrutor responsável não encontrado.'];
            }
            $stmt=$pdo->prepare('INSERT INTO professional_chat_groups (name,owner_professional_id,created_at) VALUES (?,?,?)');
            $stmt->execute([$name,$ownerId,date('Y-m-d H:i:s')]);
            $groupId=(int)$pdo->lastInsertId();
            $sql=Database::driver()==='mysql'
                ? 'INSERT IGNORE INTO professional_chat_group_members (group_id,professional_id,joined_at) VALUES (?,?,?)'
                : 'INSERT OR IGNORE INTO professional_chat_group_members (group_id,professional_id,joined_at) VALUES (?,?,?)';
            $insert=$pdo->prepare($sql);
            foreach($valid as $professionalId) $insert->execute([$groupId,$professionalId,date('Y-m-d H:i:s')]);
            $pdo->commit();
            return ['ok'=>true,'message'=>'Grupo privado de instrutores criado.','group_id'=>$groupId];
        }catch(Throwable $e){
            if($pdo->inTransaction()) $pdo->rollBack();
            return ['ok'=>false,'message'=>'Não foi possível criar o grupo: '.$e->getMessage()];
        }
    }
}
