<?php
/**
 * API - Lista de contactos del chat turnero
 * Devuelve usuarios que tienen conversaciones con canal='turnero',
 * con el último mensaje y conteo de no leídos.
 */

require_once __DIR__ . '/../../../config/config.php';
requireAuthentication();

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-cache, no-store, must-revalidate');

try {
    $db     = Database::getInstance();
    $limit  = max(1, min(200, intval($_GET['limit'] ?? 50)));
    $page   = max(1, intval($_GET['page'] ?? 1));
    $offset = ($page - 1) * $limit;
    $search = trim($_GET['search'] ?? '');

    $whereClauses = ["c.canal = 'turnero'"];
    $params = [];

    if ($search !== '') {
        $whereClauses[] = "(u.name LIKE :s1 OR u.phone_number LIKE :s2)";
        $params[':s1'] = '%' . $search . '%';
        $params[':s2'] = '%' . $search . '%';
    }

    $where = implode(' AND ', $whereClauses);

    $sql = "SELECT
                u.id            AS user_id,
                COALESCE(u.name, u.phone_number) AS name,
                u.phone_number,
                u.avatar_url,
                lm.content      AS last_message,
                lm.direction    AS last_direction,
                lm.message_type AS last_message_type,
                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
            FROM users u
            JOIN conversations c  ON c.user_id = u.id AND c.canal = 'turnero'
            LEFT JOIN (
                SELECT t1.*
                FROM conversations t1
                JOIN (
                    SELECT user_id, MAX(created_at) AS last_time
                    FROM conversations
                    WHERE canal = 'turnero'
                    GROUP BY user_id
                ) t2 ON t1.user_id = t2.user_id AND t1.created_at = t2.last_time AND t1.canal = 'turnero'
            ) lm ON lm.user_id = u.id
            WHERE {$where}
            GROUP BY u.id
            ORDER BY lm.created_at DESC
            LIMIT {$limit} OFFSET {$offset}";

    $rows = $db->fetchAll($sql, $params);

    $totalRow = $db->fetch(
        "SELECT COUNT(DISTINCT c.user_id) AS cnt FROM conversations c
         JOIN users u ON u.id = c.user_id
         WHERE c.canal = 'turnero'" . ($search !== '' ? " AND (u.name LIKE :s1 OR u.phone_number LIKE :s2)" : ''),
        $search !== '' ? [':s1' => '%'.$search.'%', ':s2' => '%'.$search.'%'] : []
    );

    $data = array_map(function($r) {
        return [
            'user_id'        => intval($r['user_id']),
            'name'           => $r['name'],
            'phone_number'   => $r['phone_number'],
            'avatar_url'     => $r['avatar_url'] ?? null,
            'last_message'   => $r['last_message'] ?? '',
            'last_direction' => $r['last_direction'] ?? 'incoming',
            'last_message_type' => $r['last_message_type'] ?? 'text',
            'last_time'      => $r['last_time'] ?? null,
            'unread_count'   => intval($r['unread_count']),
        ];
    }, $rows ?: []);

    $total   = intval($totalRow['cnt'] ?? 0);
    $hasMore = ($page * $limit) < $total;

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

} catch (Exception $e) {
    error_log('chat_get_list.php: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Error interno']);
}
