<?php
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/mj_deal_helpers.php';
mj_deal_ensure_schema();
$pageTitle = 'Deals & Offers';
$metaDescription = 'Browse promotional deals and contact sellers directly. MJ Marketplace does not collect customer payment for deals.';
$qText=trim((string)($_GET['q']??'')); $countryId=(int)($_GET['country_id']??0); $catId=(int)($_GET['category_id']??0); $sort=trim((string)($_GET['sort']??'featured'));
$where=[mj_deal_public_where('d')]; $params=[];
if($qText!==''){ $where[]='(d.title LIKE ? OR d.description LIKE ? OR d.short_description LIKE ? OR co.name LIKE ?)'; $like='%'.$qText.'%'; array_push($params,$like,$like,$like,$like); }
if($countryId>0){ $where[]='d.country_id=?'; $params[]=$countryId; }
if($catId>0){ $where[]='d.category_id=?'; $params[]=$catId; }
$order='d.is_sponsored DESC, d.is_featured DESC, d.id DESC';
if($sort==='ending'){ $order='CASE WHEN d.end_at IS NULL THEN 1 ELSE 0 END, d.end_at ASC'; }
if($sort==='popular'){ $order='d.enquiry_count DESC, d.whatsapp_click_count DESC, d.view_count DESC'; }
if($sort==='new'){ $order='d.id DESC'; }
$page=max(1,(int)($_GET['page']??1)); $perPage=18; $offset=($page-1)*$perPage;
$total=safe_count_public('SELECT COUNT(*) c FROM mj_deals d LEFT JOIN mj_companies co ON co.id=d.company_id WHERE '.implode(' AND ',$where),$params);
$deals=[]; try { $deals=all_rows('SELECT d.*, co.name company_name, co.slug company_slug, co.phone company_phone, co.whatsapp company_whatsapp, co.email company_email, c.name country_name, ci.name city_name, cat.name category_name FROM mj_deals d LEFT JOIN mj_companies co ON co.id=d.company_id LEFT JOIN mj_countries c ON c.id=d.country_id LEFT JOIN mj_cities ci ON ci.id=d.city_id LEFT JOIN mj_categories cat ON cat.id=d.category_id WHERE '.implode(' AND ',$where).' ORDER BY '.$order.' LIMIT '.$perPage.' OFFSET '.$offset,$params); } catch(Throwable $e){ mj_frontend_runtime_error($e,'deals list'); }
$countries=table_exists('mj_countries')?safe_all_rows_public('SELECT id,name FROM mj_countries WHERE is_active=1 ORDER BY sort_order,name LIMIT 200'):[];
$categories=table_exists('mj_categories')?safe_all_rows_public("SELECT id,name FROM mj_categories WHERE is_active=1 AND type IN ('marketplace','service','company') ORDER BY sort_order,name LIMIT 200"):[];
include __DIR__ . '/includes/header.php';
?>
<section class="mj-deals-hero py-5">
  <div class="container">
    <div class="row align-items-center g-4">
      <div class="col-lg-8">
        <span class="badge text-bg-light rounded-pill mb-3"><i class="bi bi-shield-lock me-1"></i>Display & enquiry only</span>
        <h1 class="display-5 fw-bold mb-3">Deals & Offers Near You</h1>
        <p class="lead mb-3">Find promotions, service offers, city deals and limited-time discounts. Contact the seller directly by enquiry, WhatsApp, call or email.</p>
        <div class="alert alert-info rounded-4 mb-0"><b>No customer payment through MJ Marketplace.</b> Final transaction and payment are handled directly between customer and seller.</div>
      </div>
      <div class="col-lg-4"><div class="mj-glass rounded-5 p-4"><h3 class="fw-bold mb-1"><?= number_format($total) ?></h3><p class="mb-0">active display deals</p></div></div>
    </div>
  </div>
