<?php
/**
 * API - Obtener mensajes recientes para dashboard
 * Fecha: 13 de noviembre de 2025
 */

require_once '../config/config.php';

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Content-Type');

try {
    $db = Database::getInstance();
    
    $recentconversations = $db->fetchAll(
        "SELECT 
            c.content,
            c.direction,
            c.message_type,
            c.created_at,
            u.phone_number,
            u.name
         FROM conversations c
         JOIN users u ON c.user_id = u.id
         WHERE c.content IS NOT NULL AND c.content != '' AND (c.canal IS NULL OR c.canal = 'bot')
         ORDER BY c.created_at DESC
         LIMIT 10"
    );
    
    echo json_encode($recentconversations);
    
} catch (Exception $e) {
    error_log("Error in get_recent_messages.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Error interno del servidor']);
}
?>