<?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_admin();
try { mjv3041_ensure_light_schema(); mjv3041_repair_seller_lead_owners(); } catch (Throwable $ignore) {}
$adminId = mjv304_current_user_id();
$message = '';
$error = '';
try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $leadId = (int)($_POST['lead_id'] ?? 0);
        if (isset($_POST['admin_note'])) {
            mjv304_add_lead_note($leadId, $adminId, 'admin', trim((string)($_POST['note'] ?? '')), null);
            $message = 'Admin note saved.';
        }
        if (isset($_POST['update_status'])) {
            mjv304_update_lead_status($leadId, (string)$_POST['status'], $adminId, 'admin', trim((string)($_POST['note'] ?? '')));
            $message = 'Lead status updated.';
        }
    }
} catch (Throwable $e) { $error = $e->getMessage(); }
$filters = [
    'q'=>trim((string)($_GET['q'] ?? '')),
    'status'=>trim((string)($_GET['status'] ?? '')),
    'type'=>trim((string)($_GET['type'] ?? '')),
    'country'=>trim((string)($_GET['country'] ?? '')),
    'seller_user_id'=>(int)($_GET['seller_user_id'] ?? 0),
    'from'=>trim((string)($_GET['from'] ?? '')),
    'to'=>trim((string)($_GET['to'] ?? '')),
    'lead_id'=>(int)($_GET['lead_id'] ?? 0),
    'page'=>(int)($_GET['page'] ?? 1),
    'limit'=>30,
];
$data = mjv304_query_leads($filters, true);
$today = (int)mjv304_fetch_value("SELECT COUNT(*) FROM seller_leads WHERE DATE(created_at)=CURDATE()");
$new = (int)mjv304_fetch_value("SELECT COUNT(*) FROM seller_leads WHERE status='new'");
$follow = (int)mjv304_fetch_value("SELECT COUNT(*) FROM seller_leads WHERE followup_at IS NOT NULL AND followup_at <= NOW() AND status NOT IN ('converted','closed','spam')");
$converted = (int)mjv304_fetch_value("SELECT COUNT(*) FROM seller_leads WHERE status='converted'");
$adminTitle = 'Leads Inbox';
$adminSubtitle = 'Monitor customer enquiries, seller follow-ups, contact requests and CRM activity.';
include __DIR__ . '/_header.php';
?>
<div class="mj-v304-wrap">
  <div class="mj-page-head">
    <div><h1>Admin Leads Overview</h1><p>Monitor customer enquiries created for sellers from deals, listings, and company pages.</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>Today</h3><div class="num"><?php echo $today; ?></div><div class="mj-muted">New enquiries</div></div>
    <div class="mj-card"><h3>New</h3><div class="num"><?php echo $new; ?></div><div class="mj-muted">Waiting seller action</div></div>
    <div class="mj-card"><h3>Follow-up Due</h3><div class="num"><?php echo $follow; ?></div><div class="mj-muted">Due / overdue</div></div>
    <div class="mj-card"><h3>Converted</h3><div class="num"><?php echo $converted; ?></div><div class="mj-muted">Reported won</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="Customer, phone, email, item title..."></div>
    <div><label>Seller ID</label><input name="seller_user_id" value="<?php echo $filters['seller_user_id'] ?: ''; ?>" placeholder="User ID"></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>Country</label><input name="country" value="<?php echo mjv304_e($filters['country']); ?>"></div>
    <div><label>From</label><input type="date" name="from" value="<?php echo mjv304_e($filters['from']); ?>"></div>
    <div><label>&nbsp;</label><button class="mj-btn mj-btn-primary" type="submit">Filter</button></div>
  </form>

  <div class="mj-table-wrap">
    <table class="mj-table mj-leads-clean-table">
      <thead><tr><th>Lead</th><th>Seller</th><th>Customer</th><th>Source</th><th>Status</th><th>Admin Action</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 2", [(int)$lead['id']]); ?>
        <tr data-lead-row="<?php echo (int)$lead['id']; ?>">
          <td data-label="Lead"><b>#<?php echo (int)$lead['id']; ?></b><br><span class="mj-muted"><?php echo mjv304_e(date('d M Y H:i', strtotime($lead['created_at']))); ?></span></td>
          <td data-label="Seller">User ID: <b><?php echo (int)$lead['seller_user_id']; ?></b></td>
          <td data-label="Customer"><b><?php echo mjv304_e($lead['customer_name'] ?: 'Customer'); ?></b><br><?php echo mjv304_e($lead['customer_phone'] ?: '-'); ?><br><span class="mj-muted"><?php echo mjv304_e($lead['customer_email'] ?: '-'); ?></span></td>
          <td data-label="Source"><a href="../<?php echo mjv304_e(mjv304_lead_source_url($lead)); ?>" target="_blank"><?php echo mjv304_e($lead['source_title'] ?: 'Untitled'); ?></a><br><span class="mj-muted"><?php echo mjv304_e(ucfirst($lead['source_type'])); ?> <?php echo $lead['country'] ? '• '.mjv304_e($lead['country']) : ''; ?></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><?php foreach($activities as $a): ?><div class="mj-note-box"><small><?php echo mjv304_e(date('d M H:i', strtotime($a['created_at']))); ?> • <?php echo mjv304_e($a['user_type']); ?></small><br><?php echo nl2br(mjv304_e($a['note'] ?: ($a['old_status'].' → '.$a['new_status']))); ?></div><?php endforeach; ?></td>
          <td data-label="Admin Action">
            <div class="mj-lead-actions-clean">
              <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'); ?>">Update</button>
              <button type="button" class="mj-btn mj-btn-sm" data-mj-lead-action data-action="add_note" data-modal-title="Add admin 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'); ?>">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'); ?>">Follow-up</button>
              <a class="mj-btn mj-btn-sm" href="leads.php?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>Admin note / reason</label><textarea name="note" rows="3" placeholder="Optional admin note"></textarea></div>
        <div data-mj-action-section="add_note" style="display:none"><label>Admin note</label><textarea name="note" rows="4" placeholder="Type admin 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>
<?php include __DIR__ . '/_footer.php'; ?>
