89 lines
2.8 KiB
PHP
89 lines
2.8 KiB
PHP
<?php
|
||
// /messages/start.php
|
||
declare(strict_types=1);
|
||
require_once __DIR__ . '/_bootstrap.php';
|
||
|
||
$role = $GLOBALS['MESSAGES_CTX']['role']; // 'praticien' | 'client'
|
||
$meId = (int)$GLOBALS['MESSAGES_CTX']['me_id'];
|
||
|
||
$pid = isset($_GET['praticien_id']) ? (int)$_GET['praticien_id'] : 0;
|
||
$cid = isset($_GET['client_id']) ? (int)$_GET['client_id'] : 0;
|
||
|
||
// Déterminer l’interlocuteur selon mon rôle
|
||
if ($role === 'client' && $pid > 0) {
|
||
$praticienId = $pid;
|
||
$clientId = $meId;
|
||
} elseif ($role === 'praticien' && $cid > 0) {
|
||
$praticienId = $meId;
|
||
$clientId = $cid;
|
||
} else {
|
||
http_response_code(400);
|
||
echo "Bad params";
|
||
exit;
|
||
}
|
||
|
||
// Chercher une conversation existante
|
||
$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 côté moi + rouvrir
|
||
if ($role === 'client') {
|
||
$pdo->prepare("
|
||
UPDATE conversations
|
||
SET deleted_for_client = 0,
|
||
deleted_for_praticien = 0,
|
||
archived_by_client = 0,
|
||
archived_by_praticien = 0,
|
||
status = 'open',
|
||
updated_at = NOW()
|
||
WHERE id = ?
|
||
")->execute([(int)$conv['id']]);
|
||
} else { // praticien
|
||
$pdo->prepare("
|
||
UPDATE conversations
|
||
SET deleted_for_praticien = 0,
|
||
deleted_for_client = 0,
|
||
archived_by_praticien = 0,
|
||
archived_by_client = 0,
|
||
status = 'open',
|
||
updated_at = NOW()
|
||
WHERE id = ?
|
||
")->execute([(int)$conv['id']]);
|
||
}
|
||
$convId = (int)$conv['id'];
|
||
} else {
|
||
// Créer la conversation
|
||
$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]);
|
||
|
||
$convId = (int)$pdo->lastInsertId();
|
||
|
||
// counters optionnels
|
||
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([$convId]);
|
||
}
|
||
|
||
$pdo->commit();
|
||
} catch (Throwable $e) {
|
||
$pdo->rollBack();
|
||
http_response_code(500);
|
||
echo "Create failed";
|
||
exit;
|
||
}
|
||
}
|
||
|
||
// Redirection vers l’UI
|
||
header('Location: /messages/?conv=' . $convId);
|
||
exit;
|