client = $client; } public function ensureSubaccount(Unit $unit): UnitPaymentAccount { $existingAccount = UnitPaymentAccount::where('unit_id', $unit->id)->first(); if ($existingAccount && $existingAccount->asaas_account_id) { return $existingAccount; } if (empty($unit->cnpj)) { throw new Exception("A unidade {$unit->fantasy_name} não possui um CNPJ cadastrado. O CNPJ é obrigatório para criar a subconta."); } $payload = [ 'name' => $unit->fantasy_name ?? $unit->social_reason ?? 'Unidade Ginástica do Cérebro', 'email' => $unit->email, 'cpfCnpj' => preg_replace('/[^0-9]/', '', $unit->cnpj), 'mobilePhone' => preg_replace('/[^0-9]/', '', $unit->cell_number ?? $unit->phone_number ?? ''), 'address' => $unit->street, 'addressNumber' => $unit->address_number ?? 'S/N', 'province' => $unit->neighborhood, 'postalCode' => preg_replace('/[^0-9]/', '', $unit->postal_code), 'companyType' => 'LIMITED', ]; $response = $this->client->post('/accounts', $payload); return UnitPaymentAccount::updateOrCreate( ['unit_id' => $unit->id], [ 'asaas_account_id' => $response['id'], 'asaas_wallet_id' => $response['walletId'], 'asaas_api_key' => $response['apiKey'], 'status' => 'ACTIVE', 'onboarded_at' => now(), ] ); } }