<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET");

require_once '../../config/db.php';
require_once '../../core/Auth.php';

try {
    $user_id = Auth::check();

    // Fetch chats where user is a participant
    // For simplicity, we join with i_users to get the other person's info in 1-on-1 chats
    $sql = "
        SELECT 
            c.id as chat_id, 
            c.type,
            (SELECT i_username FROM i_users JOIN chat_members cm ON cm.user_id = i_users.iuid WHERE cm.chat_id = c.id AND cm.user_id != ? LIMIT 1) as other_user_name,
            (SELECT user_avatar FROM i_users JOIN chat_members cm ON cm.user_id = i_users.iuid WHERE cm.chat_id = c.id AND cm.user_id != ? LIMIT 1) as other_user_avatar,
            (SELECT content FROM messages WHERE chat_id = c.id ORDER BY id DESC LIMIT 1) as last_message,
            (SELECT created_at FROM messages WHERE chat_id = c.id ORDER BY id DESC LIMIT 1) as last_time
        FROM chats c
        JOIN chat_members m ON c.id = m.chat_id
        WHERE m.user_id = ?
        ORDER BY last_time DESC
    ";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$user_id, $user_id, $user_id]);
    $chats = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Normalizar avatares a URLs absolutas
    $server_url = "http://localhost/Juuvix_Shop/KLKAPP%20TEST";
    foreach ($chats as &$chat) {
        if ($chat['other_user_avatar'] && $chat['other_user_avatar'] !== 'default.png') {
            if (preg_match('/avatars[\\\\\/]([^\\\\\/]+)$/', $chat['other_user_avatar'], $matches)) {
                $chat['other_user_avatar'] = $server_url . "/avatars/" . $matches[1];
            } else if (strpos($chat['other_user_avatar'], 'http') === false) {
                $chat['other_user_avatar'] = $server_url . "/avatars/" . basename($chat['other_user_avatar']);
            }
        }
    }

    echo json_encode(['success' => true, 'chats' => $chats]);

} catch (Exception $e) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
