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

$listingId=(int)($_GET['listing_id']??$_POST['listing_id']??0);
$companyId=(int)($_GET['company_id']??$_POST['company_id']??0);
$sellerId=(int)($_GET['seller_id']??$_POST['seller_id']??0);
$buyerParam=(int)($_GET['buyer_id']??$_POST['buyer_id']??0);

$listing=null;
$company=null;
$seller=null;
$buyer=null;

if($listingId>0){
    $listing=safe_one_public('SELECT l.*, u.name seller_name, u.email seller_email, u.trust_score seller_trust_score, c.name country_name,c.flag_emoji,c.currency_code,c.timezone_default, ci.name city, cat.name category
        FROM mj_listings l
        LEFT JOIN mj_users u ON u.id=l.user_id
        LEFT JOIN mj_countries c ON c.id=l.country_id
        LEFT JOIN mj_cities ci ON ci.id=l.city_id
        LEFT JOIN mj_categories cat ON cat.id=l.category_id
        WHERE l.id=? LIMIT 1',[$listingId]);
    if($listing){
        $sellerId=$sellerId ?: (int)($listing['user_id']??0);
        if(!$companyId && !empty($listing['company_id'])){ $companyId=(int)$listing['company_id']; }
    }
}
if(!$sellerId && $companyId){
    $tmp=safe_one_public('SELECT user_id FROM mj_companies WHERE id=? LIMIT 1',[$companyId]);
    $sellerId=(int)($tmp['user_id']??0);
}
if(!$sellerId){
    $pageTitle='Seller not found';
    include __DIR__.'/includes/header.php';
    echo '<section class="mj-section"><div class="container"><div class="mj-card p-5 text-center"><h1 class="fw-bold">Seller not found</h1><p class="text-muted">We could not find the seller for this chat.</p><a class="btn btn-primary" href="'.e(base_url('browse.php')).'">Browse Listings</a></div></div></section>';
    include __DIR__.'/includes/footer.php';
    exit;
}

if($companyId>0){
    $company=safe_one_public('SELECT co.*, cat.name category_name, c.name country_name, c.flag_emoji, ci.name city_name
        FROM mj_companies co
        LEFT JOIN mj_categories cat ON cat.id=co.category_id
        LEFT JOIN mj_countries c ON c.id=co.country_id
        LEFT JOIN mj_cities ci ON ci.id=co.city_id
        WHERE co.id=? LIMIT 1',[$companyId]);
}

$seller=safe_one_public('SELECT id,name,email,trust_score,created_at FROM mj_users WHERE id=? LIMIT 1',[$sellerId]);
if(!$seller){
    $pageTitle='Seller not found';
    include __DIR__.'/includes/header.php';
    echo '<section class="mj-section"><div class="container"><div class="mj-card p-5 text-center"><h1 class="fw-bold">Seller not found</h1><p class="text-muted">Seller information is not available.</p><a class="btn btn-primary" href="'.e(base_url('browse.php')).'">Browse Listings</a></div></div></section>';
    include __DIR__.'/includes/footer.php';
    exit;
}

$buyerId = ((int)$u['id']===$sellerId) ? ($buyerParam ?: (int)$u['id']) : (int)$u['id'];
$buyer=safe_one_public('SELECT id,name,email,trust_score,created_at FROM mj_users WHERE id=? LIMIT 1',[$buyerId]);
if(!$buyer){ $buyer=$u; $buyerId=(int)$u['id']; }

$chat=one('SELECT * FROM mj_chats WHERE IFNULL(listing_id,0)=? AND IFNULL(company_id,0)=? AND buyer_id=? AND seller_id=? LIMIT 1',[$listingId,$companyId,$buyerId,$sellerId]);
if(!$chat){
    q('INSERT INTO mj_chats(listing_id,company_id,buyer_id,seller_id,created_at) VALUES(?,?,?,?,NOW())',[$listingId?:null,$companyId?:null,$buyerId,$sellerId]);
    $chat=one('SELECT * FROM mj_chats WHERE id=? LIMIT 1',[db()->lastInsertId()]);
}

if($_SERVER['REQUEST_METHOD']==='POST'){
    $msg=trim((string)($_POST['message']??''));
    if($msg===''){
        flash('error','Please type a message before sending.');
    } elseif(function_exists('mb_strlen') ? mb_strlen($msg)>2000 : strlen($msg)>2000) {
        flash('error','Message is too long. Please keep it under 2000 characters.');
    } else {
        $risk=0;
        try{
            if(table_exists('mj_fraud_rules')){
                foreach(all_rows('SELECT * FROM mj_fraud_rules WHERE is_active=1') as $rule){
                    if(!empty($rule['keyword']) && stripos($msg,(string)$rule['keyword'])!==false) $risk+=(int)$rule['risk_points'];
                }
            }
        }catch(Throwable $e){}
        q('INSERT INTO mj_chat_messages(chat_id,sender_id,message,risk_score,created_at) VALUES(?,?,?,?,NOW())',[$chat['id'],$u['id'],$msg,$risk]);
        q('UPDATE mj_chats SET last_message=?,last_message_at=NOW() WHERE id=?',[$msg,$chat['id']]);
        if($listingId>0){ try{ mj263_track_event($listingId,'chat_message','sent'); }catch(Throwable $e){} }
        $url='chat.php?listing_id='.$listingId.'&company_id='.$companyId.'&seller_id='.$sellerId;
        if((int)$u['id']===$sellerId && $buyerId){ $url.='&buyer_id='.$buyerId; }
        redirect($url);
    }
}

$messages=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=? ORDER BY m.id ASC',[$chat['id']]);
try{ q('UPDATE mj_chat_messages SET is_read=1, read_at=IFNULL(read_at,NOW()) WHERE chat_id=? AND sender_id<>?',[$chat['id'],(int)$u['id']]); }catch(Throwable $e){}

$listingImage='';
if($listing){
    $imgs=mj263_listing_images($listingId);
    if($imgs && !empty($imgs[0]['image_path'])) $listingImage=base_url($imgs[0]['image_path']);
    elseif(!empty($listing['image_path'])) $listingImage=base_url($listing['image_path']);
}
if(!$listingImage){ $listingImage=asset('images/empty-state.svg'); }
$listingTitle=$listing['title'] ?? 'Marketplace chat';
$currency=$listing['currency_code'] ?? ($company['currency_code'] ?? 'SGD');
$listingPrice=isset($listing['price']) ? money($listing['price'],$currency) : '';
$listingUrl=$listing ? base_url('listing.php?id='.$listingId) : '';
$companyUrl=$company ? mj_company_public_url($company) : '';
$otherUser=((int)$u['id']===$sellerId) ? $buyer : $seller;
$lastMessageId = $messages ? (int)max(array_map(function($m){ return (int)($m['id'] ?? 0); }, $messages)) : 0;
$chatRole = ((int)$u['id']===$sellerId) ? 'seller' : 'buyer';
$pageTitle='Chat - '.$listingTitle;
include __DIR__.'/includes/header.php';
?>
<section class="mj-chat-hero">
  <div class="container">
    <div class="d-flex flex-wrap justify-content-between align-items-center gap-3">
      <div>
        <span class="mj-badge mb-2"><i class="bi bi-chat-dots"></i> Marketplace Chat</span>
        <h1 class="fw-bold mb-1">Chat about this listing</h1>
        <p class="text-muted mb-0">Ask questions, confirm details and keep your conversation safe inside MJ Marketplace.</p>
      </div>
      <div class="d-flex flex-wrap gap-2">
        <?php if($listing): ?><a class="btn btn-outline-primary rounded-pill" href="<?=e($listingUrl)?>"><i class="bi bi-box-arrow-up-right me-1"></i>View Listing</a><?php endif; ?>
        <?php if($listing): ?><a class="btn btn-primary rounded-pill" href="<?=e(base_url('make-offer.php?listing_id='.$listingId))?>"><i class="bi bi-cash-coin me-1"></i>Make Offer</a><?php endif; ?>
      </div>
    </div>
  </div>
</section>

<section class="mj-section mj-chat-section">
  <div class="container">
    <?php show_flash(); ?>
    <div class="row g-4">
      <div class="col-lg-4">
        <?php if($listing): ?>
        <div class="mj-chat-listing-card mj-card p-3 mb-4">
          <div class="d-flex gap-3">
            <img src="<?=e($listingImage)?>" alt="<?=e($listingTitle)?>" class="mj-chat-listing-img">
            <div class="flex-grow-1">
              <div class="d-flex flex-wrap gap-1 mb-1">
                <span class="mj-badge"><i class="bi bi-tag"></i><?=e($listing['category'] ?: 'Listing')?></span>
                <?php if(!empty($listing['availability_status'])): ?><span class="mj-badge good"><?=e($listing['availability_status'])?></span><?php endif; ?>
              </div>
              <h5 class="fw-bold mb-1"><a class="text-dark text-decoration-none" href="<?=e($listingUrl)?>"><?=e($listingTitle)?></a></h5>
              <?php if($listingPrice): ?><div class="mj-listing-price mb-1"><?=e($listingPrice)?></div><?php endif; ?>
              <p class="small text-muted mb-0"><i class="bi bi-geo-alt me-1"></i><?=e(trim(($listing['flag_emoji'] ?? '').' '.($listing['country_name'] ?? '').(!empty($listing['city'])?' • '.$listing['city']:'')))?></p>
            </div>
          </div>
          <div class="mj-chat-mini-stats mt-3">
            <span><i class="bi bi-eye"></i><?=e((int)($listing['views']??0))?> views</span>
            <span><i class="bi bi-fire"></i><?=e((int)($listing['engagement_count']??0))?> engaged</span>
            <span><i class="bi bi-cash-coin"></i><?=e((int)($listing['offer_count']??0))?> offers</span>
          </div>
          <div class="d-grid gap-2 mt-3">
            <a class="btn btn-outline-primary" href="<?=e($listingUrl)?>"><i class="bi bi-box-arrow-up-right me-1"></i>Open Listing Details</a>
            <a class="btn btn-primary" href="<?=e(base_url('make-offer.php?listing_id='.$listingId))?>"><i class="bi bi-cash-coin me-1"></i>Make Offer</a>
          </div>
        </div>
        <?php endif; ?>

        <div class="mj-card p-4 mb-4">
          <h5 class="fw-bold mb-3"><?= $company ? 'Company / Seller' : 'Seller Details' ?></h5>
          <?php if($company): ?>
            <div class="d-flex gap-3 align-items-center mb-3">
              <div class="mj-company-logo-xl" style="width:64px;height:64px;border-radius:18px">
                <?php if(!empty($company['logo'])): ?><img src="<?=e(base_url($company['logo']))?>" alt="<?=e($company['name'])?>"><?php else: ?><i class="bi bi-building"></i><?php endif; ?>
              </div>
              <div>
                <b><?=e($company['name'])?></b>
                <small class="d-block text-muted"><?=e(($company['category_name'] ?? 'Company').(!empty($company['city_name'])?' • '.$company['city_name']:''))?></small>
                <div class="d-flex flex-wrap gap-1 mt-1">
                  <?php if(!empty($company['is_verified'])): ?><span class="mj-badge good"><i class="bi bi-patch-check-fill"></i>Verified</span><?php endif; ?>
                  <?php if(!empty($company['is_sponsored'])): ?><span class="mj-badge dark"><i class="bi bi-megaphone"></i>Sponsored</span><?php endif; ?>
                </div>
              </div>
            </div>
            <div class="row g-2 mb-3">
              <div class="col-6"><div class="mj-mini-trust"><span>Trust</span><b><?=e((int)($company['trust_score']??0))?>%</b><small><?=e(mj_trust_score_label($company['trust_score']??0))?></small></div></div>
              <div class="col-6"><div class="mj-mini-trust"><span>Profile</span><b><?=e((int)($company['profile_score']??0))?>%</b><small>Company details</small></div></div>
            </div>
            <a class="btn btn-outline-primary w-100" href="<?=e($companyUrl)?>"><i class="bi bi-building me-1"></i>View Company Profile</a>
          <?php else: ?>
            <div class="d-flex gap-3 align-items-center">
              <div class="mj-icon-box"><i class="bi bi-person-check"></i></div>
              <div><b><?=e($seller['name'] ?? 'Seller')?></b><small class="d-block text-muted">Trust score <?=e($seller['trust_score'] ?? 0)?> • Seller</small></div>
            </div>
          <?php endif; ?>
        </div>

        <div class="mj-card p-4 border-warning mj-chat-safety-card">
          <h5 class="fw-bold"><i class="bi bi-shield-exclamation me-1"></i>Stay safe</h5>
          <ul class="small text-muted mb-0 ps-3">
            <li>Confirm price, condition and service details before payment.</li>
            <li>Never share OTP, bank login, Singpass or passwords.</li>
            <li>Keep chat inside MJ Marketplace. Customer-to-seller payment is not processed by this website.</li>
            <li>Report suspicious listings or messages.</li>
          </ul>
        </div>
      </div>

      <div class="col-lg-8">
        <div class="mj-chat-panel mj-card" data-chat-id="<?=e((int)$chat['id'])?>">
          <div class="mj-chat-header">
            <div class="d-flex align-items-center gap-3">
              <div class="mj-icon-box"><i class="bi bi-person-circle"></i></div>
              <div>
                <h5 class="fw-bold mb-0">Chat with <?=e($otherUser['name'] ?? 'User')?></h5>
                <small class="text-muted"><?=e($listingTitle)?><?= $company ? ' • '.e($company['name']) : '' ?></small>
              </div>
            </div>
            <div class="d-flex flex-wrap gap-2">
              <button type="button" class="btn btn-sm btn-outline-warning rounded-pill" data-chat-action="mute_hour" data-chat-id="<?=e((int)$chat['id'])?>"><i class="bi bi-bell-slash me-1"></i>Mute</button>
              <button type="button" class="btn btn-sm btn-outline-secondary rounded-pill" data-chat-action="pin" data-chat-id="<?=e((int)$chat['id'])?>"><i class="bi bi-pin-angle me-1"></i>Pin</button>
              <button type="button" class="btn btn-sm btn-outline-danger rounded-pill" data-chat-action="report" data-chat-id="<?=e((int)$chat['id'])?>"><i class="bi bi-flag me-1"></i>Report</button>
              <a href="<?=e(base_url('messages.php'))?>" class="btn btn-sm btn-outline-secondary rounded-pill"><i class="bi bi-inbox me-1"></i>All Messages</a>
            </div>
          </div>

          <div class="alert alert-warning rounded-0 mb-0 border-start-0 border-end-0">
            <i class="bi bi-shield-check me-1"></i> Safety: keep chat inside MJ Marketplace. Customer-to-seller payment is not processed by this website. Never share OTP or bank login.
          </div>

          <div class="mj-chat-messages" id="mjChatMessages" data-chat-id="<?=e((int)$chat['id'])?>" data-last-id="<?=e($lastMessageId)?>" data-current-user="<?=e((int)$u['id'])?>">
            <?php if($listing): ?>
              <div class="mj-chat-context-card">
                <div class="mj-chat-context-label">
                  <i class="bi bi-box-seam me-1"></i>Conversation started from this listing
                </div>
                <div class="d-flex gap-3 align-items-start">
                  <a href="<?=e($listingUrl)?>" class="flex-shrink-0">
                    <img src="<?=e($listingImage)?>" alt="<?=e($listingTitle)?>" class="mj-chat-context-img">
                  </a>
                  <div class="flex-grow-1 min-width-0">
                    <div class="d-flex flex-wrap gap-1 mb-1">
                      <span class="mj-badge"><i class="bi bi-tag"></i><?=e($listing['category'] ?: 'Listing')?></span>
                      <?php if(!empty($listing['availability_status'])): ?><span class="mj-badge good"><?=e($listing['availability_status'])?></span><?php endif; ?>
                      <?php if($company): ?><span class="mj-badge"><i class="bi bi-building"></i>Company listing</span><?php endif; ?>
                    </div>
                    <h5 class="fw-bold mb-1"><a href="<?=e($listingUrl)?>" class="text-dark text-decoration-none"><?=e($listingTitle)?></a></h5>
                    <div class="d-flex flex-wrap gap-3 align-items-center small text-muted mb-2">
                      <?php if($listingPrice): ?><b class="text-dark"><?=e($listingPrice)?></b><?php endif; ?>
                      <span><i class="bi bi-geo-alt me-1"></i><?=e(trim(($listing['flag_emoji'] ?? '').' '.($listing['country_name'] ?? '').(!empty($listing['city'])?' • '.$listing['city']:'')))?></span>
                      <span><i class="bi bi-eye me-1"></i><?=e((int)($listing['views']??0))?> views</span>
                      <span><i class="bi bi-cash-coin me-1"></i><?=e((int)($listing['offer_count']??0))?> offers</span>
                    </div>
                    <?php if($company): ?>
                      <div class="small text-muted mb-2">
                        <i class="bi bi-building-check me-1"></i>
                        Posted by <b><?=e($company['name'])?></b>
                        <?php if(!empty($company['is_verified'])): ?><span class="text-success fw-bold ms-1"><i class="bi bi-patch-check-fill"></i> Verified</span><?php endif; ?>
                      </div>
                    <?php endif; ?>
                    <div class="d-flex flex-wrap gap-2">
                      <a class="btn btn-sm btn-outline-primary rounded-pill" href="<?=e($listingUrl)?>"><i class="bi bi-box-arrow-up-right me-1"></i>Open Listing</a>
                      <a class="btn btn-sm btn-primary rounded-pill" href="<?=e(base_url('make-offer.php?listing_id='.$listingId))?>"><i class="bi bi-cash-coin me-1"></i>Make Offer</a>
                      <?php if($company): ?><a class="btn btn-sm btn-outline-secondary rounded-pill" href="<?=e($companyUrl)?>"><i class="bi bi-building me-1"></i>View Company</a><?php endif; ?>
                    </div>
                  </div>
                </div>
                <div class="mj-chat-context-tip mt-3">
                  <i class="bi bi-lightbulb me-1"></i>
                  Tip: Confirm availability, price, warranty and service details here before making payment.
                </div>
              </div>
            <?php endif; ?>

            <?php if(!$messages): ?>
              <div class="mj-chat-empty text-center">
                <div class="mj-icon-box mx-auto mb-3"><i class="bi bi-chat-square-dots"></i></div>
                <h4 class="fw-bold">Start the conversation</h4>
                <p class="text-muted mb-3">Ask the seller about availability, price, service details, pickup options or warranty.</p>
                <div class="d-flex flex-wrap justify-content-center gap-2">
                  <button type="button" class="btn btn-sm btn-outline-primary mj-quick-msg">Is this still available?</button>
                  <button type="button" class="btn btn-sm btn-outline-primary mj-quick-msg">Can I get more details?</button>
                  <button type="button" class="btn btn-sm btn-outline-primary mj-quick-msg">What is your best price?</button>
                </div>
              </div>
            <?php else: ?>
              <?php foreach($messages as $m): $isMe=((int)$m['sender_id']===(int)$u['id']); ?>
                <div class="mj-chat-row <?=$isMe?'is-me':'is-other'?>">
                  <div class="mj-chat-bubble">
                    <div class="mj-chat-name"><?=e($m['sender_name'] ?: ($isMe?'Me':'User'))?></div>
                    <div><?=nl2br(e($m['message']))?></div>
                    <?php if((int)($m['risk_score']??0)>0): ?><div class="mj-risk-note"><i class="bi bi-exclamation-triangle me-1"></i>Safety warning detected</div><?php endif; ?>
                    <small><?=e(local_datetime($m['created_at'] ?? '', $listing['timezone'] ?? ($listing['timezone_default'] ?? 'UTC')))?></small>
                  </div>
                </div>
              <?php endforeach; ?>
            <?php endif; ?>
          </div>

          <div class="mj-chat-quick px-3 pt-3">
            <button type="button" class="btn btn-sm btn-light mj-quick-msg">Is this still available?</button>
            <button type="button" class="btn btn-sm btn-light mj-quick-msg">Can I get more details?</button>
            <button type="button" class="btn btn-sm btn-light mj-quick-msg">Can you send quotation?</button>
            <button type="button" class="btn btn-sm btn-light mj-quick-msg">Can you WhatsApp me?</button>
          </div>

          <form method="post" class="mj-chat-form" id="mjChatForm" data-realtime-chat="1" data-chat-id="<?=e((int)$chat['id'])?>">
            <input type="hidden" name="chat_id" value="<?=e((int)$chat['id'])?>">
            <input type="hidden" name="listing_id" value="<?=e($listingId)?>">
            <input type="hidden" name="company_id" value="<?=e($companyId)?>">
            <input type="hidden" name="seller_id" value="<?=e($sellerId)?>">
            <input type="hidden" name="buyer_id" value="<?=e($buyerId)?>">
            <?=csrf_input()?>
            <textarea class="form-control" name="message" id="mjChatMessageInput" rows="2" maxlength="2000" placeholder="Type your message here... Press Enter to send, Shift + Enter for new line."></textarea>
            <button class="btn btn-primary px-4"><i class="bi bi-send me-1"></i>Send</button>
          </form>
        </div>
      </div>
    </div>
  </div>
</section>
<script>
window.MJ_CURRENT_CHAT_ID = <?=json_encode((int)$chat['id'])?>;
window.MJ_CHAT_LAST_ID = <?=json_encode((int)$lastMessageId)?>;
document.addEventListener('DOMContentLoaded', function(){
  var box=document.getElementById('mjChatMessages');
  if(box){ box.scrollTop=box.scrollHeight; }
  var input=document.getElementById('mjChatMessageInput');
  document.querySelectorAll('.mj-quick-msg').forEach(function(btn){
    btn.addEventListener('click', function(){
      if(input){ input.value=this.textContent.trim(); input.focus(); }
    });
  });
  var form=document.getElementById('mjChatForm');
  if(input && form){
    input.addEventListener('keydown', function(e){
      if(e.key==='Enter' && !e.shiftKey){
        e.preventDefault();
        if(input.value.trim()){ if(form.requestSubmit){ form.requestSubmit(); } else { form.dispatchEvent(new Event('submit', {cancelable:true})); } }
      }
    });
    form.addEventListener('submit', function(e){
      if(!input.value.trim()){
        e.preventDefault();
        input.focus();
        alert('Please type a message before sending.');
      }
    });
  }
});
</script>
<?php include __DIR__.'/includes/footer.php'; ?>
