<?php
require_once __DIR__.'/../includes/functions.php';
header('Content-Type: application/json');
try {
    $u = current_user();
    if (!$u) { echo json_encode(['ok'=>true,'logged_in'=>false,'unread_count'=>0,'items'=>[]]); exit; }
    mj_realtime_chat_ensure_schema();
    $currentChatId = (int)($_GET['current_chat_id'] ?? 0);
    $sinceId = (int)($_GET['since_id'] ?? 0);
    $unreadCount = mj_chat_unread_count((int)$u['id']);
    $rows = all_rows('SELECT m.id message_id,m.message,m.created_at,ch.id chat_id,ch.listing_id,ch.company_id,ch.buyer_id,ch.seller_id,
                             lu.title listing_title,(SELECT li.image_path FROM mj_listing_images li WHERE li.listing_id=lu.id ORDER BY li.sort_order,li.id LIMIT 1) listing_image,co.name company_name,co.logo company_logo,
                             sender.name sender_name
                      FROM mj_chat_messages m
                      INNER JOIN mj_chats ch ON ch.id=m.chat_id
                      LEFT JOIN mj_listings lu ON lu.id=ch.listing_id
                      LEFT JOIN mj_companies co ON co.id=ch.company_id
                      LEFT JOIN mj_users sender ON sender.id=m.sender_id
                      WHERE (ch.buyer_id=? OR ch.seller_id=?)
                        AND m.sender_id<>?
                        AND IFNULL(m.is_read,0)=0
                        AND IFNULL(m.is_deleted,0)=0
                        AND m.id>?
                        AND ch.id<>?
                      ORDER BY m.id DESC LIMIT 5', [(int)$u['id'],(int)$u['id'],(int)$u['id'],$sinceId,$currentChatId]);
    $items = [];
    $maxId = $sinceId;
    foreach ($rows as $r) {
        $maxId = max($maxId, (int)$r['message_id']);
        $items[] = [
            'message_id'=>(int)$r['message_id'],
            'chat_id'=>(int)$r['chat_id'],
            'title'=>(string)($r['company_name'] ?: $r['sender_name'] ?: 'New message'),
            'subtitle'=>(string)($r['listing_title'] ?: 'Marketplace chat'),
            'message'=>mb_strimwidth((string)$r['message'],0,110,'...'),
            'url'=>mj_chat_url($r),
            'image'=>!empty($r['company_logo']) ? base_url($r['company_logo']) : (!empty($r['listing_image']) ? base_url($r['listing_image']) : asset('images/empty-state.svg')),
            'time'=>(string)$r['created_at']
        ];
    }
    echo json_encode(['ok'=>true,'logged_in'=>true,'unread_count'=>$unreadCount,'items'=>$items,'max_id'=>$maxId]);
} catch (Throwable $e) {
    echo json_encode(['ok'=>false,'error'=>$e->getMessage(),'unread_count'=>0,'items'=>[]]);
}
