false, 'error' => 'Conversation and message body are required.']); exit; } $stmt = $pdo->prepare("SELECT channel FROM conversations WHERE id = ?"); $stmt->execute([$conversationId]); $channel = (string)($stmt->fetchColumn() ?: 'twilio'); $pdo->beginTransaction(); try { $msgStmt = $pdo->prepare("INSERT INTO messages (conversation_id, direction, body, status, created_at) VALUES (?, 'outbound', ?, 'queued', NOW())"); $msgStmt->execute([$conversationId, $body]); $messageId = (int)$pdo->lastInsertId(); $payload = json_encode([ 'conversation_id' => $conversationId, 'message_id' => $messageId, 'body' => $body ], JSON_UNESCAPED_UNICODE); $queueStmt = $pdo->prepare("INSERT INTO sms_queue (message_id, provider, payload, status, attempts, created_at, updated_at) VALUES (?, ?, ?, 'queued', 0, NOW(), NOW())"); $queueStmt->execute([$messageId, $channel, $payload]); $pdo->commit(); } catch (Throwable $e) { $pdo->rollBack(); http_response_code(500); echo json_encode(['success' => false, 'error' => 'Failed to queue message.']); exit; } echo json_encode(['success' => true, 'message_id' => $messageId]); exit; } $conversationId = isset($_GET['conversation_id']) ? (int)$_GET['conversation_id'] : 0; if ($conversationId <= 0) { http_response_code(422); echo json_encode(['success' => false, 'error' => 'conversation_id is required.']); exit; } $stmt = $pdo->prepare("SELECT * FROM messages WHERE conversation_id = ? ORDER BY created_at ASC"); $stmt->execute([$conversationId]); $rows = $stmt->fetchAll(); echo json_encode(['success' => true, 'messages' => $rows]);