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

$uid=(int)$u['id'];
if(isset($_GET['sync'])){ $res=mj_crm_sync_from_marketplace(); flash('success','Customer sync completed. Records checked: '.$res['updated']); redirect('my-customers.php'); }

if($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action']??'')==='add_manual'){
  $cid=mj_crm_find_or_create_customer([
    'owner_user_id'=>$uid,
    'company_id'=>!empty($_POST['company_id'])?(int)$_POST['company_id']:null,
    'name'=>trim((string)($_POST['name']??'')),
    'email'=>trim((string)($_POST['email']??'')),
    'phone'=>trim((string)($_POST['phone']??'')),
    'whatsapp'=>trim((string)($_POST['whatsapp']??'')),
    'source_type'=>'manual',
    'source_label'=>'Manual entry',
    'status'=>trim((string)($_POST['status']??'new')),
    'actor_user_id'=>$uid
  ]);
  if($cid){ flash('success','Customer saved.'); redirect('customer-view.php?id='.$cid); }
  flash('error','Unable to save customer. Please enter at least useful customer details.');
}

$status=trim((string)($_GET['status']??''));
$qstr=trim((string)($_GET['q']??''));
$follow=trim((string)($_GET['follow']??''));
$where=['c.owner_user_id=?']; $params=[$uid];
if($status!=='' && array_key_exists($status,mj_crm_statuses())){ $where[]='c.status=?'; $params[]=$status; }
if($follow==='today'){ $where[]='c.next_followup_at IS NOT NULL AND DATE(c.next_followup_at)<=CURDATE()'; }
if($qstr!==''){ $where[]='(c.name LIKE ? OR c.email LIKE ? OR c.phone LIKE ? OR c.whatsapp LIKE ? OR co.name LIKE ? OR c.tags LIKE ?)'; $like='%'.$qstr.'%'; array_push($params,$like,$like,$like,$like,$like,$like); }

