'Unauthorized']); exit; } $action = $_GET['action'] ?? null; $userId = $_SESSION['user_id']; $userType = $_SESSION['user_type']; header('Content-Type: application/json'); switch ($action) { case 'get_conversations': $db = db(); // This query is complex. It gets the last message for each conversation. $stmt = $db->prepare(" SELECT other_user.id as user_id, other_user.type as user_type, other_user.name, last_message.message, last_message.created_at, (SELECT COUNT(*) FROM messages WHERE receiver_id = :user_id AND receiver_type = :user_type AND sender_id = other_user.id AND sender_type = other_user.type AND is_read = 0) as unread_count FROM ( SELECT CASE WHEN sender_id = :user_id AND sender_type = :user_type THEN receiver_id ELSE sender_id END as other_id, CASE WHEN sender_id = :user_id AND sender_type = :user_type THEN receiver_type ELSE sender_type END as other_type, MAX(id) as last_message_id FROM messages WHERE (sender_id = :user_id AND sender_type = :user_type) OR (receiver_id = :user_id AND receiver_type = :user_type) GROUP BY other_id, other_type ) as conversations JOIN messages as last_message ON last_message.id = conversations.last_message_id JOIN ( SELECT id, name, 'coach' as type FROM coaches UNION ALL SELECT id, name, 'client' as type FROM clients ) as other_user ON other_user.id = conversations.other_id AND other_user.type = conversations.other_type ORDER BY last_message.created_at DESC "); $stmt->execute(['user_id' => $userId, 'user_type' => $userType]); $conversations = $stmt->fetchAll(PDO::FETCH_ASSOC); echo json_encode($conversations); break; case 'get_messages': $peerId = $_GET['user_id'] ?? null; $peerType = $_GET['user_type'] ?? null; if (empty($peerId) || empty($peerType)) { http_response_code(400); echo json_encode(['error' => 'Missing user_id or user_type']); exit; } $db = db(); // Mark messages as read $updateStmt = $db->prepare("UPDATE messages SET is_read = 1 WHERE sender_id = ? AND sender_type = ? AND receiver_id = ? AND receiver_type = ?"); $updateStmt->execute([$peerId, $peerType, $userId, $userType]); // Fetch messages $stmt = $db->prepare("SELECT * FROM messages WHERE (sender_id = ? AND sender_type = ? AND receiver_id = ? AND receiver_type = ?) OR (sender_id = ? AND sender_type = ? AND receiver_id = ? AND receiver_type = ?) ORDER BY created_at ASC"); $stmt->execute([$userId, $userType, $peerId, $peerType, $peerId, $peerType, $userId, $userType]); $messages = $stmt->fetchAll(PDO::FETCH_ASSOC); echo json_encode($messages); break; case 'send_message': $data = json_decode(file_get_contents('php://input'), true); if (empty($data['receiver_id']) || empty($data['receiver_type']) || empty($data['message'])) { http_response_code(400); echo json_encode(['error' => 'Missing required fields']); exit; } $db = db(); $stmt = $db->prepare("INSERT INTO messages (sender_id, sender_type, receiver_id, receiver_type, message) VALUES (?, ?, ?, ?, ?)"); if ($stmt->execute([$userId, $userType, $data['receiver_id'], $data['receiver_type'], $data['message']])) { // Send email notification require_once __DIR__ . '/../mail/MailService.php'; $receiverTable = $data['receiver_type'] === 'coach' ? 'coaches' : 'clients'; $stmt = $db->prepare("SELECT email FROM {$receiverTable} WHERE id = ?"); $stmt->execute([$data['receiver_id']]); $recipient = $stmt->fetch(PDO::FETCH_ASSOC); if ($recipient && !empty($recipient['email'])) { $to = $recipient['email']; $subject = 'You have a new message'; $messageBody = 'You have received a new message. Click here to view: View Messages'; MailService::sendMail($to, $subject, $messageBody, strip_tags($messageBody)); } echo json_encode(['success' => true]); } else { http_response_code(500); echo json_encode(['error' => 'Failed to send message']); } break; default: http_response_code(400); echo json_encode(['error' => 'Invalid action']); break; }