<?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,
            u.status as user_status,
            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,
            u.advisor_requested as advisor_requested,
            u.terms_pending as terms_pending,
            u.terms_accepted_at as terms_accepted_at,
            COUNT(*) as total_conversations,
            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, u.status, c.content, c.direction, c.message_type, c.created_at, c.status, u.advisor_requested, u.terms_pending, u.terms_accepted_at
         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'],
            'user_status' => $conv['user_status'] ?? 'active',
            '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',
            'advisor_requested' => !empty($conv['advisor_requested']) ? true : false,
            'terms_pending' => !empty($conv['terms_pending']) ? true : false,
            'terms_accepted_at' => $conv['terms_accepted_at'] ?? null,
            'total_conversations' => intval($conv['total_conversations']),
            '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';
}
?>