<?php
require_once __DIR__ . '/../lib.php';
hw_require_auth(['client']);

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

$authUser = hw_get_auth_user();
$db = hw_db();

try {
    // Get all conversations for this user
    $stmt = $db->prepare("
        SELECT 
            c.id,
            c.coach_id,
            co.display_name as coach_name,
            c.last_message_time,
            c.last_message,
            (SELECT COUNT(*) FROM messages WHERE conversation_id = c.id AND sender_type = 'coach' AND is_read = 0) as unread_count,
            0 as is_online
        FROM conversations c
        LEFT JOIN coaches co ON c.coach_id = co.id
        WHERE c.user_id = ?
        ORDER BY c.last_message_time DESC
    ");
    
    $stmt->execute([$authUser['id']]);
    $conversations = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'conversations' => $conversations
    ]);
    
} catch (Exception $e) {
    error_log("Error fetching conversations: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Failed to load conversations'
    ]);
}
