<?php
require_once __DIR__ . '/includes/mj_v304_bootstrap.php';
require_once __DIR__ . '/includes/mj_v304_leads_helper.php';
require_once __DIR__ . '/includes/mj_v3041_access_notifications_location.php';
mjv304_require_login();
try { mjv3041_ensure_light_schema(); mjv3041_repair_seller_lead_owners(); } catch (Throwable $ignore) {}
$userId = mjv304_current_user_id();
$message = '';
$error = '';
try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $leadId = (int)($_POST['lead_id'] ?? 0);
        $own = mjv304_fetch_one("SELECT * FROM seller_leads WHERE id=? AND seller_user_id=?", [$leadId, $userId]);
        if (!$own) { throw new RuntimeException('Lead not found.'); }
        if (isset($_POST['update_status'])) {
            mjv304_update_lead_status($leadId, (string)$_POST['status'], $userId, 'user', trim((string)($_POST['note'] ?? '')));
            $message = 'Lead status updated.';
        }
        if (isset($_POST['add_note'])) {
            $follow = trim((string)($_POST['followup_at'] ?? ''));
            mjv304_add_lead_note($leadId, $userId, 'user', trim((string)($_POST['note'] ?? '')), $follow ?: null);
            $message = 'Lead note saved.';
        }
        if (isset($_POST['mark_read'])) {
            mjv304_execute("UPDATE seller_leads SET is_read=1 WHERE id=? AND seller_user_id=?", [$leadId, $userId]);
            $message = 'Lead marked as read.';
        }
    }
} catch (Throwable $e) { $error = $e->getMessage(); }

