query('SELECT id, name, is_active FROM staff ORDER BY name')->fetchAll(); // Ungelesene Nachrichten je Absender $unreadStmt = $pdo->prepare( 'SELECT from_staff_id, COUNT(*) AS cnt FROM staff_chat_messages WHERE to_staff_id=? AND is_read=0 GROUP BY from_staff_id' ); $unreadStmt->execute([$staff['id']]); $unreadByStaff = []; foreach ($unreadStmt->fetchAll() as $r) { $unreadByStaff[$r['from_staff_id']] = (int)$r['cnt']; } $conversation = []; $withStaff = null; if ($withId) { $s = $pdo->prepare('SELECT * FROM staff WHERE id=?'); $s->execute([$withId]); $withStaff = $s->fetch(); // Als gelesen markieren $pdo->prepare('UPDATE staff_chat_messages SET is_read=1 WHERE from_staff_id=? AND to_staff_id=?') ->execute([$withId, $staff['id']]); // Konversation laden $cStmt = $pdo->prepare( "SELECT m.*, sf.name AS from_name FROM staff_chat_messages m JOIN staff sf ON sf.id = m.from_staff_id WHERE (m.from_staff_id=? AND m.to_staff_id=?) OR (m.from_staff_id=? AND m.to_staff_id=?) ORDER BY m.created_at ASC LIMIT 200" ); $cStmt->execute([$staff['id'], $withId, $withId, $staff['id']]); $conversation = $cStmt->fetchAll(); } // Nachricht senden (AJAX oder normal) if ($_SERVER['REQUEST_METHOD'] === 'POST') { verify_csrf(); $toId = (int) ($_POST['to_id'] ?? 0); $msg = trim($_POST['message'] ?? ''); if ($toId && $msg !== '') { $pdo->prepare('INSERT INTO staff_chat_messages (from_staff_id, to_staff_id, message, created_at) VALUES (?,?,?,?)') ->execute([$staff['id'], $toId, $msg, db_now()]); } if (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])) { header('Content-Type: application/json'); echo json_encode(['ok' => true]); exit; } redirect('/staff/chat.php?with=' . $toId); } // AJAX: neue Nachrichten pollen if (($_GET['action'] ?? '') === 'poll' && $withId) { header('Content-Type: application/json'); $since = $_GET['since'] ?? '1970-01-01 00:00:00'; $pStmt = $pdo->prepare( "SELECT m.*, sf.name AS from_name FROM staff_chat_messages m JOIN staff sf ON sf.id = m.from_staff_id WHERE ((m.from_staff_id=? AND m.to_staff_id=?) OR (m.from_staff_id=? AND m.to_staff_id=?)) AND m.created_at > ? ORDER BY m.created_at ASC" ); $pStmt->execute([$staff['id'], $withId, $withId, $staff['id'], $since]); $pdo->prepare('UPDATE staff_chat_messages SET is_read=1 WHERE from_staff_id=? AND to_staff_id=?') ->execute([$withId, $staff['id']]); echo json_encode($pStmt->fetchAll()); exit; } $pageTitle = 'Interner Chat'; $activePage = 'chat'; require __DIR__ . '/_header.php'; ?>