</section>
<section class="container py-4">
  <form class="mj-card p-3 p-lg-4 mb-4" method="get">
    <div class="row g-3 align-items-end">
      <div class="col-lg-4"><label class="form-label small text-muted">Search</label><input class="form-control form-control-lg" name="q" value="<?=e($qText)?>" placeholder="Search deals, services, companies"></div>
      <div class="col-md-3 col-lg-2"><label class="form-label small text-muted">Country</label><select class="form-select" name="country_id"><option value="0">All countries</option><?php foreach($countries as $c): ?><option value="<?=(int)$c['id']?>" <?=$countryId===(int)$c['id']?'selected':''?>><?=e($c['name'])?></option><?php endforeach; ?></select></div>
      <div class="col-md-3 col-lg-2"><label class="form-label small text-muted">Category</label><select class="form-select" name="category_id"><option value="0">All categories</option><?php foreach($categories as $cat): ?><option value="<?=(int)$cat['id']?>" <?=$catId===(int)$cat['id']?'selected':''?>><?=e($cat['name'])?></option><?php endforeach; ?></select></div>
      <div class="col-md-3 col-lg-2"><label class="form-label small text-muted">Sort</label><select class="form-select" name="sort"><option value="featured" <?=$sort==='featured'?'selected':''?>>Featured first</option><option value="new" <?=$sort==='new'?'selected':''?>>Newest</option><option value="ending" <?=$sort==='ending'?'selected':''?>>Ending soon</option><option value="popular" <?=$sort==='popular'?'selected':''?>>Popular</option></select></div>
      <div class="col-md-3 col-lg-2"><button class="btn btn-primary w-100"><i class="bi bi-search me-1"></i>Search</button></div>
    </div>
  </form>
  <div class="row g-4">
    <?php if(!$deals): ?><div class="col-12"><div class="mj-card p-5 text-center"><i class="bi bi-tags display-5 text-muted"></i><h3 class="h5 mt-3">No deals found</h3><p class="text-muted mb-0">Try another country, category or keyword.</p></div></div><?php endif; ?>
    <?php foreach($deals as $d): $url=mj_deal_public_url($d); $img=$d['image_path']?base_url($d['image_path']):asset('images/no-image.png'); $disc=(float)($d['discount_percent']??0); ?>
    <div class="col-md-6 col-xl-4">
      <div class="mj-deal-card h-100">
        <a class="mj-deal-img" href="<?=e($url)?>"><img src="<?=e($img)?>" alt="<?=e($d['title'])?>"><span class="mj-deal-badges"><?php if(!empty($d['is_sponsored'])): ?><b>Sponsored</b><?php elseif(!empty($d['is_featured'])): ?><b>Featured</b><?php endif; ?><?php if($disc>0): ?><em><?=e((string)(int)$disc)?>% OFF</em><?php endif; ?></span></a>
        <div class="p-3 p-lg-4">
          <div class="small text-muted mb-2"><i class="bi bi-geo-alt me-1"></i><?=e(trim(($d['city_name']?:'').' '.($d['country_name']?:'')) ?: 'Online / Contact seller')?> · <?=e($d['category_name'] ?: 'Deal')?></div>
          <h2 class="h5 fw-bold mb-2"><a class="text-decoration-none text-dark" href="<?=e($url)?>"><?=e($d['title'])?></a></h2>
          <p class="text-muted small mb-3"><?=e(mb_strimwidth((string)($d['short_description'] ?: strip_tags((string)$d['description'])),0,110,'...'))?></p>
          <div class="d-flex align-items-end justify-content-between gap-2 mb-3"><div><?php if((float)$d['deal_price']>0): ?><div class="h5 fw-bold text-primary mb-0"><?=money($d['deal_price'],$d['currency_code'])?></div><?php if((float)$d['original_price']>0): ?><div class="small text-muted"><s><?=money($d['original_price'],$d['currency_code'])?></s></div><?php endif; ?><?php else: ?><div class="h6 fw-bold text-primary mb-0"><?=e($d['price_note'] ?: 'Contact seller')?></div><?php endif; ?></div><div class="small text-end text-muted"><?php if($d['end_at']): ?>Ends<br><?=e(date('d M',strtotime($d['end_at'])))?><?php else: ?>Ongoing<?php endif; ?></div></div>
          <div class="d-grid gap-2"><a class="btn btn-primary rounded-pill" href="<?=e($url)?>"><i class="bi bi-chat-dots me-1"></i>View & Enquire</a></div>
        </div>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
  <?php $pages=max(1,(int)ceil($total/$perPage)); if($pages>1): ?><nav class="mt-4"><ul class="pagination justify-content-center"><?php for($i=max(1,$page-2);$i<=min($pages,$page+2);$i++): ?><li class="page-item <?=$i===$page?'active':''?>"><a class="page-link" href="?<?=e(http_build_query(array_merge($_GET,['page'=>$i])))?>"><?=$i?></a></li><?php endfor; ?></ul></nav><?php endif; ?>
</section>
<?php include __DIR__ . '/includes/footer.php'; ?>
