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

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

$authUser = hw_get_auth_user();
$conversationId = $_GET['conversation_id'] ?? null;

if (!$conversationId) {
    echo json_encode(['success' => false, 'message' => 'Conversation ID required']);
    exit;
}

$db = hw_db();

try {
    // Verify user has access to this conversation
    $checkStmt = $db->prepare("SELECT id FROM conversations WHERE id = ? AND user_id = ?");
    $checkStmt->execute([$conversationId, $authUser['id']]);
    
    if (!$checkStmt->fetch()) {
        echo json_encode(['success' => false, 'message' => 'Unauthorized']);
        exit;
    }
    
    // Get messages
    $stmt = $db->prepare("
        SELECT 
            id,
            message,
            sender_type,
            created_at,
            is_read
        FROM messages
        WHERE conversation_id = ?
        ORDER BY created_at ASC
    ");
    
    $stmt->execute([$conversationId]);
    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Mark messages as read
    $updateStmt = $db->prepare("
        UPDATE messages 
        SET is_read = 1 
        WHERE conversation_id = ? AND sender_type = 'coach' AND is_read = 0
    ");
    $updateStmt->execute([$conversationId]);
    
    echo json_encode([
        'success' => true,
        'messages' => $messages
    ]);
    
} catch (Exception $e) {
    error_log("Error fetching messages: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Failed to load messages'
    ]);
}
