'Unauthorized']); exit(); } if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['error' => 'Method Not Allowed']); exit(); } $user_id = $_SESSION['user_id']; $data = json_decode(file_get_contents('php://input'), true); $channel_id = $data['channel_id'] ?? null; $content = $data['content'] ?? null; if (!$channel_id || !$content) { http_response_code(400); echo json_encode(['error' => 'Channel ID and content are required']); exit(); } $content = trim($content); if (empty($content)) { http_response_code(400); echo json_encode(['error' => 'Message content cannot be empty']); exit(); } try { $pdo = db(); // Verify user has access to this channel's server $stmt = $pdo->prepare(" SELECT c.id FROM channels c JOIN servers s ON c.server_id = s.id JOIN server_members sm ON s.id = sm.server_id WHERE c.id = ? AND sm.user_id = ? "); $stmt->execute([$channel_id, $user_id]); if ($stmt->fetch() === false) { http_response_code(403); echo json_encode(['error' => 'Forbidden']); exit(); } // Insert message $stmt = $pdo->prepare(" INSERT INTO messages (channel_id, user_id, content) VALUES (?, ?, ?) "); $stmt->execute([$channel_id, $user_id, $content]); header('Content-Type: application/json'); echo json_encode(['success' => true, 'message' => 'Message sent']); } catch (PDOException $e) { error_log("Send Message Error: " . $e->getMessage()); http_response_code(500); echo json_encode(['error' => 'Internal Server Error']); }