'user_id es requerido']); exit; } // Paginación: limit y before (timestamp) - cargamos N mensajes anteriores a 'before' $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 50; $limit = max(1, min(200, $limit)); $before = !empty($_GET['before']) ? $_GET['before'] : null; // expect timestamp string $db = Database::getInstance(); // Construir consulta: obtener mensajes ordenados DESC (más recientes primero) y limitar $sql = "SELECT id, user_id, COALESCE(content, message_text) as content, message_id, c.media_url, u.phone_number as user_phone, direction, message_type, status, created_at, COALESCE(c.is_read, 0) as is_read FROM conversations c LEFT JOIN users u ON c.user_id = u.id WHERE user_id = :user_id"; $params = ['user_id' => $userId]; if ($before) { $sql .= " AND created_at < :before"; $params['before'] = $before; } $sql .= " ORDER BY created_at DESC LIMIT " . $limit; $conversations = $db->fetchAll($sql, $params); // Si no hay mensajes, devolver array vacío if (empty($conversations)) { echo json_encode(['success' => true, 'data' => [], 'has_more' => false]); exit; } // Queremos devolver los mensajes en orden cronológico ascendente para la UI $conversations = array_reverse($conversations); // Indicar si hay más mensajes anteriores (si la consulta original devolvió exactamente $limit, podría haber más) $hasMore = count($conversations) >= 1 && count($conversations) == $limit ? true : false; // Si no hay mensajes en conversations, intentar con conversations if (empty($conversations)) { $conversations = $db->fetchAll( "SELECT id, user_id, message_text as content, direction, message_type, status, created_at FROM conversations WHERE user_id = :user_id ORDER BY created_at ASC", ['user_id' => $userId] ); } // Formatear fechas y limpiar datos $conversations = array_map(function($msg) { $external = (isset($msg['media_url']) && $msg['media_url']) ? (preg_match('#^https?://#i', $msg['media_url']) ? $msg['media_url'] : ("api/get_media.php?id=" . urlencode($msg['media_url']))) : null; $contentStr = $msg['content'] ?? ''; if (!$external && $contentStr) { $j = json_decode($contentStr, true); if (is_array($j)) { foreach (['image','document','audio','video'] as $k) { if (isset($j[$k]) && is_array($j[$k])) { if (!empty($j[$k]['link'])) { $external = $j[$k]['link']; break; } if (!empty($j[$k]['url'])) { $external = $j[$k]['url']; break; } if (!empty($j[$k]['id'])) { $external = "api/get_media.php?id=" . urlencode($j[$k]['id']); break; } } } if (!$external && !empty($j['link'])) $external = $j['link']; } } return [ 'id' => intval($msg['id']), 'user_id' => intval($msg['user_id']), 'content' => $msg['content'] ?? '', 'message_id' => $msg['message_id'] ?? null, 'media_url' => null, 'local_file' => $msg['local_file'] ?? null, 'local_thumb' => $msg['local_thumb'] ?? null, 'media_url_external' => $external, 'filename' => $msg['filename'] ?? null, 'mime_type' => $msg['mime_type'] ?? null, 'user_phone' => $msg['user_phone'] ?? null, 'direction' => $msg['direction'] ?? 'incoming', 'message_type' => $msg['message_type'] ?? 'text', 'status' => $msg['status'] ?? 'sent', 'created_at' => $msg['created_at'] ]; }, $conversations); // earliest message timestamp (para paginación hacia atrás) $earliest = $conversations[0]['created_at'] ?? null; echo json_encode(['success' => true, 'data' => $conversations, 'has_more' => $hasMore, 'earliest' => $earliest]); } catch (Exception $e) { error_log("Error in get_user_conversations.php: " . $e->getMessage()); http_response_code(500); echo json_encode(['error' => 'Error interno del servidor']); } ?>