<?php
/**
 * API - Obtener conversaciones recientes
 * Fecha: 4 de enero de 2026
 */

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

// Verificar autenticación
requireAuthentication();

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();
    
    // Paginación: recibir page y limit desde query string (con límites razonables)
    $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 50;
    $limit = max(1, min(200, $limit)); // máximo 200 por página
    $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
    $offset = ($page - 1) * $limit;
    
    // Parámetro de búsqueda
    $search = isset($_GET['search']) ? trim($_GET['search']) : '';

    // Obtener conversaciones agregadas por usuario: último mensaje + conteo de no leídos + avatar
    $filter = isset($_GET['filter']) ? strtolower(trim($_GET['filter'])) : 'all';

    $sql = "SELECT 
            u.id AS user_id,
            COALESCE(u.name, u.phone_number) AS name,
            u.phone_number,
            u.avatar_url,
            u.bot_enabled,
            u.on_hold,
            u.advisor_requested,
            u.in_service,
            u.in_service_by,
            u.in_service_at,
            lm.message_id AS last_message_id,
            lm.content AS last_message,
            lm.direction AS direction,
            lm.message_type AS message_type,
            lm.local_file AS last_local_file,
            lm.local_thumb AS last_local_thumb,
            lm.created_at AS last_time,
            IFNULL(SUM(CASE WHEN c.direction = 'incoming' AND (c.is_read IS NULL OR c.is_read = 0) THEN 1 ELSE 0 END), 0) AS unread_count";
    
    // Si hay búsqueda, agregar campo para ordenar por relevancia
    if (!empty($search)) {
        $sql .= ",
            (CASE 
                WHEN u.name LIKE ? THEN 3
                WHEN u.phone_number LIKE ? THEN 2
                ELSE 1
            END) AS relevance";
    }
    
    $sql .= "
         FROM users u
         LEFT JOIN conversations c ON c.user_id = u.id AND (c.canal IS NULL OR c.canal = 'bot')
         LEFT JOIN (
             SELECT t1.* FROM conversations t1
             JOIN (
                 SELECT user_id, MAX(created_at) AS last_time FROM conversations
                 WHERE (canal IS NULL OR canal = 'bot') GROUP BY user_id
             ) t2 ON t1.user_id = t2.user_id AND t1.created_at = t2.last_time
             WHERE (t1.canal IS NULL OR t1.canal = 'bot')
         ) lm ON lm.user_id = u.id";

    // Agregar condición de búsqueda si existe
    if (!empty($search)) {
        $sql .= "
         WHERE (
            u.name LIKE ?
            OR u.phone_number LIKE ?
            OR EXISTS (
                SELECT 1 FROM conversations c2
                WHERE c2.user_id = u.id
                AND c2.content LIKE ?
                AND (c2.canal IS NULL OR c2.canal = 'bot')
            )
         )";
    }
    
    $sql .= "
         GROUP BY u.id";

    // Aplicar filtro 'unread' si se solicita
    if ($filter === 'unread') {
        $sql .= " HAVING IFNULL(SUM(CASE WHEN c.direction = 'incoming' AND (c.is_read IS NULL OR c.is_read = 0) THEN 1 ELSE 0 END), 0) > 0";
    }

    // Ordenar por relevancia si hay búsqueda, sino por fecha
    if (!empty($search)) {
        $sql .= "\n         ORDER BY relevance DESC, lm.created_at DESC";
    } else {
        $sql .= "\n         ORDER BY lm.created_at DESC";
    }
    
    $sql .= "\n         LIMIT %d OFFSET %d";

    // Preparar parámetros para la consulta
    $params = [];
    if (!empty($search)) {
        $searchParam = '%' . $search . '%';
        // Para el campo de relevancia
        $params[] = $searchParam; // name LIKE
        $params[] = $searchParam; // phone_number LIKE
        // Para el WHERE
        $params[] = $searchParam; // name LIKE
        $params[] = $searchParam; // phone_number LIKE
        $params[] = $searchParam; // content LIKE
    }
    
    $finalSql = sprintf($sql, $limit, $offset);
    
    if (!empty($params)) {
        $conversations = $db->fetchAll($finalSql, $params);
    } else {
        $conversations = $db->fetchAll($finalSql);
    }

    // Conteo total de usuarios con al menos una conversación (útil para paginar)
    if (!empty($search)) {
        // Conteo con búsqueda
        $searchParam = '%' . $search . '%';
        $countSql = "SELECT COUNT(DISTINCT u.id) AS count 
                     FROM users u
                     LEFT JOIN conversations c ON c.user_id = u.id
                     WHERE (
                        u.name LIKE ? 
                        OR u.phone_number LIKE ? 
                        OR EXISTS (
                            SELECT 1 FROM conversations c2 
                            WHERE c2.user_id = u.id 
                            AND c2.content LIKE ?
                        )
                     )";
        if ($filter === 'unread') {
            $countSql .= " AND c.direction = 'incoming' AND (c.is_read IS NULL OR c.is_read = 0)";
        }
        $totalRow = $db->fetch($countSql, [$searchParam, $searchParam, $searchParam]);
    } else {
        // Conteo normal sin búsqueda
        if ($filter === 'unread') {
            $totalRow = $db->fetch("SELECT COUNT(DISTINCT user_id) AS count FROM conversations c WHERE c.direction = 'incoming' AND (c.is_read IS NULL OR c.is_read = 0) AND (c.canal IS NULL OR c.canal = 'bot')");
        } else {
            $totalRow = $db->fetch("SELECT COUNT(DISTINCT user_id) AS count FROM conversations WHERE (canal IS NULL OR canal = 'bot')");
        }
    }
    $total = isset($totalRow['count']) ? intval($totalRow['count']) : 0;

    // Si no hay datos, retornar array vacío
    if (empty($conversations)) {
        $conversations = [];
    }

    // Si hay búsqueda, obtener el snippet del mensaje que coincidió (no solo el último)
    $matchedContentMap = [];
    if (!empty($search)) {
        $userIds = array_column($conversations, 'user_id');
        if (!empty($userIds)) {
            $placeholders = implode(',', array_fill(0, count($userIds), '?'));
            $searchParam = '%' . $search . '%';
            $params2 = array_merge([$searchParam], $userIds);
            $matchedRows = $db->fetchAll(
                "SELECT user_id, content FROM conversations
                 WHERE content LIKE ? AND user_id IN ($placeholders)
                 ORDER BY created_at DESC",
                $params2
            );
            // Guardar el primer mensaje coincidente por usuario
            foreach ($matchedRows as $row) {
                if (!isset($matchedContentMap[$row['user_id']])) {
                    $matchedContentMap[$row['user_id']] = mb_substr($row['content'], 0, 80);
                }
            }
        }
    }

    // Formatear datos para el frontend
    $conversations = array_map(function($conv) use ($matchedContentMap, $search) {
        $matched = null;
        if (!empty($search) && isset($matchedContentMap[$conv['user_id']])) {
            $matched = $matchedContentMap[$conv['user_id']];
        }
        return [
            'user_id' => intval($conv['user_id']),
            'name' => $conv['name'] ?? $conv['phone_number'],
            'phone_number' => $conv['phone_number'],
            'avatar_url' => $conv['avatar_url'] ?? null,
            'last_message' => $conv['last_message'] ?? '',
            'last_time' => $conv['last_time'] ?? null,
            'direction' => $conv['direction'] ?? 'incoming',
            'message_type' => $conv['message_type'] ?? 'text',
            'last_local_file' => $conv['last_local_file'] ?? null,
            'last_local_thumb' => $conv['last_local_thumb'] ?? null,
            'unread_count' => intval($conv['unread_count'] ?? 0),
            'bot_enabled' => isset($conv['bot_enabled']) ? (bool)$conv['bot_enabled'] : true,
            'on_hold' => isset($conv['on_hold']) ? (bool)$conv['on_hold'] : false,
            'advisor_requested' => isset($conv['advisor_requested']) ? (bool)$conv['advisor_requested'] : false,
            'in_service' => isset($conv['in_service']) ? (bool)$conv['in_service'] : false,
            'in_service_by' => isset($conv['in_service_by']) ? intval($conv['in_service_by']) : null,
            'in_service_at' => $conv['in_service_at'] ?? null,
            'matched_content' => $matched  // snippet del mensaje que coincidió (solo en búsqueda)
        ];
    }, $conversations);

    // Indicar metadatos para la paginación
    $hasMore = ($page * $limit) < $total;

    echo json_encode([
        'success' => true,
        'data' => $conversations,
        'page' => $page,
        'limit' => $limit,
        'has_more' => (bool)$hasMore,
        'total' => $total
    ]);

    
} catch (Exception $e) {
    error_log("Error in get_conversations.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Error interno del servidor: ' . $e->getMessage()]);
}
?>