<?php
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/mj_deal_helpers.php';
$admin = require_admin();
mj_deal_ensure_schema();
verify_csrf();
$adminTitle = 'Deal Enquiries';
$adminSubtitle = 'Customer leads from display-only deals. Sellers handle payment/contact directly outside MJ Marketplace.';
if ($_SERVER['REQUEST_METHOD']==='POST') {
    $id=(int)($_POST['id']??0); $status=trim((string)($_POST['status']??'')); $note=trim((string)($_POST['admin_note']??''));
    try {
        if(!in_array($status,['new','contacted','interested','closed','spam'],true)) throw new RuntimeException('Invalid status.');
        q('UPDATE mj_deal_enquiries SET status=?, admin_note=?, updated_at=NOW() WHERE id=?',[$status,$note,$id]);
        admin_log('deal_enquiry_status','mj_deal_enquiries',$id,['status'=>$status]);
        flash('success','Enquiry updated.');
    } catch(Throwable $e){ flash('error',$e->getMessage()); }
    redirect('deal-enquiries.php'.(!empty($_GET['deal_id'])?'?deal_id='.(int)$_GET['deal_id']:''));
}
$status=trim((string)($_GET['status']??'')); $dealId=(int)($_GET['deal_id']??0); $qText=trim((string)($_GET['q']??''));
$where=['1=1']; $params=[];
if($status!==''){ $where[]='e.status=?'; $params[]=$status; }
if($dealId>0){ $where[]='e.deal_id=?'; $params[]=$dealId; }
if($qText!==''){ $where[]='(e.name LIKE ? OR e.email LIKE ? OR e.phone LIKE ? OR d.title LIKE ?)'; $like='%'.$qText.'%'; array_push($params,$like,$like,$like,$like); }
$page=max(1,(int)($_GET['page']??1)); $perPage=30; $offset=($page-1)*$perPage;
$total=safe_count('SELECT COUNT(*) c FROM mj_deal_enquiries e LEFT JOIN mj_deals d ON d.id=e.deal_id WHERE '.implode(' AND ',$where),$params);
$rows=[]; try { $rows=all_rows('SELECT e.*, d.title AS deal_title, d.slug AS deal_slug, co.name AS company_name FROM mj_deal_enquiries e LEFT JOIN mj_deals d ON d.id=e.deal_id LEFT JOIN mj_companies co ON co.id=e.company_id WHERE '.implode(' AND ',$where).' ORDER BY e.id DESC LIMIT '.$perPage.' OFFSET '.$offset,$params); } catch(Throwable $e){}
$summary=['new'=>safe_count('SELECT COUNT(*) c FROM mj_deal_enquiries WHERE status="new"'),'contacted'=>safe_count('SELECT COUNT(*) c FROM mj_deal_enquiries WHERE status="contacted"'),'closed'=>safe_count('SELECT COUNT(*) c FROM mj_deal_enquiries WHERE status="closed"'),'spam'=>safe_count('SELECT COUNT(*) c FROM mj_deal_enquiries WHERE status="spam"')];
include __DIR__.'/_header.php';
?>
<div class="row">
  <div class="col-md-3 col-6"><div class="small-box bg-danger"><div class="inner"><h3><?=e($summary['new'])?></h3><p>New</p></div><div class="icon"><i class="fas fa-bell"></i></div></div></div>
  <div class="col-md-3 col-6"><div class="small-box bg-info"><div class="inner"><h3><?=e($summary['contacted'])?></h3><p>Contacted</p></div><div class="icon"><i class="fas fa-phone"></i></div></div></div>
  <div class="col-md-3 col-6"><div class="small-box bg-success"><div class="inner"><h3><?=e($summary['closed'])?></h3><p>Closed</p></div><div class="icon"><i class="fas fa-check"></i></div></div></div>
  <div class="col-md-3 col-6"><div class="small-box bg-secondary"><div class="inner"><h3><?=e($summary['spam'])?></h3><p>Spam</p></div><div class="icon"><i class="fas fa-ban"></i></div></div></div>
</div>
<div class="card card-primary card-outline"><div class="card-header"><h3 class="card-title"><i class="fas fa-envelope-open-text mr-2"></i>Deal Enquiries</h3></div><div class="card-body">
<form class="row mb-3" method="get"><div class="col-md-5 mb-2"><input class="form-control" name="q" value="<?=e($qText)?>" placeholder="Search name, email, phone, deal"></div><div class="col-md-3 mb-2"><select class="form-control" name="status"><option value="">All statuses</option><?php foreach(['new','contacted','interested','closed','spam'] as $s): ?><option value="<?=e($s)?>" <?=$status===$s?'selected':''?>><?=e(ucwords($s))?></option><?php endforeach; ?></select></div><div class="col-md-4 mb-2"><button class="btn btn-primary">Filter</button> <a class="btn btn-light" href="deal-enquiries.php">Reset</a></div></form>
<div class="table-responsive"><table class="table table-hover table-striped"><thead><tr><th>Customer</th><th>Deal</th><th>Message</th><th>Status</th><th>Date</th><th width="260">Update</th></tr></thead><tbody>
<?php if(!$rows): ?><tr><td colspan="6"><div class="text-center text-muted py-4"><i class="fas fa-inbox fa-2x mb-2"></i><h5>No enquiries found</h5></div></td></tr><?php endif; ?>
<?php foreach($rows as $r): ?><tr><td><b><?=e($r['name'])?></b><br><small><?=e($r['email'] ?: '-')?><br><?=e($r['phone'] ?: '-')?></small></td><td><a href="../deal.php?id=<?=(int)$r['deal_id']?>" target="_blank"><?=e($r['deal_title'] ?: 'Deal')?></a><br><small class="text-muted"><?=e($r['company_name'] ?: '')?></small></td><td><?=nl2br(e(mb_strimwidth((string)$r['message'],0,180,'...')))?><br><?php if($r['preferred_datetime']): ?><small class="text-muted">Preferred: <?=e($r['preferred_datetime'])?></small><?php endif; ?></td><td><span class="badge badge-<?= $r['status']==='new'?'danger':($r['status']==='closed'?'success':($r['status']==='spam'?'secondary':'info')) ?>"><?=e(ucwords($r['status']))?></span></td><td><small><?=e(date('d M Y H:i',strtotime($r['created_at'])))?></small></td><td><form method="post" class="mb-0"><?=csrf_input()?><input type="hidden" name="id" value="<?=(int)$r['id']?>"><div class="input-group input-group-sm mb-1"><select class="form-control" name="status"><?php foreach(['new','contacted','interested','closed','spam'] as $s): ?><option value="<?=e($s)?>" <?=$r['status']===$s?'selected':''?>><?=e(ucwords($s))?></option><?php endforeach; ?></select><div class="input-group-append"><button class="btn btn-primary">Save</button></div></div><input class="form-control form-control-sm" name="admin_note" value="<?=e($r['admin_note'] ?? '')?>" placeholder="Admin note"></form></td></tr><?php endforeach; ?>
</tbody></table></div>
<?php $pages=max(1,(int)ceil($total/$perPage)); if($pages>1): ?><ul class="pagination pagination-sm mb-0"><?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><?php endif; ?>
</div></div>
<?php include __DIR__.'/_footer.php'; ?>
