<?php
require_once __DIR__.'/includes/functions.php';
mj263_schema();
mj_trust_bundle_ensure_schema();
mj_leads_ensure_schema();

$id=(int)($_GET['id']??0);
$l=safe_one_public('SELECT l.*, u.name seller_name, u.trust_score, u.email seller_email, 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',[$id]);

if(!$l){
  http_response_code(404);
  $pageTitle='Listing not found';
  include __DIR__.'/includes/header.php';
  echo '<section class="mj-section"><div class="container"><div class="alert alert-warning rounded-4">Listing not found.</div><a class="btn btn-primary" href="'.e(base_url('browse.php')).'">Browse Listings</a></div></section>';
  include __DIR__.'/includes/footer.php';
  exit;
}

[$visible,$visibleReason]=mj263_visible_reason($l);
$mode=mj263_status_public_mode((string)($l['status']??'active'));
if(!$visible && $mode==='hidden'){
  $owner = current_user();
  $isOwner=$owner && (int)$owner['id']===(int)($l['user_id']??0);
  if(!$isOwner && !current_admin()) {
    http_response_code(404);
    $pageTitle='Listing unavailable';
    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">Listing unavailable</h1><p class="text-muted">This listing is currently inactive, expired, pending approval, or deleted.</p><a class="btn btn-primary" href="'.e(base_url('browse.php')).'">Browse Active Listings</a></div></div></section>';
    include __DIR__.'/includes/footer.php';
    exit;
  }
}

mj263_track_event($id,'view');

$viewer = current_user();
$adminViewer = current_admin();
$canViewContact = (bool)($viewer || $adminViewer);
$loginUrl = base_url('login.php');

$images=mj263_listing_images($id);
if(!$images && !empty($l['image_path'])) $images=[['image_path'=>$l['image_path']]];
$imgPaths=array_map(function($im){return base_url($im['image_path']);},$images);

$company = mj_listing_company_fetch($l);
$companyId = (int)($company['id'] ?? 0);
$companyLogo = !empty($company['logo']) ? base_url($company['logo']) : '';
$companyPhone = trim((string)($company['phone'] ?? ''));
$companyWhatsapp = trim((string)($company['whatsapp'] ?? ''));
$companyEmail = trim((string)($company['email'] ?? ''));
$companyWebsite = trim((string)($company['website'] ?? ''));
$companyLocation = trim((string)(($company['flag_emoji'] ?? '').' '.($company['country_name'] ?? '').(!empty($company['city_name']) ? ' • '.$company['city_name'] : '')));

$isSavedListing = $viewer ? mj_is_saved_listing((int)$viewer['id'], $id) : false;
$isSavedCompany = ($viewer && $companyId) ? mj_is_saved_company((int)$viewer['id'], $companyId) : false;

$listingUrl = mj263_listing_url($l);
$qrUrl = mj263_qr_url($listingUrl,260);

$moreCompanyListings = [];
if ($companyId > 0) {
    $moreCompanyListings = safe_all_rows_public('SELECT l.*, c.currency_code, c.flag_emoji, ci.name city, cat.name category
        FROM mj_listings l
        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.company_id=? AND l.id<>? AND l.status IN ("active","approved","published")
        ORDER BY l.is_featured DESC, l.updated_at DESC, l.id DESC
        LIMIT 6', [$companyId, $id]);
}

$similar=mj_public_fetch_listings(['country_id'=>(int)($l['country_id']??0),'category_id'=>(int)($l['category_id']??0),'area'=>visitor_area()],8);
$similar=array_values(array_filter($similar,function($x)use($id,$companyId){
    if((int)($x['id']??0)===$id) return false;
    if($companyId>0 && (int)($x['company_id']??0)===$companyId) return false;
    return true;
}));


verify_csrf();
if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string)($_POST['action'] ?? '') === 'listing_enquiry') {
    try {
        $leadId = mj_leads_record_listing_enquiry($l, $_POST);
        try { mj263_track_event($id, 'enquiry'); } catch(Throwable $ignore) {}
        flash('success', 'Your enquiry was sent. Seller will contact you directly.');
        redirect('listing.php?id='.(int)$id.'#listing-enquiry');
    } catch (Throwable $e) {
        flash('error', $e->getMessage());
    }
}

