<?php
require_once __DIR__.'/../includes/functions.php';
$admin=require_admin(); verify_csrf(); mj_crm_ensure_schema(); $adminTitle='Customers / CRM';

if(isset($_GET['sync'])){ $res=mj_crm_sync_from_marketplace(); flash('success','CRM sync completed. Records checked: '.$res['updated']); redirect('customers.php'); }

$status=trim((string)($_GET['status']??'')); $qstr=trim((string)($_GET['q']??'')); $company=(int)($_GET['company_id']??0);
$where=[]; $params=[];
if($status!=='' && array_key_exists($status,mj_crm_statuses())){ $where[]='c.status=?'; $params[]=$status; }
if($company>0){ $where[]='c.company_id=?'; $params[]=$company; }
if($qstr!==''){ $where[]='(c.name LIKE ? OR c.email LIKE ? OR c.phone LIKE ? OR c.whatsapp LIKE ? OR co.name LIKE ? OR u.email LIKE ?)'; $like='%'.$qstr.'%'; array_push($params,$like,$like,$like,$like,$like,$like); }
$rows=all_rows('SELECT c.*, co.name company_name, u.name owner_name, u.email owner_email FROM mj_customers c LEFT JOIN mj_companies co ON co.id=c.company_id LEFT JOIN mj_users u ON u.id=c.owner_user_id '.($where?'WHERE '.implode(' AND ',$where):'').' ORDER BY COALESCE(c.next_followup_at,c.last_activity_at,c.created_at) DESC LIMIT 500',$params);
$companies=safe_all_rows_public('SELECT id,name FROM mj_companies ORDER BY name LIMIT 500');
$stats=[
 'total'=>safe_count('SELECT COUNT(*) c FROM mj_customers'),
 'follow'=>safe_count('SELECT COUNT(*) c FROM mj_customers WHERE next_followup_at IS NOT NULL AND DATE(next_followup_at)<=CURDATE()'),
 'hot'=>safe_count('SELECT COUNT(*) c FROM mj_customers WHERE lead_score>=?',[(int)setting('crm_hot_lead_score','70')]),
 'converted'=>safe_count('SELECT COUNT(*) c FROM mj_customers WHERE status="converted"')
];
include __DIR__.'/_header.php';
?>
<div class="row">
  <div class="col-lg-3 col-6"><div class="small-box bg-info"><div class="inner"><h3><?=e($stats['total'])?></h3><p>Total Customers</p></div><div class="icon"><i class="fas fa-users"></i></div></div></div>
  <div class="col-lg-3 col-6"><div class="small-box bg-warning"><div class="inner"><h3><?=e($stats['follow'])?></h3><p>Follow-up Due</p></div><div class="icon"><i class="fas fa-clock"></i></div></div></div>
  <div class="col-lg-3 col-6"><div class="small-box bg-danger"><div class="inner"><h3><?=e($stats['hot'])?></h3><p>Hot Leads</p></div><div class="icon"><i class="fas fa-fire"></i></div></div></div>
  <div class="col-lg-3 col-6"><div class="small-box bg-success"><div class="inner"><h3><?=e($stats['converted'])?></h3><p>Converted</p></div><div class="icon"><i class="fas fa-check"></i></div></div></div>
</div>
<div class="card card-primary card-outline">
  <div class="card-header"><h3 class="card-title"><i class="fas fa-address-book mr-2"></i>Customer Management</h3><div class="card-tools"><a href="customers.php?sync=1" class="btn btn-sm btn-success"><i class="fas fa-sync mr-1"></i>Sync Marketplace Leads</a></div></div>
  <div class="card-body"><?php show_flash(); ?>
    <form class="form-inline mb-3">
      <input class="form-control mr-2" name="q" value="<?=e($qstr)?>" placeholder="Search customer, owner, company">
      <select class="form-control mr-2" name="status"><option value="">All statuses</option><?php foreach(mj_crm_statuses() as $k=>$v): ?><option value="<?=e($k)?>" <?=$status===$k?'selected':''?>><?=e($v)?></option><?php endforeach; ?></select>
      <select class="form-control mr-2" name="company_id"><option value="">All companies</option><?php foreach($companies as $co): ?><option value="<?=e($co['id'])?>" <?=$company===(int)$co['id']?'selected':''?>><?=e($co['name'])?></option><?php endforeach; ?></select>
      <button class="btn btn-primary">Filter</button>
      <a class="btn btn-outline-secondary ml-2" href="customers.php">Clear</a>
    </form>
    <div class="table-responsive"><table class="table table-hover">
      <thead><tr><th>Customer</th><th>Owner / Company</th><th>Status</th><th>Score</th><th>Follow-up</th><th>Last Activity</th><th>Action</th></tr></thead>
      <tbody>
      <?php foreach($rows as $r): ?><tr>
        <td><b><?=e($r['name'] ?: 'Customer #'.$r['id'])?></b><br><small><?=e($r['email'])?> <?=e($r['phone'])?></small></td>
        <td><?=e($r['owner_name'] ?: $r['owner_email'])?><br><small><?=e($r['company_name'] ?: 'General')?></small></td>
        <td><span class="badge badge-<?=e(mj_crm_status_class($r['status']))?>"><?=e(mj_crm_status_label($r['status']))?></span></td>
        <td><b><?=e($r['lead_score'])?>%</b></td>
        <td><?=e($r['next_followup_at'] ?: '-')?></td>
        <td><?=e($r['last_activity_at'] ?: $r['created_at'])?></td>
        <td><a class="btn btn-sm btn-primary" href="customer-view.php?id=<?=e($r['id'])?>">Open</a></td>
      </tr><?php endforeach; ?>
      <?php if(!$rows): ?><tr><td colspan="7" class="text-center text-muted py-4">No customers found.</td></tr><?php endif; ?>
      </tbody>
    </table></div>
  </div>
</div>
<?php include __DIR__.'/_footer.php'; ?>
