39121-vm/api/conversations.php
2026-03-12 03:03:10 +00:00

33 lines
861 B
PHP

<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/bootstrap.php';
header('Content-Type: application/json');
$twilioId = (int)($_GET['twilio_number_id'] ?? 0);
if ($twilioId <= 0) {
echo json_encode(['items' => []]);
exit;
}
$stmt = db()->prepare("
SELECT c.id, ct.name, ct.phone,
m.body AS last_message,
c.last_message_at AS last_time
FROM conversations c
JOIN contacts ct ON ct.id = c.contact_id
LEFT JOIN messages m ON m.id = (
SELECT id FROM messages
WHERE conversation_id = c.id
ORDER BY created_at DESC
LIMIT 1
)
WHERE c.twilio_number_id = :twilio
ORDER BY c.last_message_at DESC, c.created_at DESC
");
$stmt->bindValue(':twilio', $twilioId, PDO::PARAM_INT);
$stmt->execute();
$items = $stmt->fetchAll();
echo json_encode(['items' => $items]);