<?php
require_once __DIR__.'/includes/functions.php';
require_once __DIR__.'/includes/account-v281-ui.php';
mj_v281_ensure_schema();
$u = require_user(); $userId=(int)$u['id']; mj_require_user_feature('crm_leads', $userId, 'CRM / Leads is not enabled for your account.'); $pageTitle='CRM / Leads';
$tabs=['inbox'=>'Lead Inbox','pipeline'=>'Pipeline','followups'=>'Follow-up Calendar','timeline'=>'Customer Timeline','quick'=>'Quick Replies','performance'=>'Performance','automation'=>'Automation'];
$tab=(string)($_GET['tab'] ?? 'inbox'); if(!isset($tabs[$tab])){$tab='inbox';}
try{
  if($_SERVER['REQUEST_METHOD']==='POST'){
    verify_csrf();
    $action=(string)($_POST['action']??'');
    if($action==='add_lead'){
      $name=trim((string)($_POST['name']??'')); $email=trim((string)($_POST['email']??'')); $phone=trim((string)($_POST['phone']??''));
      if($name==='' && $email==='' && $phone===''){ throw new RuntimeException('Please enter at least name, email or phone.'); }
      q('INSERT INTO mj_customers(owner_user_id,name,email,phone,status,source_type,source_label,last_activity_at,created_at) VALUES(?,?,?,?,"new","manual","Manual CRM",NOW(),NOW())',[$userId,substr($name,0,190),substr($email,0,190),substr($phone,0,80)]);
      $cid=(int)db()->lastInsertId();
      q('INSERT INTO mj_customer_timeline(customer_id,actor_user_id,event_type,event_title,event_note,created_at) VALUES(?,?,?,?,?,NOW())',[$cid,$userId,'manual','Lead added','Added from CRM / Leads page.']);
      mj_v281_log_activity($userId,'crm_lead_added','Added CRM lead: '.($name ?: $email ?: $phone));
      flash('success','Lead added.'); redirect('crm-leads.php');
    }
    if($action==='quick_reply'){
      $title=trim((string)($_POST['title']??'')); $message=trim((string)($_POST['message']??''));
      if($title==='' || $message===''){ throw new RuntimeException('Quick reply title and message are required.'); }
      q('INSERT INTO mj_quick_reply_templates(user_id,title,message,is_active,created_at) VALUES(?,?,?,?,NOW())',[$userId,substr($title,0,190),$message,1]);
      mj_v281_log_activity($userId,'quick_reply_added','Added quick reply: '.$title);
      flash('success','Quick reply saved.'); redirect('crm-leads.php?tab=quick');
    }
  }
}catch(Throwable $e){ flash('error',$e->getMessage()); }
$statuses=['new','contacted','interested','offered','won','lost','follow_up'];
$statusCounts=[]; foreach($statuses as $s){ $statusCounts[$s]=mj_v281_table_count('mj_customers','owner_user_id=? AND status=?',[$userId,$s]); }
$leads=table_exists('mj_customers')?all_rows('SELECT * FROM mj_customers WHERE owner_user_id=? ORDER BY COALESCE(last_activity_at,created_at) DESC, id DESC LIMIT 60',[$userId]):[];
$hot=table_exists('mj_customers')?all_rows('SELECT * FROM mj_customers WHERE owner_user_id=? AND lead_score>=? ORDER BY lead_score DESC,id DESC LIMIT 20',[$userId,(int)setting('crm_hot_lead_score','70')]):[];
$followups=table_exists('mj_customers')?all_rows('SELECT * FROM mj_customers WHERE owner_user_id=? AND next_followup_at IS NOT NULL ORDER BY next_followup_at ASC LIMIT 30',[$userId]):[];
$timeline=table_exists('mj_customer_timeline')?all_rows('SELECT t.*, c.name customer_name, c.email customer_email FROM mj_customer_timeline t JOIN mj_customers c ON c.id=t.customer_id WHERE c.owner_user_id=? ORDER BY t.id DESC LIMIT 30',[$userId]):[];
$quick=table_exists('mj_quick_reply_templates')?all_rows('SELECT * FROM mj_quick_reply_templates WHERE user_id=? ORDER BY id DESC LIMIT 20',[$userId]):[];
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> Smart CRM</span><h1 class="fw-bold mb-1">CRM / Leads</h1><p class="text-muted mb-0">Lead inbox, customer timeline, follow-up reminders, quick replies, lead scoring and seller automation.</p></div></div>
  <?php mj_v281_tabs($tabs,$tab,'crm-leads.php'); ?>

  <?php if($tab==='inbox'): ?>
    <div class="row g-4 mb-4"><?php foreach($statusCounts as $s=>$c): ?><div class="col-6 col-md-4 col-xl"><div class="stat"><b><?=e($c)?></b><br><span class="muted"><?=e(ucwords(str_replace('_',' ',$s)))?></span></div></div><?php endforeach; ?></div>
    <form method="post" class="card card-body border-0 rounded-4 shadow-sm mb-4"><?=csrf_input()?><input type="hidden" name="action" value="add_lead"><h3 class="h5 fw-bold">Add Manual Lead</h3><div class="row g-3"><div class="col-md-4"><input class="form-control" name="name" placeholder="Customer name"></div><div class="col-md-4"><input class="form-control" name="email" placeholder="Email"></div><div class="col-md-4"><input class="form-control" name="phone" placeholder="Phone / WhatsApp"></div></div><button class="btn btn-primary rounded-pill mt-3">Add Lead</button></form>
    <div class="card card-body border-0 rounded-4 shadow-sm"><div class="d-flex justify-content-between align-items-center mb-3"><h3 class="h5 fw-bold mb-0">Lead Inbox</h3><a href="<?=base_url('my-customers.php')?>">Classic Customer Page</a></div><?php if(!$leads): mj_v281_empty('No CRM leads yet','Leads from enquiries, offers, quotes, orders, QR scans, social shares and manual entry will appear here.','bi-people'); else: ?><div class="table-responsive"><table class="table align-middle"><thead><tr><th>Customer</th><th>Contact</th><th>Status</th><th>Score</th><th>Source</th><th>Next Follow-up</th><th></th></tr></thead><tbody><?php foreach($leads as $l): ?><tr><td><b><?=e($l['name'] ?: 'Unnamed')?></b><br><small class="text-muted"><?=e($l['tags'] ?? '')?></small></td><td><?=e($l['email'] ?? '')?><br><small><?=e($l['phone'] ?? $l['whatsapp'] ?? '')?></small></td><td><?=mj_v281_badge((string)($l['status'] ?? 'new'))?></td><td><b><?=e((int)($l['lead_score'] ?? 0))?></b></td><td><?=e($l['source_label'] ?? $l['source_type'] ?? '')?></td><td><?=e($l['next_followup_at'] ?? '')?></td><td><a class="btn btn-sm btn-outline-primary" href="<?=base_url('customer-view.php?id='.(int)$l['id'])?>">Open</a></td></tr><?php endforeach; ?></tbody></table></div><?php endif; ?></div>

  <?php elseif($tab==='pipeline'): ?>
    <div class="row g-3"><?php foreach($statuses as $s): ?><div class="col-md-6 col-xl-3"><div class="mj-mini-card"><h5 class="fw-bold"><?=e(ucwords(str_replace('_',' ',$s)))?></h5><div class="display-6 fw-bold text-primary"><?=e($statusCounts[$s])?></div><p class="text-muted mb-0">Pipeline stage for CRM tracking.</p></div></div><?php endforeach; ?></div>
    <div class="mt-4"><?php mj_v281_feature_grid([['bi-tags','Lead Tags','Hot, Warm, Cold, Follow-up and Closed tags.'],['bi-person-check','Lead Assignment','Company owner can assign leads to staff.'],['bi-diagram-3','Duplicate Detection','Group same buyer asking multiple listings.']]); ?></div>

  <?php elseif($tab==='followups'): ?>
    <div class="card card-body border-0 rounded-4 shadow-sm"><h3 class="h5 fw-bold">Follow-up Calendar</h3><?php if(!$followups): mj_v281_empty('No scheduled follow-ups','Set next follow-up date in customer profile and reminders will appear here.','bi-calendar-check'); else: ?><div class="table-responsive"><table class="table"><thead><tr><th>Follow-up</th><th>Customer</th><th>Contact</th><th>Status</th></tr></thead><tbody><?php foreach($followups as $f): ?><tr><td><?=e($f['next_followup_at'])?></td><td><?=e($f['name'] ?? '')?></td><td><?=e($f['email'] ?? $f['phone'] ?? '')?></td><td><?=mj_v281_badge((string)$f['status'])?></td></tr><?php endforeach; ?></tbody></table></div><?php endif; ?></div>
    <div class="mt-4"><?php mj_v281_feature_grid([['bi-bell','Auto Reminder','Alert seller before scheduled follow-up.'],['bi-exclamation-circle','Missed Lead Alert','Notify if seller did not reply within X hours.'],['bi-clock-history','Offer Expiry Reminder','Remind buyer before offer expires.']]); ?></div>

  <?php elseif($tab==='timeline'): ?>
    <?php if(!$timeline): mj_v281_empty('No customer timeline yet','Every enquiry, offer, note, order, payment and admin update will appear here.','bi-clock-history'); else: ?><div class="mj-timeline"><?php foreach($timeline as $t): ?><div class="mj-timeline-item"><b><?=e($t['event_title'] ?: $t['event_type'])?></b><div class="small text-muted"><?=e($t['created_at'])?> · <?=e($t['customer_name'] ?: $t['customer_email'])?></div><p class="mb-0"><?=e($t['event_note'] ?? '')?></p></div><?php endforeach; ?></div><?php endif; ?>

  <?php elseif($tab==='quick'): ?>
    <form method="post" class="card card-body border-0 rounded-4 shadow-sm mb-4"><?=csrf_input()?><input type="hidden" name="action" value="quick_reply"><h3 class="h5 fw-bold">Add Quick Reply Template</h3><label class="label">Title</label><input class="form-control" name="title" placeholder="Example: Price enquiry reply"><label class="label">Message</label><textarea class="form-control" rows="4" name="message" placeholder="Thanks for your enquiry..."></textarea><button class="btn btn-primary rounded-pill mt-3">Save Template</button></form>
    <?php if(!$quick): mj_v281_empty('No quick replies yet','Create saved replies for common buyer questions.','bi-reply'); else: ?><div class="row g-3"><?php foreach($quick as $q): ?><div class="col-md-6"><div class="mj-mini-card"><h5 class="fw-bold"><?=e($q['title'])?></h5><p class="text-muted mb-0"><?=nl2br(e($q['message']))?></p></div></div><?php endforeach; ?></div><?php endif; ?>

  <?php elseif($tab==='performance'): ?>
    <div class="row g-4 mb-4"><div class="col-md-4"><div class="stat"><b><?=e(count($hot))?></b><br><span class="muted">Hot Leads</span></div></div><div class="col-md-4"><div class="stat"><b><?=e(mj_v281_table_count('mj_customers','owner_user_id=? AND last_activity_at < DATE_SUB(NOW(), INTERVAL '.max(1,(int)setting('crm_no_response_days','3')).' DAY)',[$userId]))?></b><br><span class="muted">Needs Follow-up</span></div></div><div class="col-md-4"><div class="stat"><b><?=e(mj_v281_table_count('mj_customers','owner_user_id=?',[$userId]))?></b><br><span class="muted">Total Customers</span></div></div></div>
    <?php mj_v281_feature_grid([['bi-fire','Lead Priority Score','Hot lead based on repeat views, offers, WhatsApp clicks and QR scans.'],['bi-bar-chart','Listing Performance','Views, clicks, call taps, WhatsApp clicks and enquiry conversion.'],['bi-lightbulb','Boost Suggestions','Suggest sponsor/feature when views or leads are low.']]); ?>

  <?php elseif($tab==='automation'): ?>
    <?php mj_v281_feature_grid([['bi-robot','Auto Reply','Automatic reply when seller is offline or in away mode.'],['bi-shop-window','Business Hours Reply','Different message after working hours.'],['bi-alarm','Renew Countdown','Notify user before listing expiry and request renew flow.'],['bi-envelope-paper','Daily Digest','One clean summary instead of many notifications.'],['bi-person-lines-fill','CRM Auto Customer','Create/update customer from quote, offer, order and chat.'],['bi-person-badge','Staff Assignment','Assign lead to staff, branch or company manager.']]); ?>
  <?php endif; ?>
</section></div></div>
<?php include __DIR__.'/includes/footer.php'; ?>
