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

$uid=(int)$u['id'];
$tab=strtolower(trim((string)($_GET['tab'] ?? 'all')));
$status=strtolower(trim((string)($_GET['status'] ?? '')));
$qstr=trim((string)($_GET['q'] ?? ''));
$where=['(o.buyer_id=? OR o.seller_id=?)']; $params=[$uid,$uid];
if($tab==='buying'){ $where[]='o.buyer_id=?'; $params[]=$uid; }
elseif($tab==='selling'){ $where[]='o.seller_id=?'; $params[]=$uid; }
elseif($tab==='discussion'){ $where[]='o.status IN ("pending_payment","processing","payment_submitted","ready")'; }
elseif($tab==='completed'){ $where[]='o.status="completed"'; }
elseif($tab==='disputed'){ $where[]='o.status="disputed"'; }
if($status!=='' && array_key_exists($status,mj_order_statuses())){ $where[]='o.status=?'; $params[]=$status; }
if($qstr!==''){ $where[]='(o.order_number LIKE ? OR l.title LIKE ? OR co.name LIKE ? OR b.name LIKE ? OR s.name LIKE ?)'; $like='%'.$qstr.'%'; array_push($params,$like,$like,$like,$like,$like); }
$rows=all_rows('SELECT o.*, l.title listing_title, (SELECT li.image_path FROM mj_listing_images li WHERE li.listing_id=l.id ORDER BY li.sort_order,li.id LIMIT 1) listing_image, b.name buyer_name, s.name seller_name, co.name company_name FROM mj_orders o LEFT JOIN mj_listings l ON l.id=o.listing_id LEFT JOIN mj_users b ON b.id=o.buyer_id LEFT JOIN mj_users s ON s.id=o.seller_id LEFT JOIN mj_companies co ON co.id=COALESCE(o.company_id,l.company_id) WHERE '.implode(' AND ',$where).' ORDER BY o.updated_at DESC,o.id DESC LIMIT 200',$params);
$counts=['buying'=>0,'selling'=>0,'discussion'=>0,'pending_payment'=>0,'processing'=>0,'payment_submitted'=>0,'ready'=>0,'completed'=>0,'disputed'=>0];
try{ $counts['buying']=(int)(one('SELECT COUNT(*) c FROM mj_orders WHERE buyer_id=?',[$uid])['c']??0); $counts['selling']=(int)(one('SELECT COUNT(*) c FROM mj_orders WHERE seller_id=?',[$uid])['c']??0); foreach(all_rows('SELECT status,COUNT(*) c FROM mj_orders WHERE buyer_id=? OR seller_id=? GROUP BY status',[$uid,$uid]) as $c){$counts[(string)$c['status']]=(int)$c['c'];} $counts['discussion']=(int)($counts['pending_payment']??0)+(int)($counts['processing']??0)+(int)($counts['payment_submitted']??0)+(int)($counts['ready']??0);}catch(Throwable $e){}
$pageTitle='My Enquiries'; include __DIR__.'/includes/header.php';
?>
<div class="container py-5"><div class="sidebar-layout"><?php include __DIR__.'/includes/account-sidebar.php'; ?><section>
  <div class="mj-page-hero rounded-4 mb-4"><div class="container-fluid"><span class="mj-badge mb-2"><i class="bi bi-bag-check"></i>Enquiries</span><h1 class="fw-bold mb-1">My Enquiries</h1><p class="text-muted mb-0">Accepted offers and quotations become enquiry records. Customer-to-seller payment is disabled on MJ Marketplace.</p></div></div>
  <?php show_flash(); ?>
  <div class="row g-3 mb-4"><div class="col-md-3"><div class="mj-quote-stat"><span>Buying</span><b><?=e($counts['buying'])?></b></div></div><div class="col-md-3"><div class="mj-quote-stat"><span>Selling</span><b><?=e($counts['selling'])?></b></div></div><div class="col-md-3"><div class="mj-quote-stat"><span>In Discussion</span><b><?=e($counts['discussion']??0)?></b></div></div><div class="col-md-3"><div class="mj-quote-stat"><span>Completed</span><b><?=e($counts['completed']??0)?></b></div></div></div>
  <div class="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','buying'=>'Buying','selling'=>'Selling','discussion'=>'Discussion','completed'=>'Completed','disputed'=>'Issues'] as $k=>$v): ?><a class="btn btn-sm <?=$tab===$k?'btn-primary':'btn-outline-primary'?> rounded-pill" href="<?=e(base_url('my-orders.php?tab='.$k.($qstr!==''?'&q='.rawurlencode($qstr):'')))?>"><?=e($v)?></a><?php endforeach; ?></div><form class="d-flex flex-wrap gap-2" method="get"><input type="hidden" name="tab" value="<?=e($tab)?>"><input class="form-control rounded-pill" name="q" value="<?=e($qstr)?>" placeholder="Search enquiry, listing, company"><select class="form-select rounded-pill" name="status"><option value="">All statuses</option><?php foreach(mj_order_statuses() as $k=>$v): ?><option value="<?=e($k)?>" <?=$status===$k?'selected':''?>><?=e($v)?></option><?php endforeach; ?></select><button class="btn btn-primary rounded-pill"><i class="bi bi-search"></i></button></form></div></div>
  <?php if(!$rows): ?><div class="mj-card p-5 text-center"><div class="mj-icon-box mx-auto mb-3"><i class="bi bi-bag-check"></i></div><h3 class="fw-bold">No enquiries yet</h3><p class="text-muted">Enquiry records are created after an accepted offer or accepted quotation. No customer payment is collected by MJ Marketplace.</p><div class="d-flex justify-content-center gap-2 flex-wrap"><a class="btn btn-primary rounded-pill" href="<?=e(base_url('browse.php'))?>">Browse Listings</a><a class="btn btn-outline-primary rounded-pill" href="<?=e(base_url('my-offers.php'))?>">View Offers</a><a class="btn btn-outline-primary rounded-pill" href="<?=e(base_url('my-quotes.php'))?>">View Quotes</a></div></div><?php else: ?>
  <?php foreach($rows as $r): $isSeller=$uid===(int)$r['seller_id']; $img=!empty($r['listing_image'])?base_url($r['listing_image']):asset('images/empty-state.svg'); ?><div class="mj-card p-3 mb-3 mj-order-row"><div class="row g-3 align-items-center"><div class="col-lg-7"><div class="d-flex gap-3"><img src="<?=e($img)?>" class="mj-offer-thumb" alt=""><div><div class="d-flex flex-wrap gap-2 mb-2"><span class="badge text-bg-<?=e(mj_order_status_class((string)$r['status']))?> rounded-pill"><?=e(mj_order_status_label((string)$r['status']))?></span><span class="badge text-bg-<?=e(mj_order_payment_status_class((string)($r['payment_status']??'')))?> rounded-pill"><?=e(mj_order_payment_status_label((string)($r['payment_status']??'')))?></span><span class="mj-badge"><?=e($isSeller?'Selling':'Buying')?></span><span class="mj-badge"><?=e(ucwords(str_replace('_',' ',(string)($r['source_type']?:'manual'))))?></span></div><h4 class="fw-bold mb-1"><a href="<?=e(base_url('order-view.php?id='.(int)$r['id']))?>" class="text-dark text-decoration-none"><?=e($r['order_number'] ?: 'Enquiry #'.(int)$r['id'])?></a></h4><p class="text-muted mb-1"><?=e($r['listing_title'] ?: 'Enquiry')?><?=!empty($r['company_name'])?' • '.e($r['company_name']):''?></p><small><?=e($isSeller?'Buyer: '.($r['buyer_name']?:'Buyer'):'Seller: '.($r['seller_name']?:'Seller'))?></small></div></div></div><div class="col-lg-2"><span class="text-muted small d-block">Agreed amount</span><b class="fs-5"><?=money($r['total_amount'] ?: $r['amount'],$r['currency_code'] ?: 'SGD')?></b></div><div class="col-lg-3 text-lg-end"><a class="btn btn-sm btn-primary" href="<?=e(base_url('order-view.php?id='.(int)$r['id']))?>">View Enquiry</a><a class="btn btn-sm btn-outline-primary" href="<?=e(mj_order_chat_url($r))?>"><i class="bi bi-chat-dots"></i> Chat</a></div></div></div><?php endforeach; ?><?php endif; ?>
</section></div></div>
<?php include __DIR__.'/includes/footer.php'; ?>
