funcional
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
/**
|
||||
* API - Obtener mensajes de una conversación específica
|
||||
*/
|
||||
|
||||
require_once '../config/config.php';
|
||||
|
||||
// Modo debug: desactivar autenticación si existe el parámetro debug
|
||||
$debugMode = isset($_GET['debug']) && $_GET['debug'] === 'true';
|
||||
|
||||
if (!$debugMode) {
|
||||
requireAuthentication();
|
||||
}
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
header('Access-Control-Allow-Origin: *');
|
||||
header('Access-Control-Allow-Methods: GET');
|
||||
header('Access-Control-Allow-Headers: Content-Type');
|
||||
|
||||
try {
|
||||
$user_id = $_GET['user_id'] ?? null;
|
||||
|
||||
if (!$user_id) {
|
||||
http_response_code(400);
|
||||
echo json_encode(['error' => 'user_id es requerido']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
|
||||
// Obtener información del usuario
|
||||
$user = $db->fetch(
|
||||
"SELECT id, phone_number, name FROM users WHERE id = ?",
|
||||
[$user_id]
|
||||
);
|
||||
|
||||
if (!$user) {
|
||||
http_response_code(404);
|
||||
echo json_encode(['error' => 'Usuario no encontrado']);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Obtener todos los mensajes de la conversación
|
||||
$messages = $db->fetchAll(
|
||||
"SELECT
|
||||
id,
|
||||
message_id,
|
||||
direction,
|
||||
message_type,
|
||||
content,
|
||||
status,
|
||||
created_at
|
||||
FROM conversations
|
||||
WHERE user_id = ?
|
||||
ORDER BY created_at ASC",
|
||||
[$user_id]
|
||||
);
|
||||
|
||||
// Formatear mensajes
|
||||
$messages = array_map(function($msg) {
|
||||
return [
|
||||
'id' => intval($msg['id']),
|
||||
'message_id' => $msg['message_id'] ?? '',
|
||||
'direction' => $msg['direction'],
|
||||
'message_type' => $msg['message_type'],
|
||||
'content' => $msg['content'] ?? '',
|
||||
'status' => $msg['status'] ?? 'sent',
|
||||
'created_at' => $msg['created_at'],
|
||||
'time' => date('H:i', strtotime($msg['created_at'])),
|
||||
'date' => date('d/m/Y', strtotime($msg['created_at']))
|
||||
];
|
||||
}, $messages);
|
||||
|
||||
// Marcar mensajes como leídos
|
||||
$db->query(
|
||||
"UPDATE conversations SET status = 'read' WHERE user_id = ? AND direction = 'incoming' AND status != 'read'",
|
||||
[$user_id]
|
||||
);
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'user' => [
|
||||
'id' => intval($user['id']),
|
||||
'phone_number' => $user['phone_number'],
|
||||
'name' => $user['name'] ?? $user['phone_number']
|
||||
],
|
||||
'messages' => $messages,
|
||||
'total_messages' => count($messages)
|
||||
]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
error_log("Error in get_conversation_detail.php: " . $e->getMessage());
|
||||
http_response_code(500);
|
||||
echo json_encode(['error' => 'Error interno del servidor: ' . $e->getMessage()]);
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
/**
|
||||
* API - Obtener conversaciones agrupadas por usuario con último mensaje
|
||||
*/
|
||||
|
||||
require_once '../config/config.php';
|
||||
|
||||
// Modo debug: desactivar autenticación si existe el parámetro debug
|
||||
$debugMode = isset($_GET['debug']) && $_GET['debug'] === 'true';
|
||||
|
||||
if (!$debugMode) {
|
||||
requireAuthentication();
|
||||
}
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
header('Access-Control-Allow-Origin: *');
|
||||
header('Access-Control-Allow-Methods: GET');
|
||||
header('Access-Control-Allow-Headers: Content-Type');
|
||||
|
||||
try {
|
||||
$db = Database::getInstance();
|
||||
|
||||
// Obtener conversaciones agrupadas por usuario con último mensaje
|
||||
$conversations = $db->fetchAll(
|
||||
"SELECT
|
||||
u.id as user_id,
|
||||
u.phone_number,
|
||||
COALESCE(u.name, u.phone_number) as name,
|
||||
c.content as last_message,
|
||||
c.direction as last_direction,
|
||||
c.message_type as last_message_type,
|
||||
c.created_at as last_message_time,
|
||||
c.status as last_message_status,
|
||||
COUNT(*) as total_messages,
|
||||
SUM(CASE WHEN c.direction = 'incoming' AND c.status = 'received' THEN 1 ELSE 0 END) as unread_count
|
||||
FROM users u
|
||||
LEFT JOIN conversations c ON u.id = c.user_id
|
||||
WHERE c.id IN (
|
||||
SELECT MAX(id)
|
||||
FROM conversations
|
||||
GROUP BY user_id
|
||||
)
|
||||
GROUP BY u.id, u.phone_number, u.name, c.content, c.direction, c.message_type, c.created_at, c.status
|
||||
ORDER BY c.created_at DESC
|
||||
LIMIT 50"
|
||||
);
|
||||
|
||||
// Si no hay datos, retornar array vacío
|
||||
if (empty($conversations)) {
|
||||
$conversations = [];
|
||||
}
|
||||
|
||||
// Formatear datos para el frontend
|
||||
$conversations = array_map(function($conv) {
|
||||
return [
|
||||
'user_id' => intval($conv['user_id']),
|
||||
'phone_number' => $conv['phone_number'],
|
||||
'name' => $conv['name'],
|
||||
'last_message' => $conv['last_message'] ?? '',
|
||||
'last_direction' => $conv['last_direction'] ?? 'incoming',
|
||||
'last_message_type' => $conv['last_message_type'] ?? 'text',
|
||||
'last_message_time' => $conv['last_message_time'],
|
||||
'last_message_status' => $conv['last_message_status'] ?? 'sent',
|
||||
'total_messages' => intval($conv['total_messages']),
|
||||
'unread_count' => intval($conv['unread_count']),
|
||||
'time_ago' => timeAgo($conv['last_message_time'])
|
||||
];
|
||||
}, $conversations);
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'conversations' => $conversations,
|
||||
'total' => count($conversations)
|
||||
]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
error_log("Error in get_conversation_list.php: " . $e->getMessage());
|
||||
http_response_code(500);
|
||||
echo json_encode(['error' => 'Error interno del servidor: ' . $e->getMessage()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calcular tiempo transcurrido
|
||||
*/
|
||||
function timeAgo($datetime) {
|
||||
$time = time() - strtotime($datetime);
|
||||
|
||||
if ($time < 60) return 'Ahora';
|
||||
if ($time < 3600) return floor($time/60) . 'm';
|
||||
if ($time < 86400) return floor($time/3600) . 'h';
|
||||
if ($time < 2592000) return floor($time/86400) . 'd';
|
||||
if ($time < 31536000) return floor($time/2592000) . ' mes';
|
||||
return floor($time/31536000) . ' año';
|
||||
}
|
||||
?>
|
||||
+64
-4
@@ -18,21 +18,38 @@ if (!$debugMode) {
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
header('Access-Control-Allow-Origin: *');
|
||||
header('Access-Control-Allow-Methods: POST');
|
||||
header('Access-Control-Allow-Methods: POST, OPTIONS');
|
||||
header('Access-Control-Allow-Headers: Content-Type');
|
||||
|
||||
// Manejar preflight OPTIONS request
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
|
||||
http_response_code(200);
|
||||
exit;
|
||||
}
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
http_response_code(405);
|
||||
echo json_encode(['error' => 'Método no permitido']);
|
||||
echo json_encode(['error' => 'Método no permitido. Use POST.', 'method_received' => $_SERVER['REQUEST_METHOD']]);
|
||||
exit;
|
||||
}
|
||||
|
||||
try {
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
$rawInput = file_get_contents('php://input');
|
||||
$input = json_decode($rawInput, true);
|
||||
|
||||
// Debug logging
|
||||
if ($debugMode) {
|
||||
error_log("=== SEND MESSAGE DEBUG ===");
|
||||
error_log("Method: " . $_SERVER['REQUEST_METHOD']);
|
||||
error_log("Content-Type: " . ($_SERVER['CONTENT_TYPE'] ?? 'not set'));
|
||||
error_log("Raw input: " . $rawInput);
|
||||
error_log("Parsed JSON: " . json_encode($input));
|
||||
error_log("========================");
|
||||
}
|
||||
|
||||
if (!$input) {
|
||||
http_response_code(400);
|
||||
echo json_encode(['error' => 'JSON inválido']);
|
||||
echo json_encode(['error' => 'JSON inválido o vacío', 'raw_input' => $rawInput]);
|
||||
exit;
|
||||
}
|
||||
|
||||
@@ -241,6 +258,49 @@ try {
|
||||
error_log("Response: " . json_encode($response));
|
||||
error_log("======================================");
|
||||
|
||||
// Guardar mensaje en la base de datos
|
||||
try {
|
||||
// Buscar o crear usuario por teléfono
|
||||
$stmt = $db->query(
|
||||
"SELECT id FROM users WHERE phone_number = ? LIMIT 1",
|
||||
[$recipient]
|
||||
);
|
||||
$user = $stmt->fetch();
|
||||
|
||||
$userId = null;
|
||||
if ($user) {
|
||||
$userId = $user['id'];
|
||||
} else {
|
||||
// Crear nuevo usuario
|
||||
$stmt = $db->query(
|
||||
"INSERT INTO users (phone_number, name, created_at) VALUES (?, ?, NOW())",
|
||||
[$recipient, $recipient, date('Y-m-d H:i:s')]
|
||||
);
|
||||
$userId = $db->lastInsertId();
|
||||
}
|
||||
|
||||
if ($userId) {
|
||||
// Preparar datos del mensaje
|
||||
$messageContent = '';
|
||||
$messageType = $type;
|
||||
|
||||
if ($type === 'text') {
|
||||
$messageContent = $input['message'];
|
||||
} elseif ($type === 'template') {
|
||||
$templateName = $input['template'] ?? $input['template_name'] ?? '';
|
||||
$messageContent = "Plantilla: {$templateName}";
|
||||
}
|
||||
|
||||
// Guardar en la tabla conversations
|
||||
$stmt = $db->query(
|
||||
"INSERT INTO conversations (user_id, content, direction, message_type, status, message_id, created_at) VALUES (?, ?, 'outgoing', ?, 'sent', ?, NOW())",
|
||||
[$userId, $messageContent, $messageType, $response['messages'][0]['id'] ?? null]
|
||||
);
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
error_log("Error guardando mensaje en base de datos: " . $e->getMessage());
|
||||
}
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'message' => 'Mensaje enviado correctamente',
|
||||
|
||||
Reference in New Issue
Block a user