$filters = [
    'seller_user_id'=>$userId,
    'q'=>trim((string)($_GET['q'] ?? '')),
    'status'=>trim((string)($_GET['status'] ?? '')),
    'type'=>trim((string)($_GET['type'] ?? '')),
    'from'=>trim((string)($_GET['from'] ?? '')),
    'to'=>trim((string)($_GET['to'] ?? '')),
    'lead_id'=>(int)($_GET['lead_id'] ?? 0),
    'page'=>(int)($_GET['page'] ?? 1),
    'limit'=>25,
];
$data = mjv304_query_leads($filters, false);
$statusCounts = mjv304_fetch_all("SELECT status, COUNT(*) total FROM seller_leads WHERE seller_user_id=? GROUP BY status", [$userId]);
$countMap = array_fill_keys(array_keys(mjv304_status_options()), 0);
foreach ($statusCounts as $r) { $countMap[$r['status']] = (int)$r['total']; }
$todayNew = (int)mjv304_fetch_value("SELECT COUNT(*) FROM seller_leads WHERE seller_user_id=? AND status='new' AND DATE(created_at)=CURDATE()", [$userId]);
$followDue = (int)mjv304_fetch_value("SELECT COUNT(*) FROM seller_leads WHERE seller_user_id=? AND followup_at IS NOT NULL AND followup_at <= NOW() AND status NOT IN ('converted','closed','spam')", [$userId]);
$pageTitle = 'My Leads';
$metaDescription = 'Manage customer enquiries, leads and follow-ups in your MJ Marketplace account.';
include __DIR__ . '/includes/header.php';
?>
<div class="container py-4">
<div class="mj-v304-wrap">
  <div class="mj-page-head">
    <div><h1>My Leads</h1><p>All deal, listing, and company enquiries in one follow-up screen.</p></div>
    <div><?php include __DIR__ . '/includes/mj_v304_notification_widget.php'; ?></div>
  </div>

  <?php if ($message): ?><div class="mj-card" style="border-color:#bbf7d0;background:#f0fdf4;margin-bottom:12px;"><?php echo mjv304_e($message); ?></div><?php endif; ?>
  <?php if ($error): ?><div class="mj-card" style="border-color:#fecaca;background:#fef2f2;margin-bottom:12px;"><?php echo mjv304_e($error); ?></div><?php endif; ?>

  <div class="mj-grid mj-grid-4" style="margin-bottom:14px;">
    <div class="mj-card"><h3>New Today</h3><div class="num"><?php echo $todayNew; ?></div><div class="mj-muted">Fresh enquiries</div></div>
    <div class="mj-card"><h3>Needs Follow-up</h3><div class="num"><?php echo $followDue; ?></div><div class="mj-muted">Due now or overdue</div></div>
    <div class="mj-card"><h3>Converted</h3><div class="num"><?php echo (int)$countMap['converted']; ?></div><div class="mj-muted">Won leads</div></div>
    <div class="mj-card"><h3>Total Leads</h3><div class="num"><?php echo (int)$data['total']; ?></div><div class="mj-muted">Current filter result</div></div>
  </div>

  <form class="mj-card mj-filter" method="get">
    <div><label>Search</label><input name="q" value="<?php echo mjv304_e($filters['q']); ?>" placeholder="Name, phone, email, item title..."></div>
    <div><label>Status</label><select name="status"><option value="">All</option><?php foreach(mjv304_status_options() as $k=>$v): ?><option value="<?php echo $k; ?>" <?php echo $filters['status']===$k?'selected':''; ?>><?php echo mjv304_e($v); ?></option><?php endforeach; ?></select></div>
    <div><label>Type</label><select name="type"><option value="">All</option><?php foreach(['deal'=>'Deal','listing'=>'Listing','company'=>'Company'] as $k=>$v): ?><option value="<?php echo $k; ?>" <?php echo $filters['type']===$k?'selected':''; ?>><?php echo $v; ?></option><?php endforeach; ?></select></div>
    <div><label>From</label><input type="date" name="from" value="<?php echo mjv304_e($filters['from']); ?>"></div>
    <div><label>To</label><input type="date" name="to" value="<?php echo mjv304_e($filters['to']); ?>"></div>
    <div><label>&nbsp;</label><button class="mj-btn mj-btn-primary" type="submit">Filter</button></div>
    <div><label>&nbsp;</label><a class="mj-btn" href="my-leads.php">Reset</a></div>
  </form>

  <div class="mj-table-wrap">
    <table class="mj-table mj-leads-clean-table">
      <thead><tr><th>Lead</th><th>Customer</th><th>Contact</th><th>Status</th><th>Follow-up / Notes</th><th>Actions</th></tr></thead>
      <tbody>
      <?php if (!$data['rows']): ?>
        <tr><td colspan="6"><div class="mj-empty">No leads found.</div></td></tr>
      <?php endif; ?>
      <?php foreach ($data['rows'] as $lead):
          $activities = mjv304_fetch_all("SELECT * FROM seller_lead_activities WHERE lead_id=? ORDER BY created_at DESC,id DESC LIMIT 3", [(int)$lead['id']]);
          $sourceUrl = mjv304_lead_source_url($lead);
          $waMsg = 'Hi '.($lead['customer_name'] ?: '').', thank you for your enquiry about '.($lead['source_title'] ?: 'our listing').'.';
      ?>
        <tr data-lead-row="<?php echo (int)$lead['id']; ?>">
          <td data-label="Lead">
            <div class="mj-lead-title"><a href="<?php echo mjv304_e($sourceUrl); ?>" target="_blank"><?php echo mjv304_e($lead['source_title'] ?: 'Untitled item'); ?></a></div>
            <div class="mj-lead-meta">#<?php echo (int)$lead['id']; ?> • <?php echo mjv304_e(ucfirst($lead['source_type'])); ?> • <?php echo mjv304_e(date('d M Y H:i', strtotime($lead['created_at']))); ?></div>
            <?php if ((int)$lead['is_read'] === 0): ?><span class="mj-badge mj-badge-new">Unread</span><?php endif; ?>
          </td>
          <td data-label="Customer">
            <b><?php echo mjv304_e($lead['customer_name'] ?: 'Customer'); ?></b><br>
            <span class="mj-muted"><?php echo nl2br(mjv304_e($lead['customer_message'] ?: 'No message')); ?></span>
          </td>
          <td data-label="Contact">
            <?php echo mjv304_e($lead['customer_phone'] ?: '-'); ?><br>
            <span class="mj-muted"><?php echo mjv304_e($lead['customer_email'] ?: '-'); ?></span>
          </td>
          <td data-label="Status"><span data-lead-status-badge class="mj-badge <?php echo mjv304_badge_class($lead['status']); ?>"><?php echo mjv304_e(mjv304_status_options()[$lead['status']] ?? $lead['status']); ?></span></td>
          <td data-label="Follow-up / Notes">
            <?php if ($lead['followup_at']): ?><div><b>Follow-up:</b> <?php echo mjv304_e(date('d M Y H:i', strtotime($lead['followup_at']))); ?></div><?php endif; ?>
            <?php foreach ($activities as $a): ?><div class="mj-note-box"><small><?php echo mjv304_e(date('d M Y H:i', strtotime($a['created_at']))); ?> • <?php echo mjv304_e($a['activity_type']); ?></small><br><?php echo nl2br(mjv304_e($a['note'] ?: ($a['old_status'].' → '.$a['new_status']))); ?></div><?php endforeach; ?>
          </td>
          <td data-label="Actions">
            <div class="mj-lead-actions-clean">
              <a class="mj-btn mj-btn-sm" href="<?php echo mjv304_e(mjv304_whatsapp_link($lead['customer_phone'], $waMsg)); ?>" target="_blank">WhatsApp</a>
              <a class="mj-btn mj-btn-sm" href="<?php echo mjv304_e(mjv304_tel_link($lead['customer_phone'])); ?>">Call</a>
              <a class="mj-btn mj-btn-sm" href="<?php echo mjv304_e(mjv304_mail_link($lead['customer_email'], 'Your enquiry - '.($lead['source_title'] ?: 'MJ Marketplace'))); ?>">Email</a>
              <button type="button" class="mj-btn mj-btn-primary mj-btn-sm" data-mj-lead-action data-action="update_status" data-modal-title="Update lead status" data-lead-id="<?php echo (int)$lead['id']; ?>" data-status="<?php echo mjv304_e($lead['status']); ?>" data-followup="<?php echo mjv304_e($lead['followup_at'] ?? ''); ?>" data-lead-title="<?php echo mjv304_e($lead['source_title'] ?: 'Untitled item'); ?>">Update</button>
              <button type="button" class="mj-btn mj-btn-sm" data-mj-lead-action data-action="add_note" data-modal-title="Add lead note" data-lead-id="<?php echo (int)$lead['id']; ?>" data-status="<?php echo mjv304_e($lead['status']); ?>" data-lead-title="<?php echo mjv304_e($lead['source_title'] ?: 'Untitled item'); ?>">Note</button>
              <button type="button" class="mj-btn mj-btn-sm" data-mj-lead-action data-action="set_followup" data-modal-title="Set follow-up reminder" data-lead-id="<?php echo (int)$lead['id']; ?>" data-status="<?php echo mjv304_e($lead['status']); ?>" data-followup="<?php echo mjv304_e($lead['followup_at'] ?? ''); ?>" data-lead-title="<?php echo mjv304_e($lead['source_title'] ?: 'Untitled item'); ?>">Follow-up</button>
              <a class="mj-btn mj-btn-sm" href="?lead_id=<?php echo (int)$lead['id']; ?>">View</a>
            </div>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>


  <div class="mj429-modal" id="mj429LeadModal" aria-hidden="true">
    <div class="mj429-modal-card">
      <div class="mj429-modal-head"><div><div class="mj429-modal-title">Lead action</div><div class="mj429-modal-subtitle"></div></div><button class="mj429-modal-close" data-mj-modal-close type="button">×</button></div>
      <form method="post" class="mj429-lead-action-form mj429-modal-body">
        <input type="hidden" name="lead_id" value=""><input type="hidden" name="action" value="update_status"><input type="hidden" name="csrf_token" value="<?php echo mjv304_e(csrf_token()); ?>">
        <div data-mj-action-section="update_status"><label>Status</label><select name="status"><?php foreach(mjv304_status_options() as $k=>$v): ?><option value="<?php echo $k; ?>"><?php echo mjv304_e($v); ?></option><?php endforeach; ?></select><label>Optional note</label><input name="note" placeholder="Add short update note"></div>
        <div data-mj-action-section="add_note" style="display:none"><label>Note</label><textarea name="note" rows="4" placeholder="Type your note"></textarea></div>
        <div data-mj-action-section="set_followup" style="display:none"><label>Follow-up date/time</label><input type="datetime-local" name="followup_at"><label>Reminder note</label><textarea name="note" rows="3" placeholder="Optional reminder note"></textarea></div>
        <div class="mj429-modal-actions"><button type="button" class="mj-btn" data-mj-modal-close>Cancel</button><button type="submit" class="mj-btn mj-btn-primary">Save</button></div>
      </form>
    </div>
  </div>

  <div class="mj-pagination">
    <?php for($p=max(1,$data['page']-2); $p<=min($data['pages'],$data['page']+2); $p++):
      $qs = $_GET; $qs['page']=$p; ?>
      <a class="<?php echo $p===$data['page']?'active':''; ?>" href="?<?php echo http_build_query($qs); ?>"><?php echo $p; ?></a>
    <?php endfor; ?>
    <span><?php echo (int)$data['total']; ?> result(s)</span>
  </div>
</div>
</div>
<?php include __DIR__ . '/includes/footer.php'; ?>
