<?php
session_start();
require '../db.php';
header('Content-Type: application/json');
if (!isset($_SESSION['user_id'])) {
echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
exit;
}
$userId = $_SESSION['user_id'];
$response = ['status' => 'error'];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
try {
$success = false;
// Common params
// Common params
$replyTo = !empty($_POST['reply_to']) ? $_POST['reply_to'] : null;
$roomId = !empty($_POST['room_id']) ? intval($_POST['room_id']) : 1;
file_put_contents('../debug_send.log', "ReplyTo: " . var_export($replyTo, true) . "\n", FILE_APPEND);
// Обработка голосового сообщения
if (isset($_FILES['audio_data'])) {
$uploadDir = '../uploads/';
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0777, true);
}
$fileName = uniqid('voice_', true) . '.webm';
$filePath = $uploadDir . $fileName;
$dbPath = 'uploads/' . $fileName;
if (move_uploaded_file($_FILES['audio_data']['tmp_name'], $filePath)) {
$stmt = $pdo->prepare("INSERT INTO messages (user_id, type, content, reply_to, room_id) VALUES (?, 'voice', ?, ?, ?)");
if ($stmt->execute([$userId, $dbPath, $replyTo, $roomId])) {
$success = true;
}
} else {
$response['message'] = 'Upload Failed';
}
}
// Обработка сообщения с изображением
elseif (isset($_FILES['image_data'])) {
$uploadDir = '../uploads/';
if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
$ext = strtolower(pathinfo($_FILES['image_data']['name'], PATHINFO_EXTENSION));
$validExt = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
if (in_array($ext, $validExt)) {
$fileName = uniqid('img_', true) . '.' . $ext;
$filePath = $uploadDir . $fileName;
$dbPath = 'uploads/' . $fileName;
if (move_uploaded_file($_FILES['image_data']['tmp_name'], $filePath)) {
$stmt = $pdo->prepare("INSERT INTO messages (user_id, type, content, reply_to, room_id) VALUES (?, 'image', ?, ?, ?)");
if ($stmt->execute([$userId, $dbPath, $replyTo, $roomId])) {
$success = true;
}
}
} else {
$response['message'] = 'Invalid file type';
}
}
// Обработка текстового/системного сообщения
elseif (isset($_POST['message'])) {
$message = trim($_POST['message']);
// Разрешить тип 'system', если указан, иначе по умолчанию 'text'
$msgType = (isset($_POST['type']) && $_POST['type'] === 'system') ? 'system' : 'text';
if ($message !== '') {
$stmt = $pdo->prepare("INSERT INTO messages (user_id, type, content, reply_to, room_id) VALUES (?, ?, ?, ?, ?)");
if ($stmt->execute([$userId, $msgType, $message, $replyTo, $roomId])) {
$success = true;
}
} else {
$response['message'] = 'Empty message';
}
}
if ($success) {
$response = ['status' => 'success'];
// Триггер бота
try {
$stmt = $pdo->prepare("SELECT bot_active FROM rooms WHERE id = ?");
$stmt->execute([$roomId]);
$roomBotActive = $stmt->fetchColumn();
if ($roomBotActive) {
// Вызвать скрипт бота асинхронно
$url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]" . dirname($_SERVER['PHP_SELF']) . "/bot.php";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['room_id' => $roomId]));
curl_setopt($ch, CURLOPT_TIMEOUT, 1); // Не ждать ответа
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Передать cookie сессии, чтобы бот знал контекст, если нужно (хотя он использует свою логику)
curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
curl_exec($ch);
curl_close($ch);
}
} catch (Exception $e) { /* игнорировать ошибки бота */
}
}
} catch (PDOException $e) {
$response['message'] = $e->getMessage();
}
echo json_encode($response);
}