<?php
/* ============================================================================
   WBMCZ — Admin · Lead Management

     Potential Leads   people who registered but never subscribed and never
                       ordered — read live from `users`, always current
     Active Leads      the ones somebody is working on right now
     All Leads         everything in the `leads` table
     Closed            converted + not interested

   From any row you can open the full details, hand it to a staff member,
   change the status, set the next follow-up date and read the whole history.
   A staff account with `manage_leads` sees the leads handed to them; the
   owner account sees everybody's.
   ============================================================================ */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/Language.php';
require_once __DIR__ . '/../includes/admin_list.php';
require_once __DIR__ . '/../includes/rbac.php';
require_once __DIR__ . '/../includes/leads.php';
require_once __DIR__ . '/../includes/notify.php';

if (!isLoggedIn() || !isAdmin()) { redirect('login.php'); }
rbac_guard('manage_leads');

$lang         = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$user_id      = (int)$_SESSION['user_id'];

/* sidebar permission flags */
$can_users        = hasPermission('manage_users');
$can_sellers      = hasPermission('manage_sellers');
$can_staff        = hasPermission('manage_staff_roles');
$can_services     = hasPermission('manage_services');
$can_orders       = hasPermission('manage_orders');
$can_transactions = hasPermission('manage_transactions');
$can_tickets      = hasPermission('manage_tickets');
$can_settings     = hasPermission('manage_settings');

leads_ensure_schema($db);

$me_row = $db->select("SELECT id, name FROM users WHERE id = ?", [$user_id]);
$me     = !empty($me_row) ? $me_row[0] : ['id' => $user_id, 'name' => 'Admin'];

/* The owner sees everything; a staff account sees what was handed to them. */
$LD_SUPER = rbac_is_super();

if (isset($_SESSION['flash_success'])) { $success_msg = $_SESSION['flash_success']; unset($_SESSION['flash_success']); }
if (isset($_SESSION['flash_error']))   { $error_msg   = $_SESSION['flash_error'];   unset($_SESSION['flash_error']); }

$LD_SELF = 'leads.php' . ((isset($_GET['tab']) && $_GET['tab'] !== '') ? '?tab=' . urlencode($_GET['tab']) : '');

/* ============================================================
   AJAX — lead details + history
   ============================================================ */
if (isset($_GET['ajax'])) {
    header('Content-Type: application/json');
    $lid = (int)($_GET['id'] ?? 0);

    if ($_GET['ajax'] === 'lead') {
        $row = $db->select("SELECT * FROM leads WHERE id = ?", [$lid]);
        $out = !empty($row) ? $row[0] : null;
        if ($out && !empty($out['user_id'])) {
            try {
                $u = $db->select("SELECT id, name, mobile, email, state, district, pincode, village, post_office,
                                         block_city, landmark, created_at, is_subscribed, wallet_balance, referred_by
                                  FROM users WHERE id = ?", [(int)$out['user_id']]);
                $out['account'] = !empty($u) ? $u[0] : null;
                $o = $db->select("SELECT COUNT(*) c, COALESCE(SUM(amount),0) s FROM orders WHERE user_id = ?", [(int)$out['user_id']]);
                $out['orders'] = !empty($o) ? $o[0] : ['c' => 0, 's' => 0];
            } catch (\Throwable $e) {}
        }
        echo json_encode($out);
        exit;
    }

    if ($_GET['ajax'] === 'history') {
        echo json_encode(lead_activities($db, $lid));
        exit;
    }

    if ($_GET['ajax'] === 'user') {          // full details of a potential lead
        $uid = (int)($_GET['id'] ?? 0);
        $u   = $db->select("SELECT * FROM users WHERE id = ?", [$uid]);
        $out = !empty($u) ? $u[0] : null;
        if ($out) {
            unset($out['password']);
            try {
                $l = $db->select("SELECT * FROM leads WHERE user_id = ? ORDER BY id DESC LIMIT 1", [$uid]);
                $out['lead'] = !empty($l) ? $l[0] : null;
                $r = $db->select("SELECT name FROM users WHERE id = ?", [(int)($out['referred_by'] ?? 0)]);
                $out['referrer'] = !empty($r) ? $r[0]['name'] : '';
            } catch (\Throwable $e) {}
        }
        echo json_encode($out);
        exit;
    }
    echo json_encode([]);
    exit;
}

/* ============================================================
   POST actions
   ============================================================ */

/* ---- create a lead by hand ---- */
if (isset($_POST['add_lead'])) {
    $name   = sanitize($_POST['name'] ?? '');
    $mobile = preg_replace('/[^0-9]/', '', (string)($_POST['mobile'] ?? ''));

    if ($name === '' || strlen($mobile) < 10) {
        $_SESSION['flash_error'] = 'A lead needs a name and a valid 10-digit mobile number.';
        redirect($LD_SELF);
    }

    /* already on the website? link the account so the history stays together */
    $linked = null;
    try {
        $u = $db->select("SELECT id FROM users WHERE mobile = ? AND deleted_at IS NULL LIMIT 1", [$mobile]);
        if (!empty($u)) $linked = (int)$u[0]['id'];
    } catch (\Throwable $e) {}

    $assign_to   = (int)($_POST['assigned_to'] ?? 0);
    $assign_name = '';
    if ($assign_to > 0) {
        $a = $db->select("SELECT name FROM users WHERE id = ?", [$assign_to]);
        $assign_name = !empty($a) ? $a[0]['name'] : '';
    }

    $follow = trim((string)($_POST['next_follow_up'] ?? ''));
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $follow)) { $follow = null; }

    $lid = $db->insert(
        "INSERT INTO leads (user_id, name, mobile, alt_mobile, email, source, lead_type, interest,
                            state, district, pincode, address, status, priority,
                            assigned_to, assigned_name, assigned_at, next_follow_up, notes,
                            created_by, created_by_name)
         VALUES (?,?,?,?,?,?,'active',?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
        [
            $linked, $name, $mobile,
            preg_replace('/[^0-9]/', '', (string)($_POST['alt_mobile'] ?? '')),
            sanitize($_POST['email'] ?? ''),
            sanitize($_POST['source'] ?? 'manual'),
            sanitize($_POST['interest'] ?? ''),
            sanitize($_POST['state'] ?? ''), sanitize($_POST['district'] ?? ''),
            sanitize($_POST['pincode'] ?? ''), sanitize($_POST['address'] ?? ''),
            sanitize($_POST['status'] ?? 'new'), sanitize($_POST['priority'] ?? 'medium'),
            $assign_to > 0 ? $assign_to : null, $assign_name !== '' ? $assign_name : null,
            $assign_to > 0 ? date('Y-m-d H:i:s') : null,
            $follow, sanitize($_POST['notes'] ?? ''),
            $me['id'], $me['name'],
        ]
    );

    if ($lid) {
        lead_log($db, $lid, 'created', 'Lead entered by ' . $me['name'], '', '', $me, $follow);
        if ($assign_to > 0) {
            lead_log($db, $lid, 'assign', 'Handed to ' . $assign_name, '', $assign_name, $me);
            if (function_exists('notify_send')) {
                try { notify_send($db, $assign_to, 'New lead assigned to you', $name . ' (' . $mobile . ') has been assigned to you.', 'general', 'leads.php'); }
                catch (\Throwable $e) {}
            }
        }
        $_SESSION['flash_success'] = 'Lead "' . $name . '" added.';
    } else {
        $_SESSION['flash_error'] = 'The lead could not be saved.';
    }
    redirect($LD_SELF);
}

