<?php
require_once __DIR__.'/includes/functions.php';
$u = require_user();
mj263_schema();
mj_trust_bundle_ensure_schema();
mj_realtime_chat_ensure_schema();

$pageTitle='Messages';
$tab = strtolower(trim((string)($_GET['tab'] ?? 'all')));
$qstr = trim((string)($_GET['q'] ?? ''));
$listingFilterId = (int)($_GET['listing_id'] ?? 0);
$uid = (int)$u['id'];

$where = ['(ch.buyer_id=? OR ch.seller_id=?)'];
$params = [$uid,$uid];
if ($listingFilterId > 0) { $where[]='ch.listing_id=?'; $params[]=$listingFilterId; }
if ($tab === 'buying') { $where[]='ch.buyer_id=?'; $params[]=$uid; }
elseif ($tab === 'selling') { $where[]='ch.seller_id=?'; $params[]=$uid; }
elseif ($tab === 'unread') { $where[]='EXISTS(SELECT 1 FROM mj_chat_messages um WHERE um.chat_id=ch.id AND um.sender_id<>? AND IFNULL(um.is_read,0)=0 AND IFNULL(um.is_deleted,0)=0)'; $params[]=$uid; }

if ($tab === 'archived') {
    $where[]='((ch.buyer_id=? AND IFNULL(ch.buyer_archived,0)=1) OR (ch.seller_id=? AND IFNULL(ch.seller_archived,0)=1))';
    $params[]=$uid; $params[]=$uid;
} else {
    $where[]='((ch.buyer_id=? AND IFNULL(ch.buyer_archived,0)=0) OR (ch.seller_id=? AND IFNULL(ch.seller_archived,0)=0))';
    $params[]=$uid; $params[]=$uid;
}

if ($qstr !== '') {
    $like = '%'.$qstr.'%';
    $where[]='(lu.title LIKE ? OR co.name LIKE ? OR b.name LIKE ? OR s.name LIKE ? OR ch.last_message LIKE ?)';
    array_push($params,$like,$like,$like,$like,$like);
}

$sql = 'SELECT ch.*, lu.title listing_title, lu.price, lu.status listing_status, lu.availability_status, (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, co.is_verified company_verified, b.name buyer_name, s.name seller_name,
        (SELECT COUNT(*) FROM mj_chat_messages m WHERE m.chat_id=ch.id AND m.sender_id<>? AND IFNULL(m.is_read,0)=0 AND IFNULL(m.is_deleted,0)=0) unread_count,
        (SELECT MAX(id) FROM mj_chat_messages lm WHERE lm.chat_id=ch.id) last_message_id
        FROM mj_chats ch
        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 b ON b.id=ch.buyer_id
        LEFT JOIN mj_users s ON s.id=ch.seller_id
        WHERE '.implode(' AND ',$where).'
        ORDER BY CASE WHEN ch.buyer_id=? THEN IFNULL(ch.buyer_pinned,0) ELSE IFNULL(ch.seller_pinned,0) END DESC, COALESCE(ch.last_message_at,ch.created_at) DESC, ch.id DESC
        LIMIT 150';
$queryParams = array_merge([$uid], $params, [$uid]);
$rows = [];
try { $rows = all_rows($sql, $queryParams); } catch (Throwable $e) { flash('error', $e->getMessage()); }
$unreadTotal = mj_chat_unread_count($uid);
include __DIR__.'/includes/header.php';
?>
<section class="mj-page-hero">
  <div class="container">
    <span class="mj-badge mb-2"><i class="bi bi-chat-dots"></i> Marketplace Messages</span>
    <h1 class="fw-bold display-5 mb-1">Messages</h1>
    <p class="text-muted mb-0">Manage buying enquiries, selling chats, company messages and unread conversations in one place.</p>
  </div>