$rows=all_rows('SELECT c.*, co.name company_name FROM mj_customers c LEFT JOIN mj_companies co ON co.id=c.company_id WHERE '.implode(' AND ',$where).' ORDER BY COALESCE(c.next_followup_at,c.last_activity_at,c.created_at) DESC LIMIT 300',$params);
$companies=safe_all_rows_public('SELECT id,name FROM mj_companies WHERE user_id=? ORDER BY name',[$uid]);
$counts=['all'=>0,'follow'=>0,'hot'=>0];
try{
  $counts['all']=safe_count('SELECT COUNT(*) c FROM mj_customers WHERE owner_user_id=?',[$uid]);
  $counts['follow']=safe_count('SELECT COUNT(*) c FROM mj_customers WHERE owner_user_id=? AND next_followup_at IS NOT NULL AND DATE(next_followup_at)<=CURDATE()',[$uid]);
  $counts['hot']=safe_count('SELECT COUNT(*) c FROM mj_customers WHERE owner_user_id=? AND lead_score>=?',[$uid,(int)setting('crm_hot_lead_score','70')]);
}catch(Throwable $e){}
$pageTitle='My Customers'; 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-people"></i>Customer CRM</span>
    <h1 class="fw-bold mb-1">My Customers</h1>
    <p class="text-muted mb-0">Manage leads and customers from chats, quotes, offers, orders and manual follow-ups.</p>
  </div></div>
  <?php show_flash(); ?>
  <div class="row g-3 mb-4">
    <div class="col-md-4"><div class="mj-quote-stat"><span>Total Customers</span><b><?=e($counts['all'])?></b></div></div>
    <div class="col-md-4"><div class="mj-quote-stat"><span>Follow-up Due</span><b><?=e($counts['follow'])?></b></div></div>
    <div class="col-md-4"><div class="mj-quote-stat"><span>Hot Leads</span><b><?=e($counts['hot'])?></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">
      <form class="d-flex flex-wrap gap-2" method="get">
        <input class="form-control rounded-pill" name="q" value="<?=e($qstr)?>" placeholder="Search customer, email, phone, company">
        <select class="form-select rounded-pill" 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-select rounded-pill" name="follow"><option value="">All follow-ups</option><option value="today" <?=$follow==='today'?'selected':''?>>Due today/overdue</option></select>
        <button class="btn btn-primary rounded-pill"><i class="bi bi-search"></i></button>
      </form>
      <div class="d-flex flex-wrap gap-2">
        <a class="btn btn-outline-primary rounded-pill" href="<?=e(base_url('my-customers.php?sync=1'))?>"><i class="bi bi-arrow-repeat me-1"></i>Sync Leads</a>
        <button class="btn btn-success rounded-pill" data-bs-toggle="collapse" data-bs-target="#addCustomer"><i class="bi bi-plus-circle me-1"></i>Add Customer</button>
      </div>
    </div>
  </div>

  <div class="collapse mb-4" id="addCustomer">
    <form method="post" class="mj-card p-4">
      <?=csrf_input()?><input type="hidden" name="action" value="add_manual">
      <h4 class="fw-bold mb-3">Add customer manually</h4>
      <div class="row g-3">
        <div class="col-md-6"><label class="form-label fw-bold">Name</label><input class="form-control" name="name" required></div>
        <div class="col-md-6"><label class="form-label fw-bold">Company source</label><select class="form-select" name="company_id"><option value="">General / no company</option><?php foreach($companies as $co): ?><option value="<?=e($co['id'])?>"><?=e($co['name'])?></option><?php endforeach; ?></select></div>
        <div class="col-md-6"><label class="form-label fw-bold">Email</label><input class="form-control" name="email" type="email"></div>
        <div class="col-md-6"><label class="form-label fw-bold">Phone</label><input class="form-control" name="phone"></div>
        <div class="col-md-6"><label class="form-label fw-bold">WhatsApp</label><input class="form-control" name="whatsapp"></div>
        <div class="col-md-6"><label class="form-label fw-bold">Status</label><select class="form-select" name="status"><?php foreach(mj_crm_statuses() as $k=>$v): ?><option value="<?=e($k)?>"><?=e($v)?></option><?php endforeach; ?></select></div>
      </div>
      <button class="btn btn-primary rounded-pill mt-3">Save Customer</button>
    </form>
  </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-people"></i></div><h3 class="fw-bold">No customers yet</h3><p class="text-muted">Click Sync Leads to create customer records from quotes, offers and orders, or add one manually.</p></div>
  <?php else: ?>
    <?php foreach($rows as $r): ?>
      <div class="mj-card p-3 mb-3">
        <div class="row g-3 align-items-center">
          <div class="col-lg-6">
            <div class="d-flex flex-wrap gap-2 mb-2">
              <span class="badge text-bg-<?=e(mj_crm_status_class($r['status']))?> rounded-pill"><?=e(mj_crm_status_label($r['status']))?></span>
              <?php if((int)$r['lead_score']>=70): ?><span class="mj-badge warn">Hot Lead</span><?php endif; ?>
              <?php if($r['company_name']): ?><span class="mj-badge"><i class="bi bi-building"></i><?=e($r['company_name'])?></span><?php endif; ?>
            </div>
            <h4 class="fw-bold mb-1"><a class="text-dark text-decoration-none" href="<?=e(base_url('customer-view.php?id='.(int)$r['id']))?>"><?=e($r['name'] ?: 'Customer #'.$r['id'])?></a></h4>
            <p class="text-muted small mb-0"><?=e(mj_crm_mask_contact($r['email']))?> · <?=e(mj_crm_mask_contact($r['phone'] ?: $r['whatsapp']))?></p>
          </div>
          <div class="col-lg-3">
            <span class="text-muted small d-block">Lead score</span>
            <b><?=e($r['lead_score'])?>%</b>
            <?php if($r['next_followup_at']): ?><small class="d-block text-warning fw-bold">Follow-up <?=e(date('d M Y H:i',strtotime($r['next_followup_at'])))?></small><?php endif; ?>
          </div>
          <div class="col-lg-3 text-lg-end">
            <a class="btn btn-primary rounded-pill" href="<?=e(base_url('customer-view.php?id='.(int)$r['id']))?>">Open Customer</a>
          </div>
        </div>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>
</section></div></div>
<?php include __DIR__.'/includes/footer.php'; ?>