/* ---- edit the details of an existing lead ---- */
if (isset($_POST['edit_lead'])) {
    $lid = (int)($_POST['lead_id'] ?? 0);
    $old = $db->select("SELECT * FROM leads WHERE id = ?", [$lid]);
    if (empty($old)) { $_SESSION['flash_error'] = 'Lead not found.'; redirect($LD_SELF); }

    $follow = trim((string)($_POST['next_follow_up'] ?? ''));
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $follow)) { $follow = null; }

    $db->insert(
        "UPDATE leads SET name = ?, mobile = ?, alt_mobile = ?, email = ?, source = ?, interest = ?,
                          state = ?, district = ?, pincode = ?, address = ?, priority = ?,
                          next_follow_up = ?, notes = ?, updated_at = NOW()
         WHERE id = ?",
        [
            sanitize($_POST['name'] ?? ''), preg_replace('/[^0-9]/', '', (string)($_POST['mobile'] ?? '')),
            preg_replace('/[^0-9]/', '', (string)($_POST['alt_mobile'] ?? '')),
            sanitize($_POST['email'] ?? ''), sanitize($_POST['source'] ?? 'manual'),
            sanitize($_POST['interest'] ?? ''), sanitize($_POST['state'] ?? ''),
            sanitize($_POST['district'] ?? ''), sanitize($_POST['pincode'] ?? ''),
            sanitize($_POST['address'] ?? ''), sanitize($_POST['priority'] ?? 'medium'),
            $follow, sanitize($_POST['notes'] ?? ''), $lid,
        ]
    );
    lead_log($db, $lid, 'edit', 'Details updated', '', '', $me, $follow);
    $_SESSION['flash_success'] = 'Lead updated.';
    redirect($LD_SELF);
}

/* ---- hand a lead to a staff member (works on a potential member too) ---- */
if (isset($_POST['assign_lead'])) {
    $lid = (int)($_POST['lead_id'] ?? 0);
    $uid = (int)($_POST['from_user'] ?? 0);
    if ($lid <= 0 && $uid > 0) { $lid = lead_from_user($db, $uid, $me); }
    if ($lid <= 0) { $_SESSION['flash_error'] = 'Lead not found.'; redirect($LD_SELF); }

    $to = (int)($_POST['assigned_to'] ?? 0);
    $old = $db->select("SELECT assigned_name FROM leads WHERE id = ?", [$lid]);
    $old_name = !empty($old) ? (string)$old[0]['assigned_name'] : '';

    if ($to > 0) {
        $a = $db->select("SELECT name FROM users WHERE id = ?", [$to]);
        $nm = !empty($a) ? $a[0]['name'] : '';
        $db->insert("UPDATE leads SET assigned_to = ?, assigned_name = ?, assigned_at = NOW(), updated_at = NOW() WHERE id = ?",
                    [$to, $nm, $lid]);
        lead_log($db, $lid, 'assign', sanitize($_POST['remark'] ?? ''), $old_name, $nm, $me);
        if (function_exists('notify_send')) {
            try { notify_send($db, $to, 'New lead assigned to you', 'A lead has been assigned to you — open Lead Management to follow it up.', 'general', 'leads.php'); }
            catch (\Throwable $e) {}
        }
        $_SESSION['flash_success'] = 'Lead handed to ' . $nm . '.';
    } else {
        $db->insert("UPDATE leads SET assigned_to = NULL, assigned_name = NULL, assigned_at = NULL, updated_at = NOW() WHERE id = ?", [$lid]);
        lead_log($db, $lid, 'assign', 'Taken back to the unassigned pool', $old_name, '', $me);
        $_SESSION['flash_success'] = 'Lead moved back to the unassigned pool.';
    }
    redirect($LD_SELF);
}

/* ---- follow-up: status + remark + next date, all in one ---- */
if (isset($_POST['follow_lead'])) {
    $lid = (int)($_POST['lead_id'] ?? 0);
    $uid = (int)($_POST['from_user'] ?? 0);
    if ($lid <= 0 && $uid > 0) { $lid = lead_from_user($db, $uid, $me); }
    if ($lid <= 0) { $_SESSION['flash_error'] = 'Lead not found.'; redirect($LD_SELF); }

    $row = $db->select("SELECT status FROM leads WHERE id = ?", [$lid]);
    $old_status = !empty($row) ? (string)$row[0]['status'] : 'new';

    $status = sanitize($_POST['status'] ?? $old_status);
    if (!array_key_exists($status, lead_statuses())) { $status = $old_status; }

    $follow = trim((string)($_POST['next_follow_up'] ?? ''));
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $follow)) { $follow = null; }

    $remark = sanitize($_POST['remark'] ?? '');

    $db->insert("UPDATE leads SET status = ?, next_follow_up = ?, last_contacted_at = NOW(),
                        converted_at = IF(? = 'converted', NOW(), converted_at), updated_at = NOW()
                 WHERE id = ?", [$status, $follow, $status, $lid]);

    lead_log($db, $lid, ($status !== $old_status ? 'status' : 'note'), $remark,
             lead_status_label($old_status), lead_status_label($status), $me, $follow);

    $_SESSION['flash_success'] = 'Follow-up saved — status is now ' . lead_status_label($status) . '.';
    redirect($LD_SELF);
}

/* ---- delete ---- */
if (isset($_POST['delete_lead'])) {
    $lid = (int)$_POST['lead_id'];
    $db->insert("DELETE FROM lead_activities WHERE lead_id = ?", [$lid]);
    $db->insert("DELETE FROM leads WHERE id = ?", [$lid]);
    $_SESSION['flash_success'] = 'Lead deleted.';
    redirect($LD_SELF);
}

/* ---- bulk assign from the potential list ---- */
if (isset($_POST['bulk_assign'])) {
    $ids = array_filter(array_map('intval', explode(',', (string)($_POST['bulk_ids'] ?? ''))));
    $to  = (int)($_POST['assigned_to'] ?? 0);
    $nm  = '';
    if ($to > 0) { $a = $db->select("SELECT name FROM users WHERE id = ?", [$to]); $nm = !empty($a) ? $a[0]['name'] : ''; }

    $n = 0;
    foreach ($ids as $uid) {
        $lid = lead_from_user($db, $uid, $me);
        if ($lid <= 0) continue;
        if ($to > 0) {
            $db->insert("UPDATE leads SET assigned_to = ?, assigned_name = ?, assigned_at = NOW(), updated_at = NOW() WHERE id = ?", [$to, $nm, $lid]);
            lead_log($db, $lid, 'assign', 'Bulk assignment', '', $nm, $me);
        }
        $n++;
    }
    $_SESSION['flash_success'] = $n . ' lead(s) picked up' . ($nm !== '' ? ' and handed to ' . $nm : '') . '.';
    redirect($LD_SELF);
}

/* ============================================================
   Filters + data
   ============================================================ */
$TAB = $_GET['tab'] ?? 'potential';
if (!in_array($TAB, ['potential', 'active', 'all', 'closed'], true)) { $TAB = 'potential'; }

$LD_DEFAULTS = ['q' => '', 'status' => '', 'owner' => '', 'source' => '', 'due' => '', 'from' => '', 'to' => ''];
$LD = alist_filters('leads_' . $TAB, $LD_DEFAULTS);

$staff = lead_staff_list($db);
$stats = lead_stats($db, $LD_SUPER ? 0 : $user_id);

