<?php
// /api/seller/messages.php — GET conversations | POST reply
require_once __DIR__ . '/../init.php';

$user = AuthMiddleware::verifyToken();
AuthMiddleware::requireRole(['seller', 'admin']);

$sellerId = (int)$user['id'];
$db       = DB::conn();
$method   = $_SERVER['REQUEST_METHOD'];

// ─── GET — conversations list or thread ──────────────────────
if ($method === 'GET') {
    $buyerId = isset($_GET['buyer_id']) ? (int)$_GET['buyer_id'] : 0;

    if ($buyerId) {
        // Get full thread with a specific buyer
        $stmt = $db->prepare(
            'SELECT m.id, m.sender_role, m.body, m.is_read, m.created_at,
                    u.username as sender_name
             FROM messages m
             JOIN users u ON u.id = IF(m.sender_role="buyer", m.buyer_id, m.seller_id)
             WHERE m.seller_id = ? AND m.buyer_id = ?
             ORDER BY m.created_at ASC'
        );
        $stmt->execute([$sellerId, $buyerId]);
        $thread = $stmt->fetchAll();

        // Mark as read
        $db->prepare(
            'UPDATE messages SET is_read = 1 WHERE seller_id = ? AND buyer_id = ? AND sender_role = "buyer"'
        )->execute([$sellerId, $buyerId]);

        Response::success('Thread fetched.', ['messages' => $thread]);
    } else {
        // Get conversations list (latest message per buyer)
        $stmt = $db->prepare("
            SELECT m.buyer_id, u.username as buyer_name, u.avatar_url,
                   MAX(m.created_at) as last_at,
                   (SELECT body FROM messages WHERE seller_id = m.seller_id AND buyer_id = m.buyer_id ORDER BY created_at DESC LIMIT 1) as last_msg,
                   SUM(CASE WHEN m.sender_role='buyer' AND m.is_read=0 THEN 1 ELSE 0 END) as unread
            FROM messages m
            JOIN users u ON u.id = m.buyer_id
            WHERE m.seller_id = ?
            GROUP BY m.buyer_id
            ORDER BY last_at DESC
        ");
        $stmt->execute([$sellerId]);
        $convs = $stmt->fetchAll();

        foreach ($convs as &$c) {
            $c['buyer_id'] = (int)$c['buyer_id'];
            $c['unread']   = (int)$c['unread'];
        }
        Response::success('Conversations fetched.', ['conversations' => $convs]);
    }
}

// ─── POST — seller sends reply ────────────────────────────────
if ($method === 'POST') {
    $body    = getBody();
    $buyerId = (int)($body['buyer_id'] ?? 0);
    $msgBody = trim($body['body'] ?? '');

    if (!$buyerId || !$msgBody) Response::error('buyer_id and body required.');

    // Verify buyer exists
    $stmt = $db->prepare('SELECT id FROM users WHERE id = ? AND role = "buyer"');
    $stmt->execute([$buyerId]);
    if (!$stmt->fetch()) Response::error('Buyer not found.', 404);

    $db->prepare(
        'INSERT INTO messages (seller_id, buyer_id, sender_role, body) VALUES (?, ?, "seller", ?)'
    )->execute([$sellerId, $buyerId, $msgBody]);

    Response::success('ส่งข้อความสำเร็จ', [], 201);
}

Response::error('Method not allowed.', 405);
