diff --git a/services/BotRouter.php b/services/BotRouter.php index e4ce684..79746c9 100644 --- a/services/BotRouter.php +++ b/services/BotRouter.php @@ -142,14 +142,15 @@ class BotRouter try { $stmt = db()->prepare("INSERT INTO outbound_queue (company_id, to_number, message_type, payload) VALUES (?, ?, ?, ?)"); $stmt->execute([$company['id'], $to, $type, $payload]); - self::log("Bot encoló respuesta {$type} para {$to}"); + $queueId = (int)db()->lastInsertId(); + self::log("Bot encoló respuesta {$type} para {$to} [q#{$queueId}]"); - $messageId = 'bot_out_' . $company['id'] . '_' . time() . '_' . bin2hex(random_bytes(4)); $content = $payload; if ($type !== 'text') { $decoded = json_decode($payload, true); $content = $decoded['caption'] ?? $decoded['body'] ?? $decoded['text'] ?? $payload; } + $messageId = 'bot_out_' . $company['id'] . '_' . time() . '_' . bin2hex(random_bytes(4)); $stmt2 = db()->prepare(" INSERT IGNORE INTO conversations (company_id, message_id, phone_number, direction, message_type, content, timestamp) @@ -163,8 +164,37 @@ class BotRouter mb_substr($content, 0, 1000), time(), ]); - } catch (\PDOException $e) { - self::log('ERROR encolando respuesta: ' . $e->getMessage()); + + $phoneNumberId = $company['phone_number_id'] ?: env('WHATSAPP_PHONE_NUMBER_ID', ''); + if ($phoneNumberId === '') { + self::log("ERROR: phone_number_id no configurado para company {$company['id']}"); + return; + } + + $decodedPayload = json_decode($payload, true); + if (!is_array($decodedPayload)) { + self::log("ERROR: payload inválido para q#{$queueId}"); + return; + } + + $sendResult = match ($type) { + 'text' => WhatsAppSender::sendText($to, $decodedPayload['text'] ?? '', $phoneNumberId), + 'interactive' => WhatsAppSender::sendInteractive($to, $decodedPayload['interactive'] ?? [], $phoneNumberId), + 'image' => WhatsAppSender::sendImage($to, $decodedPayload['media_id'] ?? $decodedPayload['url'] ?? '', $phoneNumberId, $decodedPayload['caption'] ?? null), + default => ['success' => false, 'error' => "Tipo no soportado: {$type}"], + }; + + if ($sendResult['success']) { + db()->prepare("UPDATE outbound_queue SET status = 'sent', wam_id = ?, updated_at = NOW() WHERE id = ?") + ->execute([$sendResult['wam_id'], $queueId]); + self::log("Bot envió {$type} a {$to} (wam:{$sendResult['wam_id']})"); + } else { + db()->prepare("UPDATE outbound_queue SET status = 'queued', last_error = ?, updated_at = NOW() WHERE id = ?") + ->execute([$sendResult['error'] ?? 'error', $queueId]); + self::log("Bot no pudo enviar {$type} a {$to}: {$sendResult['error']} — queda en cola"); + } + } catch (\Throwable $e) { + self::log('ERROR en enqueueResponse: ' . $e->getMessage()); } }