$PER  = 60;
$page = max(1, (int)($_GET['p'] ?? 1));
$off  = ($page - 1) * $PER;

$rows = []; $total_rows = 0; $potential = [];

if ($TAB === 'potential') {
    $extra = ''; $params = [];
    if ($LD['q'] !== '') {
        $extra .= " AND (u.name LIKE ? OR u.mobile LIKE ? OR u.email LIKE ?)";
        $l = '%' . $LD['q'] . '%'; $params[] = $l; $params[] = $l; $params[] = $l;
    }
    if ($LD['owner'] === 'none')      { $extra .= " AND (l.assigned_to IS NULL OR l.id IS NULL)"; }
    elseif ($LD['owner'] === 'me')    { $extra .= " AND l.assigned_to = ?"; $params[] = $user_id; }
    elseif ($LD['owner'] !== '')      { $extra .= " AND l.assigned_to = ?"; $params[] = (int)$LD['owner']; }
    if (!$LD_SUPER)                   { $extra .= " AND (l.assigned_to = ? OR l.assigned_to IS NULL OR l.id IS NULL)"; $params[] = $user_id; }
    if ($LD['from'] !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $LD['from'])) { $extra .= " AND DATE(u.created_at) >= ?"; $params[] = $LD['from']; }
    if ($LD['to']   !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $LD['to']))   { $extra .= " AND DATE(u.created_at) <= ?"; $params[] = $LD['to']; }

    $total_rows = lead_potential_count($db, $extra, $params);
    $potential  = lead_potential_rows($db, $extra, $params, $PER, $off);
} else {
    $w = "1"; $params = [];
    if ($TAB === 'active') { $w .= " AND status IN ('new','contacted','interested','follow_up')"; }
    if ($TAB === 'closed') { $w .= " AND status IN ('converted','lost')"; }
    if ($LD['q'] !== '') {
        $w .= " AND (name LIKE ? OR mobile LIKE ? OR email LIKE ? OR interest LIKE ?)";
        $l = '%' . $LD['q'] . '%'; $params[] = $l; $params[] = $l; $params[] = $l; $params[] = $l;
    }
    if ($LD['status'] !== '') { $w .= " AND status = ?"; $params[] = $LD['status']; }
    if ($LD['source'] !== '') { $w .= " AND source = ?"; $params[] = $LD['source']; }
    if ($LD['owner'] === 'none')   { $w .= " AND assigned_to IS NULL"; }
    elseif ($LD['owner'] === 'me') { $w .= " AND assigned_to = ?"; $params[] = $user_id; }
    elseif ($LD['owner'] !== '')   { $w .= " AND assigned_to = ?"; $params[] = (int)$LD['owner']; }
    if ($LD['due'] === 'today')    { $w .= " AND next_follow_up = CURDATE()"; }
    elseif ($LD['due'] === 'over') { $w .= " AND next_follow_up < CURDATE()"; }
    elseif ($LD['due'] === 'week') { $w .= " AND next_follow_up BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 7 DAY)"; }
    if ($LD['from'] !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $LD['from'])) { $w .= " AND DATE(created_at) >= ?"; $params[] = $LD['from']; }
    if ($LD['to']   !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $LD['to']))   { $w .= " AND DATE(created_at) <= ?"; $params[] = $LD['to']; }
    if (!$LD_SUPER) { $w .= " AND (assigned_to = ? OR assigned_to IS NULL)"; $params[] = $user_id; }

    try {
        $c = $db->select("SELECT COUNT(*) c FROM leads WHERE $w", $params);
        $total_rows = !empty($c) ? (int)$c[0]['c'] : 0;
        $rows = $db->select("SELECT * FROM leads WHERE $w
                             ORDER BY (next_follow_up IS NOT NULL AND next_follow_up <= CURDATE()) DESC,
                                      id DESC LIMIT $PER OFFSET $off", $params);
    } catch (\Throwable $e) {}
}

/* ---- CSV export ---- */
if (isset($_GET['export'])) {
    if ($TAB === 'potential') {
        $ex = lead_potential_rows($db, $extra ?? '', $params ?? [], 10000, 0);
        alist_export_csv('potential_leads', [
            'User ID' => 'id', 'Name' => 'name', 'Mobile' => 'mobile', 'Email' => 'email',
            'State' => 'state', 'District' => 'district', 'Pincode' => 'pincode',
            'Registered' => 'created_at',
            'Status' => function ($r) { return $r['lead_status'] ? lead_status_label($r['lead_status']) : 'Not picked up'; },
            'Assigned to' => 'assigned_name',
        ], $ex);
    } else {
        try { $ex = $db->select("SELECT * FROM leads WHERE $w ORDER BY id DESC LIMIT 10000", $params); }
        catch (\Throwable $e) { $ex = []; }
        alist_export_csv('leads', [
            'ID' => 'id', 'Name' => 'name', 'Mobile' => 'mobile', 'Email' => 'email',
            'Source' => function ($r) { return lead_source_label($r['source']); },
            'Interest' => 'interest',
            'Status' => function ($r) { return lead_status_label($r['status']); },
            'Priority' => 'priority', 'Assigned to' => 'assigned_name',
            'Next follow-up' => 'next_follow_up', 'State' => 'state', 'District' => 'district',
            'Pincode' => 'pincode', 'Added by' => 'created_by_name', 'Created' => 'created_at',
        ], $ex);
    }
}

$pages = max(1, (int)ceil($total_rows / $PER));
$company_logo = getSetting('company_logo', '../assets/images/logo.png');

