'bad_params'], 400); } // Autorisation d’accès à la conversation assert_conversation_access($pdo, $convId, $role, $meId); try { $pdo->beginTransaction(); // ================================================== // 1) Marquer les messages comme lus // ================================================== $sql = " INSERT IGNORE INTO message_reads (message_id, user_role, user_id, read_at) SELECT m.id, ?, ?, NOW() FROM messages m WHERE m.conversation_id = ? "; $pdo->prepare($sql)->execute([$role, $meId, $convId]); // ================================================== // 2) Reset compteur de la conversation // ================================================== if ($role === 'praticien') { $pdo->prepare(" UPDATE conversation_counters SET p_unread = 0 WHERE conversation_id = ? ")->execute([$convId]); } else { $pdo->prepare(" UPDATE conversation_counters SET c_unread = 0 WHERE conversation_id = ? ")->execute([$convId]); } // ================================================== // 3) Recalcul msg_unread GLOBAL pour le compte // (source de vérité = conversation_counters) // ================================================== $compteId = (int)($_SESSION['compte_id'] ?? 0); $msgUnread = 0; $rdvUnread = 0; if ($compteId > 0) { if ($role === 'praticien') { $stmt = $pdo->prepare(" SELECT COALESCE(SUM(cc.p_unread), 0) FROM conversations c JOIN conversation_counters cc ON cc.conversation_id = c.id WHERE c.praticien_id = ? "); $stmt->execute([$meId]); } else { $stmt = $pdo->prepare(" SELECT COALESCE(SUM(cc.c_unread), 0) FROM conversations c JOIN conversation_counters cc ON cc.conversation_id = c.id WHERE c.client_id = ? "); $stmt->execute([$meId]); } $msgUnread = (int)$stmt->fetchColumn(); // ================================================== // 4) Mise à jour push_badge_counters // ⚠️ msg_unread uniquement (rdv_unread préservé) // ================================================== $pdo->prepare(" INSERT INTO push_badge_counters (compte_id, msg_unread, rdv_unread, updated_at) VALUES (:cid, :msg, 0, NOW()) ON DUPLICATE KEY UPDATE msg_unread = VALUES(msg_unread), updated_at = NOW() ")->execute([ ':cid' => $compteId, ':msg' => $msgUnread, ]); // Relire rdv_unread sans le modifier $stmt = $pdo->prepare(" SELECT rdv_unread FROM push_badge_counters WHERE compte_id = :cid "); $stmt->execute([':cid' => $compteId]); $rdvUnread = (int)($stmt->fetchColumn() ?? 0); } $pdo->commit(); // ================================================== // 5) Réponse JSON pour synchro UI + badge PWA // ================================================== json_response([ 'ok' => true, 'msg_unread' => $msgUnread, 'rdv_unread' => $rdvUnread, 'app_badge' => $msgUnread + $rdvUnread, ]); } catch (Throwable $e) { if ($pdo->inTransaction()) { $pdo->rollBack(); } json_response(['error' => 'server_error'], 500); }