<?php
require_once __DIR__ . '/includes/session_check.php';
require_once __DIR__ . '/includes/db.php';

header('Content-Type: application/json');

// Solo para administradores
if ($_SESSION['role'] !== 'admin') {
    echo json_encode(['success' => false, 'error' => 'Acceso denegado']);
    exit;
}

$chatId = $_GET['chat_id'] ?? null;
$lastId = isset($_GET['last_id']) ? (int)$_GET['last_id'] : 0;

if (!$chatId) {
    echo json_encode(['success' => false, 'error' => 'No se proporcionó un ID de chat']);
    exit;
}

try {
    // Consulta para obtener los mensajes
    $sql = "SELECT id, message_text, direction, timestamp, language_code 
            FROM telegram_interactions 
            WHERE chat_id = ?";
    
    $params = [$chatId];
    
    if ($lastId > 0) {
        $sql .= " AND id > ?";
        $params[] = $lastId;
    }
    
    $sql .= " ORDER BY timestamp ASC";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    
    // Obtener el ID del último mensaje para futuras actualizaciones
    $lastMessageId = $lastId;
    $messages = [];
    
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $message = [
            'id' => (int)$row['id'],
            'message_text' => $row['message_text'],
            'direction' => $row['direction'],
            'timestamp' => $row['timestamp'],
            'language_code' => $row['language_code']
        ];
        
        $messages[] = $message;
        
        // Actualizar el último ID de mensaje
        if ((int)$row['id'] > $lastMessageId) {
            $lastMessageId = (int)$row['id'];
        }
    }
    
    echo json_encode([
        'success' => true, 
        'history' => $messages,
        'last_id' => $lastMessageId
    ]);

} catch (PDOException $e) {
    error_log("Error al obtener historial de chat: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Error de base de datos: ' . $e->getMessage()]);
}