/* helper for the tab links, keeps the filters out of the way */
function ld_tab_url($t) { return 'leads.php?tab=' . $t; }
$page_ids = [];
foreach ($potential as $p) { $page_ids[] = (int)$p['id']; }
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lead Management - Admin Panel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=Hind+Siliguri:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body { font-family:'Inter','Hind Siliguri',sans-serif; }
        .lbl { display:block; font-size:10px; font-weight:800; color:#64748b; margin-bottom:.25rem; text-transform:uppercase; letter-spacing:.05em; }
        .fld { width:100%; padding:.55rem .7rem; background:#fff; border:1.5px solid #cbd5e1; border-radius:.7rem; font-size:.8rem; outline:none; color:#0f172a; }
        .fld:focus { border-color:#6366f1; box-shadow:0 0 0 3px rgba(99,102,241,.14); }
        .ld-tab { display:inline-flex; align-items:center; gap:.4rem; padding:.6rem 1rem; border-radius:.8rem;
                  font-size:12px; font-weight:800; color:#64748b; background:#fff; border:1px solid #e2e8f0; }
        .ld-tab.on { background:#0f172a; color:#fff; border-color:#0f172a; }
        .ld-tab .n { font-size:10px; padding:.05rem .4rem; border-radius:999px; background:rgba(100,116,139,.15); }
        .ld-tab.on .n { background:rgba(255,255,255,.2); }
        table.ld { width:100%; border-collapse:collapse; font-size:12px; }
        table.ld th { background:#f8fafc; text-align:left; padding:.6rem .7rem; font-size:9.5px; font-weight:900;
                      text-transform:uppercase; letter-spacing:.06em; color:#94a3b8; border-bottom:1px solid #e2e8f0; }
        table.ld td { padding:.6rem .7rem; border-bottom:1px solid #f1f5f9; color:#334155; vertical-align:top; }
        table.ld tr:hover td { background:#fafbff; }
        .pill { display:inline-flex; align-items:center; gap:.25rem; padding:.15rem .55rem; border-radius:999px;
                font-size:9.5px; font-weight:900; text-transform:uppercase; letter-spacing:.04em; }
        .cbtn { display:inline-flex; align-items:center; justify-content:center; gap:.3rem; padding:.35rem .6rem;
                border-radius:.55rem; font-size:10.5px; font-weight:800; color:#fff; border:0; cursor:pointer; white-space:nowrap; }
        .due  { color:#e11d48; font-weight:900; }
        .tl   { position:relative; padding-left:1.6rem; }
        .tl::before { content:''; position:absolute; left:.45rem; top:.35rem; bottom:.35rem; width:2px; background:#e2e8f0; }
        .tl-i { position:relative; padding-bottom:.9rem; }
        .tl-i::before { content:''; position:absolute; left:-1.32rem; top:.3rem; width:.65rem; height:.65rem;
                        border-radius:50%; background:#6366f1; border:2px solid #fff; box-shadow:0 0 0 2px #e0e7ff; }
    </style>
</head>
<body class="bg-gray-50" x-data="leadApp()">
<div class="flex h-screen overflow-hidden">

    <?php include __DIR__ . '/includes/sidebar.php'; ?>

    <div class="flex-1 flex flex-col min-w-0 bg-gray-100 overflow-hidden">
        <header class="h-20 bg-white text-slate-800 flex items-center justify-between px-4 lg:px-8 shadow-sm border-b border-gray-200 z-40 relative">
            <div class="flex items-center">
                <button @click="sidebarOpen = !sidebarOpen" class="p-2 mr-3 text-slate-500 hover:text-emerald-600 rounded-lg"><i class="fas fa-bars text-xl"></i></button>
                <h2 class="text-xl font-bold hidden md:block text-slate-800">Lead Management</h2>
            </div>
            <button type="button" @click="openAdd()" class="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-gradient-to-r from-indigo-600 to-blue-600 text-white text-sm font-bold shadow">
                <i class="fas fa-user-plus"></i> Add Lead
            </button>
        </header>

        <main class="flex-1 overflow-y-auto p-4 md:p-6">
            <?php echo alist_styles(); ?>

            <?php if (isset($success_msg)): ?>
            <div class="mb-4 bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-xl flex items-center shadow-sm">
                <i class="fas fa-check-circle mr-2"></i><span class="font-medium"><?php echo htmlspecialchars($success_msg); ?></span>
            </div>
            <?php endif; ?>
            <?php if (isset($error_msg)): ?>
            <div class="mb-4 bg-rose-50 border border-rose-200 text-rose-700 px-4 py-3 rounded-xl flex items-center shadow-sm">
                <i class="fas fa-triangle-exclamation mr-2"></i><span class="font-medium"><?php echo htmlspecialchars($error_msg); ?></span>
            </div>
            <?php endif; ?>

            <div class="mb-5">
                <h2 class="text-2xl font-bold text-slate-800 mb-1">Leads &amp; Follow-up</h2>
                <p class="text-gray-500 text-sm">
                    <?php if ($LD_SUPER): ?>
                        Everyone's leads. Pick up a potential member, hand it to a staff account, and track every call from here.
                    <?php else: ?>
                        The leads handed to you, plus anything still unassigned that you can pick up.
                    <?php endif; ?>
                </p>
            </div>

            <?php echo alist_stats([
                ['label' => 'Potential members', 'value' => number_format(lead_potential_count($db)), 'sub' => 'registered, never bought', 'colour' => 'indigo', 'icon' => 'fa-user-clock'],
                ['label' => 'Open leads',        'value' => number_format($stats['open']),  'sub' => $stats['unassigned'] . ' unassigned', 'colour' => 'blue',    'icon' => 'fa-fire'],
                ['label' => 'Follow-up due',     'value' => number_format($stats['due']),   'sub' => 'today or overdue',                   'colour' => 'amber',   'icon' => 'fa-bell'],
                ['label' => 'Converted',         'value' => number_format($stats['converted']), 'sub' => 'became customers',               'colour' => 'emerald', 'icon' => 'fa-circle-check'],
                ['label' => 'Not interested',    'value' => number_format($stats['lost']),  'sub' => 'closed',                             'colour' => 'rose',    'icon' => 'fa-circle-xmark'],
                ['label' => 'Added today',       'value' => number_format($stats['today']), 'sub' => 'new lead entries',                   'colour' => 'violet',  'icon' => 'fa-calendar-day'],
            ]); ?>

            <!-- tabs -->
            <div class="flex flex-wrap gap-2 mb-4">
                <a href="<?php echo ld_tab_url('potential'); ?>" class="ld-tab <?php echo $TAB === 'potential' ? 'on' : ''; ?>">
                    <i class="fas fa-user-clock"></i> Potential Leads
                </a>
                <a href="<?php echo ld_tab_url('active'); ?>" class="ld-tab <?php echo $TAB === 'active' ? 'on' : ''; ?>">
                    <i class="fas fa-fire"></i> Active Leads <span class="n"><?php echo $stats['open']; ?></span>
                </a>
                <a href="<?php echo ld_tab_url('all'); ?>" class="ld-tab <?php echo $TAB === 'all' ? 'on' : ''; ?>">
                    <i class="fas fa-list"></i> All Leads <span class="n"><?php echo $stats['total']; ?></span>
                </a>
                <a href="<?php echo ld_tab_url('closed'); ?>" class="ld-tab <?php echo $TAB === 'closed' ? 'on' : ''; ?>">
                    <i class="fas fa-flag-checkered"></i> Closed <span class="n"><?php echo $stats['converted'] + $stats['lost']; ?></span>
                </a>
            </div>

            <?php echo alist_banner('leads.php?tab=' . $TAB, 'leads_' . $TAB, $LD, $LD_DEFAULTS, [
                'q' => 'Search', 'status' => 'Status', 'owner' => 'Owner', 'source' => 'Source',
                'due' => 'Follow-up', 'from' => 'From', 'to' => 'To']); ?>

            <!-- filters -->
            <form method="GET" class="al-panel p-3 mb-5">
                <input type="hidden" name="f" value="leads_<?php echo $TAB; ?>">
                <input type="hidden" name="tab" value="<?php echo $TAB; ?>">
                <div class="grid grid-cols-2 lg:grid-cols-4 xl:grid-cols-6 gap-2 items-end">
                    <div class="col-span-2">
                        <label class="al-l">Search</label>
                        <div class="relative">
                            <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
                            <input name="q" value="<?php echo htmlspecialchars($LD['q']); ?>" placeholder="Name, mobile or email" class="al-f pl-9">
                        </div>
                    </div>

                    <?php if ($TAB !== 'potential'): ?>
                    <div><label class="al-l">Status</label>
                        <select name="status" class="al-f">
                            <option value="">Any</option>
                            <?php foreach (lead_statuses() as $k => $v): ?>
                                <option value="<?php echo $k; ?>" <?php echo $LD['status'] === $k ? 'selected' : ''; ?>><?php echo $v[0]; ?></option>
                            <?php endforeach; ?>
                        </select></div>
                    <div><label class="al-l">Source</label>
                        <select name="source" class="al-f">
                            <option value="">Any</option>
                            <?php foreach (lead_sources() as $k => $v): ?>
                                <option value="<?php echo $k; ?>" <?php echo $LD['source'] === $k ? 'selected' : ''; ?>><?php echo $v; ?></option>
                            <?php endforeach; ?>
                        </select></div>
                    <div><label class="al-l">Follow-up</label>
                        <select name="due" class="al-f">
                            <option value="">Any</option>
                            <option value="today" <?php echo $LD['due'] === 'today' ? 'selected' : ''; ?>>Due today</option>
                            <option value="over"  <?php echo $LD['due'] === 'over'  ? 'selected' : ''; ?>>Overdue</option>
                            <option value="week"  <?php echo $LD['due'] === 'week'  ? 'selected' : ''; ?>>Next 7 days</option>
                        </select></div>
                    <?php endif; ?>

                    <div><label class="al-l">Owner</label>
                        <select name="owner" class="al-f">
                            <option value="">Anyone</option>
                            <option value="me"   <?php echo $LD['owner'] === 'me'   ? 'selected' : ''; ?>>Assigned to me</option>
                            <option value="none" <?php echo $LD['owner'] === 'none' ? 'selected' : ''; ?>>Not assigned</option>
                            <?php foreach ($staff as $st): ?>
                                <option value="<?php echo (int)$st['id']; ?>" <?php echo $LD['owner'] === (string)$st['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($st['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select></div>

                    <div class="col-span-2"><label class="al-l">Added between</label>
                        <div class="flex gap-2">
                            <input type="date" name="from" value="<?php echo htmlspecialchars($LD['from']); ?>" class="al-f">
                            <input type="date" name="to"   value="<?php echo htmlspecialchars($LD['to']); ?>"   class="al-f">
                        </div>
                    </div>

                    <div class="flex gap-2">
                        <button class="al-btn al-btn-apply flex-1"><i class="fas fa-filter"></i> Apply</button>
                        <a href="leads.php?tab=<?php echo $TAB; ?>&reset=1" class="al-btn al-btn-ghost">Reset</a>
                    </div>
                    <div>
                        <a href="<?php echo alist_url('leads.php', 'leads_' . $TAB, $LD, ['tab' => $TAB, 'export' => 1]); ?>" class="al-btn al-btn-csv w-full"><i class="fas fa-file-csv"></i> Export CSV</a>
                    </div>
                </div>
                <p class="text-[11px] text-slate-400 mt-2">
                    Showing <b class="text-slate-600"><?php echo number_format($total_rows); ?></b> record(s) ·
                    page <b class="text-slate-600"><?php echo $page; ?></b> of <?php echo $pages; ?>.
                </p>
            </form>

            <?php if ($TAB === 'potential'): ?>
            <!-- ==================== POTENTIAL LEADS ==================== -->
            <div class="mb-3 flex flex-wrap items-center gap-3 bg-indigo-50 border border-indigo-100 text-indigo-800 px-4 py-3 rounded-xl text-[12px]">
                <i class="fas fa-circle-info"></i>
                <span>Everybody here <b>registered on the website but has never subscribed and never placed an order</b>.
                      Pick one up to start following it — the moment you assign it or save a follow-up it becomes an active lead.</span>
            </div>

            <div class="ul-bulkbar bg-slate-900 text-white rounded-xl px-4 py-3 mb-3 flex flex-wrap items-center gap-3"
                 x-show="sel.length > 0" style="display:none;">
                <span class="text-xs font-bold"><span x-text="sel.length"></span> selected</span>
                <form method="POST" class="flex flex-wrap items-center gap-2">
                    <input type="hidden" name="bulk_ids" :value="sel.join(',')">
                    <select name="assigned_to" class="fld !py-1.5 !text-xs text-slate-800" style="width:auto">
                        <option value="0">Pick up without assigning</option>
                        <?php foreach ($staff as $st): ?>
                            <option value="<?php echo (int)$st['id']; ?>"><?php echo htmlspecialchars($st['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <button type="submit" name="bulk_assign" value="1" class="cbtn bg-emerald-600 hover:bg-emerald-700"><i class="fas fa-user-check"></i> Assign</button>
                </form>
                <button type="button" @click="sel = []" class="text-xs font-bold text-white/70 hover:text-white ml-auto">Clear</button>
            </div>

            <div class="bg-white rounded-2xl border border-slate-200 overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="ld">
                        <thead>
                            <tr>
                                <th class="w-9"><input type="checkbox" :checked="allOnPage()" @change="toggleAll($event.target.checked)"></th>
                                <th>Member</th><th>Contact</th><th>Location</th><th>Registered</th>
                                <th>Referred / Added by</th><th>Lead status</th><th>Owner</th><th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if (empty($potential)): ?>
                            <tr><td colspan="9" class="text-center py-10 text-slate-400">Nothing here — every registered member has already bought something.</td></tr>
                        <?php else: foreach ($potential as $p): ?>
                            <tr>
                                <td><input type="checkbox" :checked="isSel(<?php echo (int)$p['id']; ?>)" @change="toggleOne(<?php echo (int)$p['id']; ?>)"></td>
                                <td>
                                    <p class="font-extrabold text-slate-800"><?php echo esc($p['name']); ?></p>
                                    <p class="text-[10.5px] text-slate-400">WBMCZ<?php echo str_pad((string)$p['id'], 4, '0', STR_PAD_LEFT); ?> · ID <?php echo (int)$p['id']; ?></p>
                                </td>
                                <td>
                                    <p class="font-semibold"><?php echo esc($p['mobile']); ?></p>
                                    <p class="text-[10.5px] text-slate-400"><?php echo esc($p['email'] ?: '—'); ?></p>
                                    <div class="flex gap-1 mt-1">
                                        <a href="tel:<?php echo esc($p['mobile']); ?>" class="cbtn bg-slate-500 hover:bg-slate-600"><i class="fas fa-phone"></i></a>
                                        <a href="https://wa.me/91<?php echo preg_replace('/\D/', '', (string)$p['mobile']); ?>" target="_blank" class="cbtn bg-emerald-600 hover:bg-emerald-700"><i class="fab fa-whatsapp"></i></a>
                                    </div>
                                </td>
                                <td class="text-[11px]">
                                    <?php echo esc($p['district'] ?: '—'); ?><br>
                                    <span class="text-slate-400"><?php echo esc($p['state'] ?: ''); ?> <?php echo esc($p['pincode'] ?: ''); ?></span>
                                </td>
                                <td class="text-[11px] text-slate-500">
                                    <?php echo !empty($p['created_at']) ? date('d M Y', strtotime($p['created_at'])) : '—'; ?><br>
                                    <span class="text-slate-400"><?php echo !empty($p['created_at']) ? date('h:i A', strtotime($p['created_at'])) : ''; ?></span>
                                </td>
                                <td class="text-[11px]">
                                    <?php if (!empty($p['created_by_name'])): ?>
                                        <?php echo esc($p['created_by_name']); ?>
                                    <?php elseif (!empty($p['referred_by'])): ?>
                                        WBMCZ<?php echo str_pad((string)$p['referred_by'], 4, '0', STR_PAD_LEFT); ?>
                                    <?php else: ?><span class="text-slate-300">Self</span><?php endif; ?>
                                </td>
                                <td>
                                    <?php if (!empty($p['lead_status'])): ?>
                                        <span class="pill <?php echo lead_status_class($p['lead_status']); ?>">
                                            <i class="fas <?php echo lead_status_icon($p['lead_status']); ?>"></i><?php echo lead_status_label($p['lead_status']); ?>
                                        </span>
                                        <?php if (!empty($p['next_follow_up'])): ?>
                                            <p class="text-[10px] mt-1 <?php echo $p['next_follow_up'] <= date('Y-m-d') ? 'due' : 'text-slate-400'; ?>">
                                                <i class="fas fa-bell"></i> <?php echo date('d M', strtotime($p['next_follow_up'])); ?>
                                            </p>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <span class="pill bg-slate-100 text-slate-500">Not picked up</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-[11px]"><?php echo esc($p['assigned_name'] ?: '—'); ?></td>
                                <td>
                                    <div class="flex flex-wrap gap-1">
                                        <button type="button" class="cbtn bg-indigo-600 hover:bg-indigo-700"
                                                @click="openUser(<?php echo (int)$p['id']; ?>)"><i class="fas fa-eye"></i> Details</button>
                                        <button type="button" class="cbtn bg-amber-500 hover:bg-amber-600"
                                                @click="openFollow(<?php echo (int)($p['lead_id'] ?? 0); ?>, <?php echo (int)$p['id']; ?>, '<?php echo esc(addslashes($p['name'])); ?>', '<?php echo esc($p['lead_status'] ?: 'new'); ?>')">
                                            <i class="fas fa-clock"></i> Follow up</button>
                                        <button type="button" class="cbtn bg-emerald-600 hover:bg-emerald-700"
                                                @click="openAssign(<?php echo (int)($p['lead_id'] ?? 0); ?>, <?php echo (int)$p['id']; ?>, '<?php echo esc(addslashes($p['name'])); ?>')">
                                            <i class="fas fa-user-check"></i> Assign</button>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <?php else: ?>
            <!-- ==================== LEAD TABLE ==================== -->
            <div class="bg-white rounded-2xl border border-slate-200 overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="ld">
                        <thead>
                            <tr>
                                <th>Lead</th><th>Contact</th><th>Interest</th><th>Source</th>
                                <th>Status</th><th>Next follow-up</th><th>Owner</th><th>Added by</th><th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if (empty($rows)): ?>
                            <tr><td colspan="9" class="text-center py-10 text-slate-400">No leads in this view yet.</td></tr>
                        <?php else: foreach ($rows as $r):
                            $overdue = !empty($r['next_follow_up']) && $r['next_follow_up'] <= date('Y-m-d')
                                       && in_array($r['status'], lead_open_statuses(), true);
                        ?>
                            <tr>
                                <td>
                                    <p class="font-extrabold text-slate-800"><?php echo esc($r['name']); ?></p>
                                    <p class="text-[10.5px] text-slate-400">
                                        #<?php echo (int)$r['id']; ?>
                                        <?php if (!empty($r['user_id'])): ?> · member WBMCZ<?php echo str_pad((string)$r['user_id'], 4, '0', STR_PAD_LEFT); ?><?php endif; ?>
                                    </p>
                                    <?php $pr = lead_priorities(); if (!empty($r['priority']) && isset($pr[$r['priority']])): ?>
                                        <span class="pill <?php echo $pr[$r['priority']][1]; ?> mt-1"><?php echo $pr[$r['priority']][0]; ?></span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <p class="font-semibold"><?php echo esc($r['mobile']); ?></p>
                                    <p class="text-[10.5px] text-slate-400"><?php echo esc($r['email'] ?: ''); ?></p>
                                    <div class="flex gap-1 mt-1">
                                        <a href="tel:<?php echo esc($r['mobile']); ?>" class="cbtn bg-slate-500 hover:bg-slate-600"><i class="fas fa-phone"></i></a>
                                        <a href="https://wa.me/91<?php echo preg_replace('/\D/', '', (string)$r['mobile']); ?>" target="_blank" class="cbtn bg-emerald-600 hover:bg-emerald-700"><i class="fab fa-whatsapp"></i></a>
                                    </div>
                                </td>
                                <td class="text-[11px] max-w-[160px]"><?php echo esc($r['interest'] ?: '—'); ?></td>
                                <td class="text-[11px]"><?php echo esc(lead_source_label($r['source'])); ?></td>
                                <td>
                                    <span class="pill <?php echo lead_status_class($r['status']); ?>">
                                        <i class="fas <?php echo lead_status_icon($r['status']); ?>"></i><?php echo lead_status_label($r['status']); ?>
                                    </span>
                                </td>
                                <td class="text-[11px] <?php echo $overdue ? 'due' : 'text-slate-500'; ?>">
                                    <?php echo !empty($r['next_follow_up']) ? date('d M Y', strtotime($r['next_follow_up'])) : '—'; ?>
                                    <?php if ($overdue): ?><br><span class="text-[9.5px]">due now</span><?php endif; ?>
                                </td>
                                <td class="text-[11px]"><?php echo esc($r['assigned_name'] ?: '—'); ?></td>
                                <td class="text-[11px] text-slate-400"><?php echo esc($r['created_by_name'] ?: '—'); ?></td>
                                <td>
                                    <div class="flex flex-wrap gap-1">
                                        <button type="button" class="cbtn bg-indigo-600 hover:bg-indigo-700" @click="openLead(<?php echo (int)$r['id']; ?>)"><i class="fas fa-eye"></i></button>
                                        <button type="button" class="cbtn bg-amber-500 hover:bg-amber-600"
                                                @click="openFollow(<?php echo (int)$r['id']; ?>, 0, '<?php echo esc(addslashes($r['name'])); ?>', '<?php echo esc($r['status']); ?>')"><i class="fas fa-clock"></i></button>
                                        <button type="button" class="cbtn bg-emerald-600 hover:bg-emerald-700"
                                                @click="openAssign(<?php echo (int)$r['id']; ?>, 0, '<?php echo esc(addslashes($r['name'])); ?>')"><i class="fas fa-user-check"></i></button>
                                        <button type="button" class="cbtn bg-slate-600 hover:bg-slate-700" @click="openEdit(<?php echo (int)$r['id']; ?>)"><i class="fas fa-pen"></i></button>
                                        <?php if ($LD_SUPER): ?>
                                        <form method="POST" class="inline" onsubmit="return confirm('Delete this lead and its history?')">
                                            <input type="hidden" name="lead_id" value="<?php echo (int)$r['id']; ?>">
                                            <button type="submit" name="delete_lead" value="1" class="cbtn bg-rose-600 hover:bg-rose-700"><i class="fas fa-trash"></i></button>
                                        </form>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <?php endif; ?>

            <?php if ($pages > 1): ?>
            <div class="flex flex-wrap items-center justify-center gap-1.5 mt-5">
                <?php for ($i = 1; $i <= min($pages, 12); $i++): ?>
                    <a href="leads.php?tab=<?php echo $TAB; ?>&p=<?php echo $i; ?>"
                       class="px-3 py-1.5 rounded-lg text-xs font-bold <?php echo $i === $page ? 'bg-slate-900 text-white' : 'bg-white border border-slate-200 text-slate-600'; ?>"><?php echo $i; ?></a>
                <?php endfor; ?>
            </div>
            <?php endif; ?>
        </main>
    </div>
</div>

<!-- ============================ MODALS ============================ -->
<template x-teleport="body">
<div x-show="modal" x-transition.opacity class="fixed inset-0 z-[100] flex items-center justify-center p-4" style="display:none;">
    <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" @click="close()"></div>

    <!-- ---------- ADD / EDIT ---------- -->
    <div x-show="modal==='form'" x-transition class="relative w-full max-w-2xl bg-white rounded-2xl shadow-2xl overflow-hidden max-h-[92vh] flex flex-col">
        <div class="bg-gradient-to-r from-indigo-600 to-blue-600 px-5 py-4 flex items-center justify-between flex-shrink-0">
            <h3 class="text-white font-bold text-lg"><i class="fas fa-user-plus mr-2"></i><span x-text="mode==='add' ? 'Add Lead' : 'Edit Lead'"></span></h3>
            <button @click="close()" class="text-white/80 hover:text-white text-2xl leading-none">&times;</button>
        </div>
        <form method="POST" class="flex flex-col overflow-hidden">
            <input type="hidden" name="lead_id" :value="f.id">
            <div class="p-5 overflow-y-auto space-y-4">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                    <div><label class="lbl">Name <span class="text-rose-500">*</span></label><input name="name" x-model="f.name" class="fld" required></div>
                    <div><label class="lbl">Mobile <span class="text-rose-500">*</span></label><input name="mobile" x-model="f.mobile" class="fld" required inputmode="numeric"></div>
                    <div><label class="lbl">Alternate mobile</label><input name="alt_mobile" x-model="f.alt_mobile" class="fld"></div>
                    <div><label class="lbl">Email</label><input type="email" name="email" x-model="f.email" class="fld"></div>
                    <div><label class="lbl">Where did it come from</label>
                        <select name="source" x-model="f.source" class="fld">
                            <?php foreach (lead_sources() as $k => $v): ?><option value="<?php echo $k; ?>"><?php echo $v; ?></option><?php endforeach; ?>
                        </select></div>
                    <div><label class="lbl">Priority</label>
                        <select name="priority" x-model="f.priority" class="fld">
                            <option value="high">High</option><option value="medium">Medium</option><option value="low">Low</option>
                        </select></div>
                    <div class="md:col-span-2"><label class="lbl">Interested in</label>
                        <input name="interest" x-model="f.interest" class="fld" placeholder="e.g. Aadhaar update, PAN card, seller account"></div>
                </div>

                <div>
                    <p class="text-[11px] font-bold uppercase tracking-wide text-blue-600 mb-2 border-b pb-1"><i class="fas fa-location-dot mr-1"></i>Location</p>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                        <div><label class="lbl">State</label><input name="state" x-model="f.state" class="fld"></div>
                        <div><label class="lbl">District</label><input name="district" x-model="f.district" class="fld"></div>
                        <div><label class="lbl">Pincode</label><input name="pincode" x-model="f.pincode" class="fld"></div>
                        <div><label class="lbl">Address</label><input name="address" x-model="f.address" class="fld"></div>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-3">
                    <div x-show="mode==='add'"><label class="lbl">Status</label>
                        <select name="status" x-model="f.status" class="fld">
                            <?php foreach (lead_statuses() as $k => $v): ?><option value="<?php echo $k; ?>"><?php echo $v[0]; ?></option><?php endforeach; ?>
                        </select></div>
                    <div x-show="mode==='add'"><label class="lbl">Assign to</label>
                        <select name="assigned_to" x-model="f.assigned_to" class="fld">
                            <option value="0">Nobody yet</option>
                            <?php foreach ($staff as $st): ?><option value="<?php echo (int)$st['id']; ?>"><?php echo htmlspecialchars($st['name']); ?></option><?php endforeach; ?>
                        </select></div>
                    <div><label class="lbl">Next follow-up</label><input type="date" name="next_follow_up" x-model="f.next_follow_up" class="fld"></div>
                </div>

                <div><label class="lbl">Notes</label><textarea name="notes" x-model="f.notes" rows="3" class="fld" placeholder="What did they ask for?"></textarea></div>

                <p class="text-[10px] text-slate-400"><i class="fas fa-circle-info mr-1"></i>Saved with your name, so everyone can see who entered it.</p>
            </div>
            <div class="flex justify-end gap-2 px-5 py-4 border-t bg-slate-50 flex-shrink-0">
                <button type="button" @click="close()" class="px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-200 rounded-lg">Cancel</button>
                <button type="submit" :name="mode==='add' ? 'add_lead' : 'edit_lead'" value="1" class="px-5 py-2 text-sm font-bold text-white bg-indigo-600 hover:bg-indigo-700 rounded-lg shadow">
                    <i class="fas fa-save mr-1"></i><span x-text="mode==='add' ? 'Add Lead' : 'Save'"></span>
                </button>
            </div>
        </form>
    </div>

    <!-- ---------- FOLLOW UP ---------- -->
    <div x-show="modal==='follow'" x-transition class="relative w-full max-w-md bg-white rounded-2xl shadow-2xl overflow-hidden">
        <div class="bg-gradient-to-r from-amber-500 to-orange-600 px-5 py-4 flex items-center justify-between">
            <div><h3 class="text-white font-bold text-base"><i class="fas fa-clock mr-2"></i>Follow-up</h3>
                 <p class="text-white/75 text-[11px]" x-text="cur.name"></p></div>
            <button @click="close()" class="text-white/80 hover:text-white text-2xl leading-none">&times;</button>
        </div>
        <form method="POST" class="p-5 space-y-4">
            <input type="hidden" name="lead_id" :value="cur.id">
            <input type="hidden" name="from_user" :value="cur.uid">
            <div><label class="lbl">Status now</label>
                <select name="status" x-model="cur.status" class="fld">
                    <?php foreach (lead_statuses() as $k => $v): ?><option value="<?php echo $k; ?>"><?php echo $v[0]; ?></option><?php endforeach; ?>
                </select></div>
            <div><label class="lbl">What happened</label>
                <textarea name="remark" rows="3" class="fld" placeholder="Called — will decide next week"></textarea></div>
            <div><label class="lbl">Call again on</label><input type="date" name="next_follow_up" class="fld"></div>
            <div class="flex justify-end gap-2 pt-1">
                <button type="button" @click="close()" class="px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-200 rounded-lg">Cancel</button>
                <button type="submit" name="follow_lead" value="1" class="px-5 py-2 text-sm font-bold text-white bg-amber-600 hover:bg-amber-700 rounded-lg shadow"><i class="fas fa-check mr-1"></i>Save follow-up</button>
            </div>
        </form>
    </div>

    <!-- ---------- ASSIGN ---------- -->
    <div x-show="modal==='assign'" x-transition class="relative w-full max-w-md bg-white rounded-2xl shadow-2xl overflow-hidden">
        <div class="bg-gradient-to-r from-emerald-600 to-teal-600 px-5 py-4 flex items-center justify-between">
            <div><h3 class="text-white font-bold text-base"><i class="fas fa-user-check mr-2"></i>Hand this lead over</h3>
                 <p class="text-white/75 text-[11px]" x-text="cur.name"></p></div>
            <button @click="close()" class="text-white/80 hover:text-white text-2xl leading-none">&times;</button>
        </div>
        <form method="POST" class="p-5 space-y-4">
            <input type="hidden" name="lead_id" :value="cur.id">
            <input type="hidden" name="from_user" :value="cur.uid">
            <div><label class="lbl">Staff member</label>
                <select name="assigned_to" class="fld">
                    <option value="0">— nobody (back to the pool) —</option>
                    <?php foreach ($staff as $st): ?>
                        <option value="<?php echo (int)$st['id']; ?>"><?php echo htmlspecialchars($st['name']); ?><?php echo !empty($st['role_name']) ? ' · ' . htmlspecialchars($st['role_name']) : ''; ?></option>
                    <?php endforeach; ?>
                </select></div>
            <div><label class="lbl">Note for them</label><textarea name="remark" rows="2" class="fld" placeholder="Optional"></textarea></div>
            <p class="text-[11px] text-slate-500">They get a notification and the lead shows up in their own list.</p>
            <div class="flex justify-end gap-2">
                <button type="button" @click="close()" class="px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-200 rounded-lg">Cancel</button>
                <button type="submit" name="assign_lead" value="1" class="px-5 py-2 text-sm font-bold text-white bg-emerald-600 hover:bg-emerald-700 rounded-lg shadow"><i class="fas fa-check mr-1"></i>Assign</button>
            </div>
        </form>
    </div>

    <!-- ---------- DETAILS ---------- -->
    <div x-show="modal==='view'" x-transition class="relative w-full max-w-2xl bg-white rounded-2xl shadow-2xl overflow-hidden max-h-[92vh] flex flex-col">
        <div class="bg-gradient-to-r from-slate-800 to-slate-700 px-5 py-4 flex items-center justify-between flex-shrink-0">
            <div class="min-w-0">
                <h3 class="text-white font-bold text-lg truncate" x-text="(view && (view.name || view.full_name)) || 'Lead details'"></h3>
                <p class="text-white/60 text-[11px]" x-text="view ? (view.mobile || '') : ''"></p>
            </div>
            <button @click="close()" class="text-white/80 hover:text-white text-2xl leading-none">&times;</button>
        </div>
        <div class="p-5 overflow-y-auto space-y-5">
            <template x-if="loading"><p class="text-center text-slate-400 py-8"><i class="fas fa-spinner fa-spin mr-2"></i>Loading…</p></template>

            <template x-if="!loading && view">
                <div class="space-y-5">
                    <div class="grid grid-cols-2 md:grid-cols-3 gap-2">
                        <template x-for="row in detailRows()" :key="row[0]">
                            <div class="bg-slate-50 border border-slate-200 rounded-xl px-3 py-2">
                                <p class="text-[9px] font-black uppercase tracking-widest text-slate-400" x-text="row[0]"></p>
                                <p class="text-[12px] font-bold text-slate-700 break-words" x-text="row[1] || '—'"></p>
                            </div>
                        </template>
                    </div>

                    <div x-show="history.length">
                        <p class="text-[11px] font-bold uppercase tracking-wide text-indigo-600 mb-3 border-b pb-1"><i class="fas fa-clock-rotate-left mr-1"></i>Follow-up history</p>
                        <div class="tl">
                            <template x-for="h in history" :key="h.id">
                                <div class="tl-i">
                                    <p class="text-[12px] font-bold text-slate-700">
                                        <span x-text="actionLabel(h.action)"></span>
                                        <template x-if="h.new_value"><span class="text-indigo-600" x-text="' → ' + h.new_value"></span></template>
                                    </p>
                                    <p class="text-[11.5px] text-slate-600" x-show="h.remark" x-text="h.remark"></p>
                                    <p class="text-[10px] text-slate-400 mt-0.5">
                                        <span x-text="h.done_by_name || 'System'"></span> ·
                                        <span x-text="fmt(h.created_at)"></span>
                                        <template x-if="h.next_follow_up"><span> · next <span x-text="h.next_follow_up"></span></span></template>
                                    </p>
                                </div>
                            </template>
                        </div>
                    </div>
                    <p x-show="!history.length" class="text-[12px] text-slate-400 text-center py-4">No follow-up recorded yet.</p>
                </div>
            </template>
        </div>
        <div class="flex justify-end gap-2 px-5 py-4 border-t bg-slate-50 flex-shrink-0">
            <button type="button" @click="close()" class="px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-200 rounded-lg">Close</button>
        </div>
    </div>
</div>
</template>

<script>
function leadApp() {
    return {
        sidebarOpen: window.innerWidth >= 768,
        modal: null, mode: 'add', loading: false,
        f: {}, cur: { id: 0, uid: 0, name: '', status: 'new' },
        view: null, history: [],

        sel: [],
        pageIds: <?php echo json_encode($page_ids); ?>,
        isSel(id) { return this.sel.indexOf(id) > -1; },
        toggleOne(id) { const i = this.sel.indexOf(id); if (i > -1) this.sel.splice(i, 1); else this.sel.push(id); },
        allOnPage() { return this.pageIds.length > 0 && this.pageIds.every(i => this.sel.includes(i)); },
        toggleAll(on) {
            if (on) { this.pageIds.forEach(i => { if (!this.sel.includes(i)) this.sel.push(i); }); }
            else { this.sel = this.sel.filter(i => !this.pageIds.includes(i)); }
        },

        blank() {
            return { id: '', name: '', mobile: '', alt_mobile: '', email: '', source: 'manual',
                     interest: '', state: '', district: '', pincode: '', address: '',
                     status: 'new', priority: 'medium', assigned_to: '0', next_follow_up: '', notes: '' };
        },
        openAdd() { this.f = this.blank(); this.mode = 'add'; this.modal = 'form'; },
        async openEdit(id) {
            this.f = this.blank(); this.mode = 'edit'; this.modal = 'form';
            const d = await this.get('lead', id);
            if (d) { Object.keys(this.f).forEach(k => { if (d[k] !== undefined && d[k] !== null) this.f[k] = String(d[k]); }); this.f.id = d.id; }
        },
        openFollow(id, uid, name, status) { this.cur = { id: id || 0, uid: uid || 0, name: name, status: status || 'new' }; this.modal = 'follow'; },
        openAssign(id, uid, name) { this.cur = { id: id || 0, uid: uid || 0, name: name, status: 'new' }; this.modal = 'assign'; },

        async openLead(id) {
            this.modal = 'view'; this.loading = true; this.view = null; this.history = [];
            this.view = await this.get('lead', id);
            this.history = (await this.get('history', id)) || [];
            this.loading = false;
        },
        async openUser(uid) {
            this.modal = 'view'; this.loading = true; this.view = null; this.history = [];
            const u = await this.get('user', uid);
            this.view = u;
            if (u && u.lead) { this.history = (await this.get('history', u.lead.id)) || []; }
            this.loading = false;
        },

        detailRows() {
            const v = this.view || {};
            const a = v.account || {};
            const rows = [
                ['Name', v.name || v.full_name], ['Mobile', v.mobile], ['Email', v.email],
                ['State', v.state || a.state], ['District', v.district || a.district], ['Pincode', v.pincode || a.pincode],
                ['Village', v.village], ['Post office', v.post_office], ['Block / City', v.block_city],
                ['Source', v.source], ['Interested in', v.interest],
                ['Status', v.status], ['Priority', v.priority],
                ['Assigned to', v.assigned_name], ['Next follow-up', v.next_follow_up],
                ['Added by', v.created_by_name], ['Registered', (v.created_at || '').substring(0, 10)],
                ['Subscribed', (v.is_subscribed || a.is_subscribed) ? 'Yes' : 'No'],
                ['Notes', v.notes],
            ];
            return rows.filter(r => r[1] !== undefined && r[1] !== null && String(r[1]) !== '');
        },
        actionLabel(a) {
            return { created: 'Lead created', assign: 'Assigned', status: 'Status changed', note: 'Note added', edit: 'Details updated' }[a] || a;
        },
        fmt(s) {
            if (!s) return '';
            const d = new Date(String(s).replace(' ', 'T'));
            if (isNaN(d)) return s;
            return d.toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' }) + ', ' +
                   d.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
        },
        async get(kind, id) {
            try { const r = await fetch('leads.php?ajax=' + kind + '&id=' + id); return await r.json(); }
            catch (e) { return null; }
        },
        close() { this.modal = null; }
    }
}
</script>
</body>
</html>
