39235-vm/api/contacts.php
2026-03-18 12:17:47 +00:00

64 lines
2.1 KiB
PHP

<?php
declare(strict_types=1);
require_once __DIR__ . '/_bootstrap.php';
ensure_schema();
$pdo = db();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$input = read_json();
$action = $input['action'] ?? '';
if (empty($action)) {
// Handle create/get contact
$phone = $input['phone'] ?? '';
if (empty($phone)) json_response(['success' => false, 'error' => 'Missing phone']);
$stmt = $pdo->prepare("SELECT * FROM contacts WHERE phone = ?");
$stmt->execute([$phone]);
$contact = $stmt->fetch();
if (!$contact) {
$stmt = $pdo->prepare("INSERT INTO contacts (phone) VALUES (?)");
$stmt->execute([$phone]);
$id = $pdo->lastInsertId();
$stmt = $pdo->prepare("SELECT * FROM contacts WHERE id = ?");
$stmt->execute([$id]);
$contact = $stmt->fetch();
}
json_response(['success' => true, 'contact' => $contact]);
}
if ($action === 'update') {
$id = (int)($input['id'] ?? 0);
if ($id <= 0) json_response(['success' => false, 'error' => 'Missing id']);
$fields = [];
$params = [];
foreach (['name', 'tags', 'status'] as $field) {
if (array_key_exists($field, $input)) {
$fields[] = "$field = ?";
$params[] = $input[$field];
}
}
if (!$fields) json_response(['success' => false, 'error' => 'No changes']);
$params[] = $id;
$stmt = $pdo->prepare("UPDATE contacts SET " . implode(', ', $fields) . " WHERE id = ?");
$stmt->execute($params);
json_response(['success' => true]);
}
json_response(['success' => false, 'error' => 'Unknown action']);
}
$sql = "
SELECT c.id, c.phone, c.name, c.tags, c.status, c.updated_at,
(SELECT body FROM messages m WHERE m.contact_id = c.id ORDER BY m.created_at DESC LIMIT 1) AS last_message,
(SELECT created_at FROM messages m WHERE m.contact_id = c.id ORDER BY m.created_at DESC LIMIT 1) AS last_time,
(SELECT COUNT(*) FROM messages m WHERE m.contact_id = c.id AND m.direction = 'in' AND m.is_read = 0) AS unread_count
FROM contacts c
ORDER BY last_time DESC, c.updated_at DESC
";
$contacts = $pdo->query($sql)->fetchAll();
json_response(['contacts' => $contacts]);