</section>
<section class="mj-section">
  <div class="container">
    <?php show_flash(); ?>
    <?php if($listingFilterId>0): ?>
      <div class="alert alert-info rounded-4 mb-4"><i class="bi bi-chat-dots me-1"></i>Showing conversations for listing #<?=e($listingFilterId)?>. <a href="<?=e(base_url('messages.php'))?>" class="fw-bold">Show all messages</a></div>
    <?php endif; ?>
    <div class="mj-chat-inbox-tools mj-card p-3 mb-4">
      <div class="d-flex flex-wrap justify-content-between align-items-center gap-3">
        <div class="mj-chat-tabs">
          <?php foreach(['all'=>'All Chats','buying'=>'Buying','selling'=>'Selling','unread'=>'Unread','archived'=>'Archived'] as $k=>$v): ?>
            <a class="btn btn-sm <?= $tab===$k?'btn-primary':'btn-outline-primary' ?> rounded-pill" href="<?=e(base_url('messages.php?tab='.$k.($qstr!==''?'&q='.rawurlencode($qstr):'').($listingFilterId>0?'&listing_id='.$listingFilterId:'')))?>"><?=e($v)?><?= $k==='unread' && $unreadTotal>0 ? ' ('.e($unreadTotal).')' : '' ?></a>
          <?php endforeach; ?>
        </div>
        <form class="d-flex gap-2" method="get">
          <input type="hidden" name="tab" value="<?=e($tab)?>">
          <?php if($listingFilterId>0): ?><input type="hidden" name="listing_id" value="<?=e($listingFilterId)?>"><?php endif; ?>
          <input class="form-control rounded-pill" name="q" value="<?=e($qstr)?>" placeholder="Search listing, company or message">
          <button class="btn btn-primary rounded-pill"><i class="bi bi-search"></i></button>
        </form>
      </div>
    </div>

    <input type="hidden" id="mjChatActionToken" value="<?=e(csrf_token())?>">

    <?php if(!$rows): ?>
      <div class="mj-card p-5 text-center">
        <div class="mj-icon-box mx-auto mb-3"><i class="bi bi-chat-square-dots"></i></div>
        <h3 class="fw-bold">No conversations found</h3>
        <p class="text-muted">When you contact sellers or receive enquiries, your chats will appear here.</p>
        <a class="btn btn-primary rounded-pill" href="<?=e(base_url('browse.php'))?>">Browse Listings</a>
      </div>
    <?php else: ?>
      <div class="mj-chat-inbox-list">
        <?php foreach($rows as $r):
          $isSeller = $uid === (int)$r['seller_id'];
          $otherName = $isSeller ? ($r['buyer_name'] ?: 'Buyer') : ($r['seller_name'] ?: 'Seller');
          $title = $r['listing_title'] ?: ($r['company_name'] ?: 'Marketplace chat');
          $img = !empty($r['company_logo']) ? base_url($r['company_logo']) : (!empty($r['listing_image']) ? base_url($r['listing_image']) : asset('images/empty-state.svg'));
          $chatUrl = mj_chat_url($r);
          $unread = (int)($r['unread_count'] ?? 0);
          $pinned = $isSeller ? (int)($r['seller_pinned'] ?? 0) : (int)($r['buyer_pinned'] ?? 0);
          $archived = $isSeller ? (int)($r['seller_archived'] ?? 0) : (int)($r['buyer_archived'] ?? 0);
        ?>
        <div class="mj-chat-inbox-row <?= $unread>0?'has-unread':'' ?>">
          <a class="mj-chat-inbox-main" href="<?=e($chatUrl)?>">
            <img src="<?=e($img)?>" alt="<?=e($title)?>">
            <div class="flex-grow-1">
              <div class="d-flex flex-wrap gap-2 align-items-center mb-1">
                <?php if($pinned): ?><span class="mj-badge warning"><i class="bi bi-pin-angle-fill"></i>Pinned</span><?php endif; ?>
                <span class="mj-badge <?= $isSeller?'dark':'' ?>"><?= $isSeller ? 'Selling' : 'Buying' ?></span>
                <?php if(!empty($r['company_name'])): ?><span class="mj-badge"><i class="bi bi-building"></i><?=e($r['company_name'])?></span><?php endif; ?>
                <?php if(!empty($r['company_verified'])): ?><span class="mj-badge good"><i class="bi bi-patch-check-fill"></i>Verified</span><?php endif; ?>
                <?php if($unread): ?><span class="mj-badge danger"><?=e($unread)?> new</span><?php endif; ?>
              </div>
              <h5 class="fw-bold mb-1"><?=e($title)?></h5>
              <p class="text-muted mb-1"><b><?=e($otherName)?></b> • <?=e(mb_strimwidth((string)($r['last_message'] ?: 'No message yet'),0,120,'...'))?></p>
              <small class="text-muted"><i class="bi bi-clock me-1"></i><?=e(local_datetime($r['last_message_at'] ?: $r['created_at'], 'UTC'))?><?= !empty($r['listing_status']) ? ' • '.e($r['availability_status'] ?: ucfirst($r['listing_status'])) : '' ?></small>
            </div>
          </a>
          <div class="mj-chat-inbox-actions">
            <a class="btn btn-sm btn-primary" href="<?=e($chatUrl)?>"><i class="bi bi-chat-dots me-1"></i>Open</a>
            <?php if(!empty($r['listing_id'])): ?><a class="btn btn-sm btn-outline-primary" href="<?=e(base_url('listing.php?id='.(int)$r['listing_id']))?>">Listing</a><?php endif; ?>
            <?php if(!empty($r['listing_id']) && !$isSeller): ?><a class="btn btn-sm btn-outline-success" href="<?=e(base_url('make-offer.php?listing_id='.(int)$r['listing_id']))?>">Offer</a><?php endif; ?>
            <button class="btn btn-sm btn-outline-secondary" data-chat-action="<?= $pinned?'unpin':'pin' ?>" data-chat-id="<?=e($r['id'])?>"><?= $pinned?'Unpin':'Pin' ?></button>
            <button class="btn btn-sm btn-outline-warning" data-chat-action="mute_hour" data-chat-id="<?=e($r['id'])?>">Mute</button>
            <button class="btn btn-sm btn-outline-secondary" data-chat-action="<?= $archived?'restore':'archive' ?>" data-chat-id="<?=e($r['id'])?>"><?= $archived?'Restore':'Archive' ?></button>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>
</section>
<script>
document.addEventListener('click',function(e){
  var btn=e.target.closest('[data-chat-action]');
  if(!btn) return;
  e.preventDefault();
  var fd=new FormData();
  fd.append('chat_id',btn.getAttribute('data-chat-id'));
  fd.append('action',btn.getAttribute('data-chat-action'));
  fd.append('csrf_token',(document.getElementById('mjChatActionToken')||{}).value||'');
  fetch((window.MJ_BASE_URL||'')+'/ajax/chat-action.php',{method:'POST',body:fd,credentials:'same-origin'}).then(r=>r.json()).then(function(res){
    if(res && res.ok){ location.reload(); } else { alert((res && res.error) ? res.error : 'Action failed.'); }
  }).catch(function(){ alert('Action failed.'); });
});
</script>
<?php include __DIR__.'/includes/footer.php'; ?>