$pageTitle=$l['seo_title'] ?: $l['title'];
$metaDescription=$l['seo_description'] ?: mb_strimwidth(strip_tags((string)($l['description']??'')),0,160,'...');
include __DIR__.'/includes/header.php';
?>
<section class="mj-page-hero">
  <div class="container">
    <nav class="small mb-2">
      <a href="<?=base_url('/')?>">Home</a> /
      <a href="<?=base_url('browse.php')?>">Browse</a> /
      <?=e($l['category'] ?? 'Listing')?>
    </nav>
    <div class="d-flex flex-wrap gap-2 mb-2">
      <?= mj263_public_badges($l) ?>
      <?php if($company): ?><span class="mj-badge"><i class="bi bi-building-check me-1"></i>Company listing</span><?php endif; ?>
      <?php if(!$visible): ?><span class="mj-badge dark">Admin/owner preview: <?=e($visibleReason)?></span><?php endif; ?>
    </div>
    <h1 class="fw-bold display-6 mb-0"><?=e($l['title'])?></h1>
  </div>
</section>

<section class="mj-section">
  <div class="container">
    <?php show_flash(); ?>
    <div class="row g-4">
      <div class="col-lg-7">
        <div class="mj-card p-3">
          <?php if($imgPaths): ?>
            <div class="text-center">
              <img id="mjMainListingImage" class="w-100 rounded-4" style="max-height:520px;object-fit:cover;cursor:zoom-in" src="<?=e($imgPaths[0])?>" data-gallery-src="<?=e($imgPaths[0])?>" data-gallery-title="<?=e($l['title'])?>" data-listing-id="<?=e($id)?>" data-mj-track="image_view" alt="<?=e($l['title'])?>">
            </div>
            <div class="d-flex gap-2 flex-wrap mt-3">
              <?php foreach($imgPaths as $i=>$src): ?>
                <img class="mj-thumb <?=$i===0?'active':''?>" src="<?=e($src)?>" data-thumb-src="<?=e($src)?>" data-gallery-src="<?=e($src)?>" data-gallery-title="<?=e($l['title'])?>" data-listing-id="<?=e($id)?>" data-mj-track="image_view" alt="photo">
              <?php endforeach; ?>
            </div>
            <script>
            document.addEventListener('click',function(e){
              var t=e.target.closest('[data-thumb-src]');
              if(t){
                document.getElementById('mjMainListingImage').src=t.getAttribute('data-thumb-src');
                document.querySelectorAll('.mj-thumb').forEach(x=>x.classList.remove('active'));
                t.classList.add('active');
              }
            });
            </script>
          <?php else: ?>
            <img class="w-100 rounded-4" src="<?=e(asset('images/empty-state.svg'))?>" alt="No image">
          <?php endif; ?>
        </div>

        <div class="mj-card p-4 mt-4">
          <h3 class="fw-bold">Listing Details</h3>
          <p class="text-muted mb-4">Review the description, price, location and seller/company details before contacting.</p>
          <p><?=nl2br(e($l['description'] ?? ''))?></p>
          <div class="row g-3 mt-2">
            <div class="col-6 col-md-3"><span class="text-muted small">Condition</span><b class="d-block"><?=e($l['condition_label'] ?: '-')?></b></div>
            <div class="col-6 col-md-3"><span class="text-muted small">Category</span><b class="d-block"><?=e($l['category'] ?: '-')?></b></div>
            <div class="col-6 col-md-3"><span class="text-muted small">Availability</span><b class="d-block"><?=e($l['availability_status'] ?: ucfirst($l['status'] ?: 'Active'))?></b></div>
            <div class="col-6 col-md-3"><span class="text-muted small">Posted</span><b class="d-block small"><?=e(local_datetime($l['created_at'] ?? '',$l['timezone'] ?: ($l['timezone_default'] ?? 'UTC')))?></b></div>
          </div>
        </div>

        <?php if($company): ?>
        <div class="mj-card p-4 mt-4 mj-company-inline-card">
          <div class="d-flex flex-wrap align-items-start gap-3">
            <div class="mj-company-logo-xl">
              <?php if($companyLogo): ?><img src="<?=e($companyLogo)?>" alt="<?=e($company['name'])?>"><?php else: ?><i class="bi bi-building"></i><?php endif; ?>
            </div>
            <div class="flex-grow-1">
              <div class="d-flex flex-wrap gap-2 mb-2">
                <span class="mj-badge"><i class="bi bi-building-check me-1"></i>Posted by Company</span>
                <?php if(!empty($company['is_verified'])): ?><span class="mj-badge success"><i class="bi bi-patch-check-fill me-1"></i>Verified Company</span><?php endif; ?>
                <?php if(!empty($company['is_featured'])): ?><span class="mj-badge warning"><i class="bi bi-star-fill me-1"></i>Featured</span><?php endif; ?>
                <?php if(!empty($company['is_sponsored'])): ?><span class="mj-badge dark"><i class="bi bi-megaphone-fill me-1"></i>Sponsored</span><?php endif; ?>
              </div>
              <h3 class="fw-bold mb-1"><?=e($company['name'])?></h3>
              <p class="text-muted mb-2"><?=e($companyLocation ?: 'Company profile')?></p>
              <p class="mb-3"><?=e(mj_company_short_description($company, 180))?></p>
              <div class="row g-2 mb-3">
                <div class="col-6 col-md-3"><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 col-md-3"><div class="mj-mini-trust"><span>Profile</span><b><?=e((int)($company['profile_score'] ?? 0))?>%</b><small>Complete details</small></div></div>
                <div class="col-6 col-md-3"><div class="mj-mini-trust"><span>Listings</span><b><?=e(count($moreCompanyListings)+1)?></b><small>Active items</small></div></div>
                <div class="col-6 col-md-3"><div class="mj-mini-trust"><span>Rating</span><b><?=e(number_format((float)($company['rating_avg'] ?? 0),1))?></b><small><?=e((int)($company['rating_count'] ?? 0))?> reviews</small></div></div>
              </div>
            </div>
          </div>

          <div class="mj-protected-contact mt-3">
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3">
              <div>
                <h5 class="fw-bold mb-1">Contact this company safely</h5>
                <p class="text-muted small mb-0"><?= $canViewContact ? 'Full contact details are visible because you are logged in.' : 'Contact details are protected. Login to view full phone, WhatsApp and email.' ?></p>
              </div>
              <?php if(!$canViewContact): ?><a class="btn btn-sm btn-primary rounded-pill" href="<?=e($loginUrl)?>"><i class="bi bi-box-arrow-in-right me-1"></i>Login to view full contact</a><?php endif; ?>
            </div>
            <div class="row g-3">
              <?php if($companyPhone): ?>
                <div class="col-md-4">
                  <a class="mj-contact-chip" href="<?=e(mj_company_contact_action_url($companyPhone,'phone',$canViewContact,$loginUrl))?>" title="<?=e(mj_contact_lock_title('phone',$canViewContact))?>" data-company-id="<?=e($companyId)?>" data-listing-id="<?=e($id)?>" data-mj-company-track="company_phone_click">
                    <i class="bi bi-telephone"></i><span><small>Phone</small><b><?=e(mj_contact_public_value($companyPhone,'phone',$canViewContact))?></b></span>
                  </a>
                </div>
              <?php endif; ?>
              <?php if($companyWhatsapp): ?>
                <div class="col-md-4">
                  <a class="mj-contact-chip" href="<?=e(mj_company_contact_action_url($companyWhatsapp,'whatsapp',$canViewContact,$loginUrl))?>" title="<?=e(mj_contact_lock_title('whatsapp',$canViewContact))?>" target="<?= $canViewContact ? '_blank' : '_self' ?>" data-company-id="<?=e($companyId)?>" data-listing-id="<?=e($id)?>" data-mj-company-track="company_whatsapp_click">
                    <i class="bi bi-whatsapp"></i><span><small>WhatsApp</small><b><?=e(mj_contact_public_value($companyWhatsapp,'whatsapp',$canViewContact))?></b></span>
                  </a>
                </div>
              <?php endif; ?>
              <?php if($companyEmail): ?>
                <div class="col-md-4">
                  <a class="mj-contact-chip" href="<?=e(mj_company_contact_action_url($companyEmail,'email',$canViewContact,$loginUrl))?>" title="<?=e(mj_contact_lock_title('email',$canViewContact))?>" data-company-id="<?=e($companyId)?>" data-listing-id="<?=e($id)?>" data-mj-company-track="company_email_click">
                    <i class="bi bi-envelope"></i><span><small>Email</small><b><?=e(mj_contact_public_value($companyEmail,'email',$canViewContact))?></b></span>
                  </a>
                </div>
              <?php endif; ?>
            </div>
          </div>

          <div class="d-flex flex-wrap gap-2 mt-3">
            <a class="btn btn-primary rounded-pill" href="<?=e(mj_company_public_url($company))?>"><i class="bi bi-building me-1"></i>View Company Profile</a>
            <a class="btn btn-outline-primary rounded-pill" href="<?=e(base_url('browse.php?company_id='.$companyId))?>"><i class="bi bi-grid me-1"></i>View Company Listings</a>
            <?php if($viewer): ?>
              <button class="btn <?= $isSavedCompany ? 'btn-success' : 'btn-outline-success' ?> rounded-pill" type="button" data-mj-save="company" data-save-id="<?=e($companyId)?>" data-saved="<?= $isSavedCompany ? '1' : '0' ?>"><i class="bi bi-heart<?= $isSavedCompany ? '-fill' : '' ?> me-1"></i><span><?= $isSavedCompany ? 'Saved Company' : 'Save Company' ?></span></button>
            <?php else: ?>
              <a class="btn btn-outline-success rounded-pill" href="<?=e($loginUrl)?>"><i class="bi bi-heart me-1"></i>Save Company</a>
            <?php endif; ?>
            <a class="btn btn-outline-danger rounded-pill" href="<?=e(base_url('report.php?type=company&id='.$companyId))?>"><i class="bi bi-flag me-1"></i>Report Company</a>
          </div>
        </div>
        <?php endif; ?>

        <div class="mj-card p-4 mt-4">
          <h3 class="fw-bold">Questions & FAQ</h3>
          <?php $faqs=safe_all_rows_public('SELECT * FROM mj_listing_faqs WHERE listing_id=? AND is_active=1 ORDER BY sort_order,id LIMIT 8',[$id]); ?>
          <?php if($faqs): foreach($faqs as $f): ?>
            <div class="border-bottom py-2"><b><?=e($f['question'])?></b><p class="text-muted mb-1"><?=nl2br(e($f['answer']))?></p></div>
          <?php endforeach; else: ?>
            <p class="text-muted mb-0">No FAQ added yet. Use chat to ask the seller.</p>
          <?php endif; ?>
        </div>
      </div>

      <div class="col-lg-5">
        <div class="mj-card p-4 sticky-top" style="top:95px">
          <span class="mj-badge mb-3"><?=e(($l['flag_emoji'] ?? '').' '.($l['country_name'] ?? ''))?> <?=e(!empty($l['city'])? '• '.$l['city'] : '')?></span>
          <div class="mj-listing-price display-6 mb-1"><?=money($l['price'] ?? 0,$l['currency_code'] ?? 'USD')?></div>
          <?php if(!empty($l['old_price']) && (float)$l['old_price']>(float)$l['price']): ?>
            <p class="text-danger fw-bold"><i class="bi bi-arrow-down-circle"></i> Price drop: was <?=money($l['old_price'],$l['currency_code']??'USD')?></p>
          <?php endif; ?>

          <div class="mj-listing-stats my-3">
            <span><i class="bi bi-eye"></i><?=e((int)($l['views']??0))?> views</span>
            <span><i class="bi bi-fire"></i><?=e((int)($l['engagement_count']??0))?> engaged</span>
            <span><i class="bi bi-cash-coin"></i><?=e((int)($l['offer_count']??0))?> offers</span>
            <span><i class="bi bi-share"></i><?=e((int)($l['share_count']??0))?> shares</span>
          </div>

          <hr>
          <div class="d-flex align-items-center gap-3 mb-3">
            <div class="mj-icon-box"><i class="bi <?= $company ? 'bi-building-check' : 'bi-person-check' ?>"></i></div>
            <div>
              <b><?=e($company['name'] ?? $l['seller_name'] ?? 'Seller')?></b>
              <small class="d-block text-muted"><?= $company ? 'Company seller' : 'Individual seller' ?> • Trust score <?=e($company['trust_score'] ?? $l['trust_score'] ?? 0)?></small>
            </div>
          </div>

          <div class="mj-trust-summary mb-3">
            <div><i class="bi bi-shield-check"></i><span><?= $company ? 'Company profile linked' : 'Seller profile linked' ?></span></div>
            <div><i class="bi bi-lock"></i><span>Contact protected for safer browsing</span></div>
            <div><i class="bi bi-clock-history"></i><span><?=e($l['availability_status'] ?: ucfirst($l['status'] ?: 'Active'))?></span></div>
            <?php if($company && !empty($company['is_verified'])): ?><div><i class="bi bi-patch-check-fill"></i><span>Verified company badge</span></div><?php endif; ?>
          </div>

          <div class="d-grid gap-2">
            <?php if($mode==='sold'): ?>
              <button class="btn btn-dark btn-lg" disabled><i class="bi bi-check2-circle me-1"></i>Sold</button>
            <?php elseif($mode==='reserved'): ?>
              <button class="btn btn-warning btn-lg" disabled><i class="bi bi-pause-circle me-1"></i>Reserved</button>
            <?php else: ?>
              <a class="btn btn-primary btn-lg" href="<?=base_url('chat.php?listing_id='.(int)$l['id'].'&seller_id='.(int)$l['user_id'])?>" data-listing-id="<?=e($id)?>" data-mj-track="chat_click"><i class="bi bi-chat-dots me-1"></i>Chat Seller</a>
              <a class="btn btn-outline-primary btn-lg" href="<?=base_url('make-offer.php?listing_id='.(int)$l['id'])?>" data-listing-id="<?=e($id)?>" data-mj-track="offer_click"><i class="bi bi-cash-coin me-1"></i>Make Offer</a>
              <a class="btn btn-outline-dark btn-lg" href="#listing-enquiry"><i class="bi bi-send me-1"></i>Send Enquiry</a>
            <?php endif; ?>

            <?php if($viewer): ?>
              <button class="btn <?= $isSavedListing ? 'btn-success' : 'btn-outline-success' ?>" type="button" data-mj-save="listing" data-save-id="<?=e($id)?>" data-saved="<?= $isSavedListing ? '1' : '0' ?>" data-listing-id="<?=e($id)?>" data-mj-track="save_click"><i class="bi bi-heart<?= $isSavedListing ? '-fill' : '' ?> me-1"></i><span><?= $isSavedListing ? 'Saved Listing' : 'Save Listing' ?></span></button>
            <?php else: ?>
              <a class="btn btn-outline-success" href="<?=e($loginUrl)?>"><i class="bi bi-heart me-1"></i>Login to Save Listing</a>
            <?php endif; ?>

            <a class="btn btn-outline-danger" href="<?=base_url('report.php?type=listing&id='.(int)$l['id'])?>"><i class="bi bi-flag me-1"></i>Report Listing</a>
          </div>


          <div class="mj-card p-3 mt-4" id="listing-enquiry">
            <h5 class="fw-bold mb-1"><i class="bi bi-send me-1"></i>Send Enquiry</h5>
            <p class="small text-muted mb-3">Ask about availability, price, condition or service details. The seller will follow up directly.</p>
            <form method="post" class="mj-clean-form">
              <?=csrf_input()?>
              <input type="hidden" name="action" value="listing_enquiry">
              <div class="mb-2"><label class="form-label small fw-bold">Name *</label><input class="form-control" name="name" required value="<?=e($viewer['name'] ?? '')?>"></div>
              <div class="row g-2">
                <div class="col-md-6 mb-2"><label class="form-label small fw-bold">Email</label><input class="form-control" type="email" name="email" value="<?=e($viewer['email'] ?? '')?>"></div>
                <div class="col-md-6 mb-2"><label class="form-label small fw-bold">Phone / WhatsApp</label><input class="form-control" name="phone" value="<?=e($viewer['mobile'] ?? '')?>"></div>
              </div>
              <div class="mb-2"><label class="form-label small fw-bold">Preferred contact</label><select class="form-select" name="preferred_contact"><option value="">Any method</option><option value="whatsapp">WhatsApp</option><option value="call">Call</option><option value="email">Email</option></select></div>
              <div class="mb-3"><label class="form-label small fw-bold">Message *</label><textarea class="form-control" name="message" rows="4" required>I am interested in this listing. Please contact me.</textarea></div>
              <button class="btn btn-primary w-100 rounded-pill"><i class="bi bi-send me-1"></i>Send Enquiry</button>
            </form>
            <div class="alert alert-info small mt-3 mb-0 rounded-4"><i class="bi bi-shield-check me-1"></i>MJ Marketplace does not collect customer payment for this listing. Final transaction is handled directly with the seller.</div>
          </div>

          <div class="mj-share-panel mt-4">
            <h6 class="fw-bold">Share this listing</h6>
            <p class="small text-muted mb-2">Send this listing to friends, customers or your team by link, WhatsApp, Facebook or QR code.</p>
            <div class="d-flex flex-wrap gap-2">
              <a class="btn btn-success btn-sm" target="_blank" data-listing-id="<?=e($id)?>" data-mj-track="share" data-share-type="whatsapp" href="https://wa.me/?text=<?=rawurlencode('Check this listing: '.$l['title'].' '.$listingUrl)?>"><i class="bi bi-whatsapp"></i></a>
              <a class="btn btn-primary btn-sm" target="_blank" data-listing-id="<?=e($id)?>" data-mj-track="share" data-share-type="facebook" href="https://www.facebook.com/sharer/sharer.php?u=<?=rawurlencode($listingUrl)?>"><i class="bi bi-facebook"></i></a>
              <a class="btn btn-info btn-sm text-white" target="_blank" data-listing-id="<?=e($id)?>" data-mj-track="share" data-share-type="telegram" href="https://t.me/share/url?url=<?=rawurlencode($listingUrl)?>&text=<?=rawurlencode($l['title'])?>"><i class="bi bi-telegram"></i></a>
              <button class="btn btn-outline-secondary btn-sm" data-copy-link="<?=e($listingUrl)?>" data-listing-id="<?=e($id)?>" data-mj-track="share" data-share-type="copy"><i class="bi bi-link-45deg"></i> Copy</button>
              <button class="btn btn-outline-primary btn-sm" data-native-share data-url="<?=e($listingUrl)?>" data-title="<?=e($l['title'])?>" data-listing-id="<?=e($id)?>" data-mj-track="share" data-share-type="native"><i class="bi bi-share"></i> Share</button>
            </div>
            <div class="mj-qr-box mt-3">
              <img src="<?=e($qrUrl)?>" alt="QR" width="160" height="160">
              <p class="small text-muted mb-2">Scan to open this listing</p>
              <a class="btn btn-sm btn-outline-dark" target="_blank" href="<?=base_url('listing-qr-poster.php?id='.$id)?>"><i class="bi bi-printer"></i> QR Poster</a>
            </div>
          </div>

          <div class="alert alert-warning mt-4 mb-0 rounded-4">
            <b><i class="bi bi-shield-exclamation me-1"></i>Contact safely</b><br>
            Confirm price, condition and service details before payment. Never share OTP, bank login or Singpass details. Report suspicious listings.
          </div>
        </div>
      </div>
    </div>

    <?php if($moreCompanyListings): ?>
      <div class="mj-section-title mt-5">
        <div>
          <h2>More listings from <?=e($company['name'] ?? 'this company')?></h2>
          <p class="text-muted mb-0">Browse other active listings from the same company.</p>
        </div>
        <a class="btn btn-outline-primary rounded-pill" href="<?=e(base_url('browse.php?company_id='.$companyId))?>">View all</a>
      </div>
      <div class="row g-4">
        <?php foreach(array_slice($moreCompanyListings,0,6) as $r): ?>
          <div class="col-md-6 col-xl-4"><?php include __DIR__.'/partials/listing-card.php'; ?></div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>

    <?php if($similar): ?>
      <div class="mj-section-title mt-5">
        <div>
          <h2>Similar listings you may like</h2>
          <p class="text-muted mb-0">Related active listings from the same category or location.</p>
        </div>
      </div>
      <div class="row g-4">
        <?php foreach(array_slice($similar,0,4) as $r): ?>
          <div class="col-md-6 col-xl-3"><?php include __DIR__.'/partials/listing-card.php'; ?></div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>
</section>
<?php include __DIR__.'/includes/footer.php'; ?>
