Files
maria_uslugi/messages/api/open_or_create_conversation.php
2026-03-05 10:25:39 +01:00

74 lines
2.5 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
// /messages/api/open_or_create_conversation.php
declare(strict_types=1);
require_once __DIR__ . '/../_bootstrap.php';
header('Content-Type: application/json; charset=utf-8');
$role = $GLOBALS['MESSAGES_CTX']['role']; // 'praticien' | 'client'
$meId = (int)$GLOBALS['MESSAGES_CTX']['me_id'];
$peerRole = $_POST['peer_role'] ?? $_GET['peer_role'] ?? '';
$peerId = (int)($_POST['peer_id'] ?? $_GET['peer_id'] ?? 0);
// sécurité minimale + cohérence rôles
if (!in_array($peerRole, ['praticien','client'], true) || $peerId<=0) {
json_response(['ok'=>false,'error'=>'bad_params'],400);
}
if ($role === $peerRole) { // on attend l’autre rôle
json_response(['ok'=>false,'error'=>'target_must_be_other_role'],400);
}
// Déterminer les 2 ids
if ($role === 'client') {
$clientId = $meId;
$praticienId = $peerId;
} else { // role=praticien
$praticienId = $meId;
$clientId = $peerId;
}
// Chercher une conversation existante entre ces 2
$stmt = $pdo->prepare("SELECT * FROM conversations WHERE praticien_id=? AND client_id=? LIMIT 1");
$stmt->execute([$praticienId,$clientId]);
$conv = $stmt->fetch(PDO::FETCH_ASSOC);
if ($conv) {
// Restaurer pour moi si supprimée/archivée et rouvrir si besoin
if ($role === 'client') {
$pdo->prepare("UPDATE conversations
SET deleted_for_client=0, archived_by_client=0, status='open', updated_at=NOW()
WHERE id=?")->execute([(int)$conv['id']]);
} else {
$pdo->prepare("UPDATE conversations
SET deleted_for_praticien=0, archived_by_praticien=0, status='open', updated_at=NOW()
WHERE id=?")->execute([(int)$conv['id']]);
}
json_response(['ok'=>true,'conversation_id'=>(int)$conv['id']]);
}
// Sinon, créer la conversation + counters
$pdo->beginTransaction();
try{
$pdo->prepare("INSERT INTO conversations
(praticien_id, client_id, status,
archived_by_praticien, archived_by_client,
deleted_for_praticien, deleted_for_client,
created_at, updated_at)
VALUES (?, ?, 'open', 0, 0, 0, 0, NOW(), NOW())
")->execute([$praticienId,$clientId]);
$newId = (int)$pdo->lastInsertId();
// counters (si table présente)
if ($pdo->query("SHOW TABLES LIKE 'conversation_counters'")->rowCount()){
$pdo->prepare("INSERT INTO conversation_counters (conversation_id, p_unread, c_unread) VALUES (?,0,0)")
->execute([$newId]);
}
$pdo->commit();
json_response(['ok'=>true,'conversation_id'=>$newId]);
}catch(Throwable $e){
$pdo->rollBack();
json_response(['ok'=>false,'error'=>'create_failed'],500);
}