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); }