<?php
require_once __DIR__.'/../includes/functions.php';
header('Content-Type: application/json');
try {
    $u = current_user();
    if (!$u) { throw new Exception('Please login to view messages.'); }
    mj_realtime_chat_ensure_schema();
    $chatId = (int)($_GET['chat_id'] ?? $_POST['chat_id'] ?? 0);
    $afterId = (int)($_GET['after_id'] ?? $_POST['after_id'] ?? 0);
    if ($chatId <= 0) { throw new Exception('Missing conversation.'); }
    $chat = one('SELECT * FROM mj_chats WHERE id=? LIMIT 1', [$chatId]);
    if (!$chat) { throw new Exception('Conversation not found.'); }
    $role = mj_chat_assert_participant($chat, (int)$u['id']);

    q('UPDATE mj_chat_messages SET is_read=1, read_at=IFNULL(read_at,NOW()) WHERE chat_id=? AND sender_id<>?', [$chatId, (int)$u['id']]);
    $readCol = $role === 'seller' ? 'last_read_seller_at' : 'last_read_buyer_at';
    try { q('UPDATE mj_chats SET `'.$readCol.'`=NOW() WHERE id=?', [$chatId]); } catch (Throwable $e) {}

    $rows = all_rows('SELECT m.*,u.name sender_name FROM mj_chat_messages m LEFT JOIN mj_users u ON u.id=m.sender_id WHERE m.chat_id=? AND m.id>? AND IFNULL(m.is_deleted,0)=0 ORDER BY m.id ASC LIMIT 100', [$chatId, $afterId]);
    $messages = array_map(function($m) use ($u){ return mj_chat_format_message($m, (int)$u['id']); }, $rows);
    $lastId = $afterId;
    foreach ($messages as $m) { if ((int)$m['id'] > $lastId) { $lastId = (int)$m['id']; } }
    echo json_encode(['ok'=>true, 'messages'=>$messages, 'last_id'=>$lastId, 'unread_count'=>mj_chat_unread_count((int)$u['id'])]);
} catch (Throwable $e) {
    echo json_encode(['ok'=>false, 'error'=>$e->getMessage()]);
}
