<?php
require_once 'config/db.php';

// ---- ALL REDIRECTING ACTIONS BEFORE header.php ----

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action']) && !empty($_POST['selected_leads'])) {
    $lead_ids   = implode(',', array_map('intval', $_POST['selected_leads']));
    $bulk_action = $_POST['bulk_action'];
    try {
        if ($bulk_action === 'junk')   { $pdo->query("UPDATE leads SET is_junk=1 WHERE id IN ($lead_ids)"); header("Location: leads.php?msg=bulk_junked"); exit; }
        if ($bulk_action === 'delete') { $pdo->query("DELETE FROM leads WHERE id IN ($lead_ids)"); header("Location: leads.php?msg=bulk_deleted"); exit; }
    } catch (PDOException $e) { $error = "Bulk Error: " . $e->getMessage(); }
}

if (isset($_GET['action']) && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    try {
        if ($_GET['action'] === 'junk')   { $pdo->prepare("UPDATE leads SET is_junk=1 WHERE id=?")->execute([$id]); header("Location: leads.php?msg=moved_to_junk"); exit; }
        if ($_GET['action'] === 'delete') { $pdo->prepare("DELETE FROM leads WHERE id=?")->execute([$id]); header("Location: leads.php?msg=deleted"); exit; }
    } catch (PDOException $e) { $error = "Error: " . $e->getMessage(); }
}

require_once 'includes/header.php';

// Flash messages
$msgs = ['moved_to_junk'=>'Lead moved to junk.','deleted'=>'Lead deleted.','bulk_junked'=>'Selected leads moved to junk.','bulk_deleted'=>'Selected leads deleted.'];
if (isset($_GET['msg'])) $success = $msgs[$_GET['msg']] ?? '';

// ---- Filters ----
$search         = trim($_GET['search']       ?? '');
$filter_status  = $_GET['status_id']         ?? '';
$filter_source  = $_GET['source_id']         ?? '';
$filter_agent   = $_GET['agent_id']          ?? '';
$filter_project = trim($_GET['project_type'] ?? '');
$filter_from    = $_GET['date_from']         ?? '';
$filter_to      = $_GET['date_to']           ?? '';

$sql = "SELECT l.*, s.name as source_name, st.name as status_name, st.color_code as status_color,
               ag.name as agent_name, ag.id as agent_id_col
        FROM leads l
        LEFT JOIN lead_sources s   ON l.source_id         = s.id
        LEFT JOIN lead_statuses st ON l.status_id         = st.id
        LEFT JOIN sales_agents ag  ON l.assigned_agent_id = ag.id
        WHERE l.is_junk = 0";
// ---- Pagination Logic ----
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$limit = 10;
$offset = ($page - 1) * $limit;

// Build filter SQL and params
$filter_sql = "";
$params = [];
if (!empty($search)) {
    $filter_sql .= " AND (l.name LIKE ? OR l.phone LIKE ? OR l.email LIKE ?)";
    $p = "%$search%"; $params[] = $p; $params[] = $p; $params[] = $p;
}
if (!empty($filter_status))  { $filter_sql .= " AND l.status_id = ?";       $params[] = $filter_status; }
if (!empty($filter_source))  { $filter_sql .= " AND l.source_id = ?";       $params[] = $filter_source; }
if (!empty($filter_agent))   { 
    if($filter_agent === 'none') $filter_sql .= " AND l.assigned_agent_id IS NULL";
    else { $filter_sql .= " AND l.assigned_agent_id=?"; $params[] = $filter_agent; }
}
if (!empty($filter_project)) { $filter_sql .= " AND l.project_type LIKE ?"; $params[] = "%$filter_project%"; }
if (!empty($filter_from))    { $filter_sql .= " AND DATE(l.created_at) >= ?"; $params[] = $filter_from; }
if (!empty($filter_to))      { $filter_sql .= " AND DATE(l.created_at) <= ?"; $params[] = $filter_to; }

// Count total leads (with filters)
$cnt_sql = "SELECT COUNT(*) FROM leads l WHERE l.is_junk = 0" . $filter_sql;
$stmt_cnt = $pdo->prepare($cnt_sql);
$stmt_cnt->execute($params);
$total_leads = $stmt_cnt->fetchColumn();
$total_pages = ceil($total_leads / $limit);

// Main Query with Pagination
$sql .= $filter_sql . " ORDER BY l.created_at DESC LIMIT $limit OFFSET $offset";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$leads = $stmt->fetchAll();

// Dropdown data for filters
$all_statuses = $pdo->query("SELECT * FROM lead_statuses ORDER BY name")->fetchAll();
$all_sources  = $pdo->query("SELECT * FROM lead_sources  ORDER BY name")->fetchAll();
$all_agents   = $pdo->query("SELECT * FROM sales_agents WHERE is_active=1 ORDER BY name")->fetchAll();

$has_filter = (!empty($search)||!empty($filter_status)||!empty($filter_source)||!empty($filter_agent)||!empty($filter_project)||!empty($filter_from)||!empty($filter_to));

?>

<div class="dashboard-content">
    <!-- Header -->
    <div class="welcome-banner" style="margin-bottom:20px; padding:20px; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:12px;" id="leadsHeader">
        <div>
            <h2><i class="fa-solid fa-users"></i> Active Leads</h2>
            <p>Manage and track all your active prospects. <strong><?= $total_leads ?></strong> lead<?= $total_leads != 1 ? 's' : '' ?> found.</p>
        </div>
        <a href="lead_add_edit.php" style="color:var(--primary); background:#fff; display:inline-flex; align-items:center; gap:8px; padding:10px 20px; border-radius:6px; text-decoration:none; font-weight:600;" class="mobile-w-100">
            <i class="fa-solid fa-plus"></i> Add New Lead
        </a>
    </div>

    <?php if (isset($success)): ?>
        <div class="badge badge-completed" style="display:block; padding:14px; margin-bottom:16px; font-size:0.95rem;"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>
    <?php if (isset($error)): ?>
        <div style="display:block; padding:14px; margin-bottom:16px; background:#fee2e2; color:#ef4444; border-radius:8px; font-weight:600;"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <!-- Filters Card -->
    <div style="background:#fff; border:2px solid #e2e8f0; border-radius:14px; padding:20px; margin-bottom:20px; box-shadow:0 2px 8px rgba(0,0,0,0.03);">
        <form action="leads.php" method="GET" id="filterForm">
            <!-- Row 1: Search + Pipeline Stage + Source + Agent -->
            <div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(200px, 1fr)); gap:14px; margin-bottom:14px;" class="stackable">
                <div>
                    <label class="flabel">🔍 Search</label>
                    <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" placeholder="Name, phone or email..." class="finput">
                </div>
                <div>
                    <label class="flabel">📊 Pipeline Stage</label>
                    <select name="status_id" class="finput">
                        <option value="">All Stages</option>
                        <?php foreach ($all_statuses as $s): ?>
                            <option value="<?= $s['id'] ?>" <?= $filter_status == $s['id'] ? 'selected' : '' ?>><?= htmlspecialchars($s['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="flabel">📣 Lead Source</label>
                    <select name="source_id" class="finput">
                        <option value="">All Sources</option>
                        <?php foreach ($all_sources as $s): ?>
                            <option value="<?= $s['id'] ?>" <?= $filter_source == $s['id'] ? 'selected' : '' ?>><?= htmlspecialchars($s['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="flabel">👤 Sales Agent</label>
                    <select name="agent_id" class="finput">
                        <option value="">All Agents</option>
                        <option value="none" <?= $filter_agent === 'none' ? 'selected' : '' ?>>— Unassigned</option>
                        <?php foreach ($all_agents as $ag): ?>
                            <option value="<?= $ag['id'] ?>" <?= $filter_agent == $ag['id'] ? 'selected' : '' ?>><?= htmlspecialchars($ag['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <!-- Row 2: Project Type + Date Range + Buttons -->
            <div style="display:flex; gap:14px; flex-wrap:wrap; align-items:flex-end;" class="stackable">
                <div style="flex:1; min-width:140px;" class="mobile-w-100">
                    <label class="flabel">🏗️ Project Type</label>
                    <input type="text" name="project_type" value="<?= htmlspecialchars($filter_project) ?>" placeholder="e.g. House Construction" class="finput">
                </div>
                <div style="flex:1; min-width:130px;" class="mobile-w-100">
                    <label class="flabel">📅 Added From</label>
                    <input type="date" name="date_from" value="<?= htmlspecialchars($filter_from) ?>" class="finput">
                </div>
                <div style="flex:1; min-width:130px;" class="mobile-w-100">
                    <label class="flabel">📅 Added To</label>
                    <input type="date" name="date_to" value="<?= htmlspecialchars($filter_to) ?>" class="finput">
                </div>
                <div style="display:flex; gap:10px; flex-wrap:wrap;" class="mobile-w-100">
                    <button type="submit" style="padding:11px 22px; background:var(--dark); color:#fff; border:none; border-radius:8px; font-weight:700; cursor:pointer; display:inline-flex; align-items:center; gap:7px; white-space:nowrap;" class="mobile-w-100 flex-center">
                        <i class="fa-solid fa-filter"></i> Filter
                    </button>
                    <button type="button" onclick="document.getElementById('exportModal').style.display='flex'" style="padding:11px 18px; background:#f0fdf4; color:#16a34a; border:2px solid #bbf7d0; border-radius:8px; font-weight:700; cursor:pointer; display:inline-flex; align-items:center; gap:7px; white-space:nowrap;" class="mobile-w-100 flex-center">
                        <i class="fa-solid fa-file-export"></i> Export
                    </button>
                    <?php if ($has_filter): ?>
                        <a href="leads.php" style="padding:11px 18px; background:#f1f5f9; color:#64748b; border-radius:8px; font-weight:600; text-decoration:none; display:inline-flex; align-items:center; gap:6px; white-space:nowrap;" class="mobile-w-100 flex-center">
                            <i class="fa-solid fa-xmark"></i> Clear
                        </a>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Active filter chips -->
            <?php if ($has_filter): ?>
            <div style="margin-top:14px; display:flex; flex-wrap:wrap; gap:6px; align-items:center;">
                <span style="font-size:0.78rem; color:#94a3b8; font-weight:600;">ACTIVE:</span>
                <?php if($search): ?>         <span class="fchip">Search: <?= htmlspecialchars($search) ?></span><?php endif; ?>
                <?php if($filter_status): ?>  <span class="fchip">Stage: <?= htmlspecialchars(array_column($all_statuses,'name','id')[$filter_status] ?? $filter_status) ?></span><?php endif; ?>
                <?php if($filter_source): ?>  <span class="fchip">Source: <?= htmlspecialchars(array_column($all_sources,'name','id')[$filter_source] ?? $filter_source) ?></span><?php endif; ?>
                <?php if($filter_agent): ?>   <span class="fchip">Agent: <?= $filter_agent === 'none' ? 'Unassigned' : htmlspecialchars(array_column($all_agents,'name','id')[$filter_agent] ?? $filter_agent) ?></span><?php endif; ?>
                <?php if($filter_project): ?> <span class="fchip">Project: <?= htmlspecialchars($filter_project) ?></span><?php endif; ?>
                <?php if($filter_from): ?>    <span class="fchip">From: <?= htmlspecialchars($filter_from) ?></span><?php endif; ?>
                <?php if($filter_to): ?>      <span class="fchip">To: <?= htmlspecialchars($filter_to) ?></span><?php endif; ?>
            </div>
            <?php endif; ?>
        </form>
    </div>

    <!-- Leads Table -->
    <style>
        .flabel { display:block; margin-bottom:7px; font-weight:700; font-size:0.82rem; color:#64748b; }
        .finput  { width:100%; padding:10px 13px; border:2px solid #e2e8f0; border-radius:8px; font-family:inherit; font-size:0.9rem; box-sizing:border-box; background:#fff; }
        .finput:focus { border-color:var(--primary); outline:none; }
        select.finput { background:#fff; }
        .fchip { background:#e0f2fe; color:#0369a1; padding:4px 10px; border-radius:14px; font-size:0.78rem; font-weight:700; }
        .btn-3d { display:inline-flex; align-items:center; justify-content:center; width:36px; height:36px; border-radius:8px; text-decoration:none; transition:all 0.1s; position:relative; top:0; border:none; cursor:pointer; margin-left:6px; }
        .btn-3d-view   { background:#3b82f6; color:#fff; box-shadow:0 4px 0 #2563eb; }
        .btn-3d-junk   { background:#f59e0b; color:#fff; box-shadow:0 4px 0 #d97706; }
        .btn-3d-delete { background:#ef4444; color:#fff; box-shadow:0 4px 0 #dc2626; }
        .btn-3d:active { top:4px; box-shadow:none !important; }
        .custom-checkbox { width:18px; height:18px; cursor:pointer; accent-color:var(--primary); }
        .stage-pill { display:inline-block; padding:3px 10px; border-radius:12px; font-size:0.75rem; font-weight:700; }
        @media (max-width:768px) {
            /* Force compact ROW view — override the global card transform */
            .admin-table, .admin-table thead, .admin-table tbody,
            .admin-table th, .admin-table td, .admin-table tr {
                display: revert !important;
            }
            .admin-table { width:100%; border-collapse:collapse; }
            .admin-table thead tr { position: relative !important; top: auto !important; left: auto !important; }
            .admin-table th, .admin-table td {
                padding: 10px 6px !important;
                font-size: 0.78rem !important;
                vertical-align: middle !important;
                min-height: auto !important;
                padding-left: 6px !important;
                border-bottom: 1px solid #f1f5f9 !important;
                border: none !important;
                border-bottom: 1px solid #f1f5f9 !important;
            }
            .admin-table tr {
                border: none !important;
                border-radius: 0 !important;
                margin-bottom: 0 !important;
                padding: 0 !important;
                box-shadow: none !important;
                display: table-row !important;
            }
            .admin-table td:before { display: none !important; content: none !important; }

            .mobile-actions-grid {
                display: flex !important;
                flex-direction: row !important;
                justify-content: flex-end !important;
                align-items: center !important;
                gap: 4px !important;
                padding-right: 8px !important;
                padding-left: 0 !important;
                width: auto !important;
            }
            .mobile-actions-grid .btn-3d { margin: 0 !important; width: 32px !important; height: 32px !important; font-size: 0.8rem !important; }
            .btn-3d { width: 32px !important; height: 32px !important; font-size: 0.8rem !important; margin-left: 3px !important; }
            .mobile-w-100 { width: 100% !important; }
            .flex-center { justify-content: center !important; }
            #leadsHeader { text-align: center; }
            #leadsHeader div { width: 100%; }
        }
    </style>

    <div class="recent-activity" style="padding:0;">
        <form action="leads.php" method="POST" id="bulkForm">
            <div style="padding:14px 20px; background:#f8fafc; border-bottom:1px solid var(--border); display:flex; align-items:center; justify-content:space-between; border-top-left-radius:12px; border-top-right-radius:12px; gap:10px; flex-wrap:wrap;">
                <label style="display:flex; align-items:center; cursor:pointer; font-weight:600; color:var(--dark); font-size:0.9rem; gap:10px;">
                    <input type="checkbox" id="selectAll" class="custom-checkbox"> Select All
                    <span style="color:#94a3b8; font-size:0.82rem; font-weight:500;">(Showing <?= count($leads) ?> on this page)</span>
                </label>
                <div style="display:flex; gap:8px;">
                    <button type="submit" name="bulk_action" value="junk" class="btn-3d btn-3d-junk" style="width:auto; padding:0 14px; font-weight:700; font-size:0.82rem; height:34px; margin:0; gap:6px;" onclick="return confirm('Move selected leads to junk?');">
                        <i class="fa-solid fa-ban"></i> Junk
                    </button>
                    <button type="submit" name="bulk_action" value="delete" class="btn-3d btn-3d-delete" style="width:auto; padding:0 14px; font-weight:700; font-size:0.82rem; height:34px; margin:0; gap:6px;" onclick="return confirm('Permanently DELETE selected leads?');">
                        <i class="fa-solid fa-trash"></i> Delete
                    </button>
                </div>
            </div>
            <div class="table-responsive">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th style="padding-left:20px; width:40px;"></th>
                            <th style="width:60px;">#</th>
                            <th>Contact / Name</th>
                            <th style="text-align:right; padding-right:20px;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($leads) > 0): $sno = $offset + 1; ?>
                            <?php foreach ($leads as $lead): ?>
                            <tr>
                                <td style="padding-left:20px;" data-label="Select">
                                    <input type="checkbox" name="selected_leads[]" value="<?= $lead['id'] ?>" class="custom-checkbox lead-checkbox">
                                </td>
                                <td style="color:#94a3b8; font-weight:500; font-size:0.9rem;" data-label="No">#<?= $sno++ ?></td>
                                <td data-label="Lead Info">
                                    <div style="font-weight:700; color:var(--dark); font-size:1rem;"><?= htmlspecialchars($lead['phone']) ?></div>
                                    <?php if (!empty($lead['name'])): ?>
                                        <div style="font-size:0.82rem; color:#64748b; margin-top:2px;"><?= htmlspecialchars($lead['name']) ?></div>
                                    <?php endif; ?>
                                    <?php 
                                        $addr_parts = array_filter([$lead['building_name'], $lead['area'], $lead['city'], $lead['district'], $lead['pincode'], $lead['state']]);
                                        if(!empty($addr_parts)): 
                                    ?>
                                        <div style="font-size:0.75rem; color:#94a3b8; margin-top:2px; font-style:italic;"><i class="fa-solid fa-location-dot" style="font-size:0.7rem;"></i> <?= htmlspecialchars(implode(', ', $addr_parts)) ?></div>
                                    <?php endif; ?>
                                </td>
                                <td style="text-align:right; padding-right:20px;" class="mobile-actions-grid" data-label="Actions">
                                    <a href="lead_view.php?id=<?= $lead['id'] ?>" class="btn-3d btn-3d-view" title="View Lead"><i class="fa-solid fa-eye"></i></a>
                                    <a href="lead_add_edit.php?edit=<?= $lead['id'] ?>" class="btn-3d" style="background:#8b5cf6; color:#fff; box-shadow:0 4px 0 #7c3aed;" title="Edit"><i class="fa-solid fa-pen"></i></a>
                                    <a href="leads.php?action=junk&id=<?= $lead['id'] ?>" class="btn-3d btn-3d-junk" title="Mark as Junk" onclick="return confirm('Move to junk?')"><i class="fa-solid fa-ban"></i></a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="4" style="text-align:center; color:#94a3b8; padding:50px 20px;">
                                    <i class="fa-solid fa-box-open" style="font-size:2.5rem; color:#e2e8f0; display:block; margin-bottom:12px;"></i>
                                    <?= $has_filter ? 'No leads match your filters. <a href="leads.php" style="color:var(--primary);">Clear filters</a>' : 'No active leads found. <a href="lead_add_edit.php" style="color:var(--primary);">Add your first lead</a>' ?>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </form>

        <!-- Pagination Controls -->
        <?php if ($total_pages > 1): ?>
        <div style="padding:20px; border-top:1px solid #f1f5f9; display:flex; justify-content:center; align-items:center; gap:10px;">
            <?php
            $query_string = $_GET;
            unset($query_string['page']);
            $base_url = "leads.php?" . http_build_query($query_string);
            if ($base_url !== "leads.php?") $base_url .= "&";
            ?>
            
            <?php if ($page > 1): ?>
                <a href="<?= $base_url ?>page=<?= $page - 1 ?>" style="padding:8px 14px; background:#fff; border:1px solid #e2e8f0; border-radius:6px; color:var(--dark); text-decoration:none; font-weight:600; font-size:0.85rem;"><i class="fa-solid fa-chevron-left"></i> Previous</a>
            <?php endif; ?>

            <div style="display:flex; gap:5px;">
                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <a href="<?= $base_url ?>page=<?= $i ?>" style="width:34px; height:34px; display:inline-flex; align-items:center; justify-content:center; border-radius:6px; text-decoration:none; font-weight:700; font-size:0.88rem; <?= $page == $i ? 'background:var(--primary); color:#fff; border:1px solid var(--primary);' : 'background:#fff; border:1px solid #e2e8f0; color:#64748b;' ?>">
                        <?= $i ?>
                    </a>
                <?php endfor; ?>
            </div>

            <?php if ($page < $total_pages): ?>
                <a href="<?= $base_url ?>page=<?= $page + 1 ?>" style="padding:8px 14px; background:#fff; border:1px solid #e2e8f0; border-radius:6px; color:var(--dark); text-decoration:none; font-weight:600; font-size:0.85rem;">Next <i class="fa-solid fa-chevron-right"></i></a>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Export Lead Modal -->
<div id="exportModal" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.6); z-index:9999; align-items:center; justify-content:center; padding:15px;">
    <div style="background:#fff; border-radius:16px; padding:30px; width:100%; max-width:500px; box-shadow:0 20px 60px rgba(0,0,0,0.3);">
        <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:20px;">
            <h3 style="margin:0; color:var(--dark);"><i class="fa-solid fa-file-excel" style="color:#16a34a; margin-right:8px;"></i> Export Leads</h3>
            <button type="button" onclick="document.getElementById('exportModal').style.display='none'" style="background:none; border:none; font-size:1.4rem; color:#94a3b8; cursor:pointer;">&#x2715;</button>
        </div>
        
        <form action="export_leads.php" method="POST">
            <p style="font-size:0.9rem; color:#64748b; margin-bottom:18px;">Select the fields you want to include in your Excel export.</p>
            
            <div style="display:grid; grid-template-columns:1fr 1fr; gap:12px; margin-bottom:24px;">
                <label style="display:flex; align-items:center; gap:8px; font-size:0.9rem; cursor:pointer;">
                    <input type="checkbox" name="fields[]" value="phone" checked disabled class="custom-checkbox"> Phone / Contact
                    <input type="hidden" name="fields[]" value="phone">
                </label>
                <label style="display:flex; align-items:center; gap:8px; font-size:0.9rem; cursor:pointer;">
                    <input type="checkbox" name="fields[]" value="name" checked class="custom-checkbox"> Name
                </label>
                <label style="display:flex; align-items:center; gap:8px; font-size:0.9rem; cursor:pointer;">
                    <input type="checkbox" name="fields[]" value="email" checked class="custom-checkbox"> Email
                </label>
                <label style="display:flex; align-items:center; gap:8px; font-size:0.9rem; cursor:pointer;">
                    <input type="checkbox" name="fields[]" value="status" checked class="custom-checkbox"> Pipeline Status
                </label>
                <label style="display:flex; align-items:center; gap:8px; font-size:0.9rem; cursor:pointer;">
                    <input type="checkbox" name="fields[]" value="source" checked class="custom-checkbox"> Lead Source
                </label>
                <label style="display:flex; align-items:center; gap:8px; font-size:0.9rem; cursor:pointer;">
                    <input type="checkbox" name="fields[]" value="agent" checked class="custom-checkbox"> Assigned Agent
                </label>
                <label style="display:flex; align-items:center; gap:8px; font-size:0.9rem; cursor:pointer;">
                    <input type="checkbox" name="fields[]" value="project_type" checked class="custom-checkbox"> Project Type
                </label>
                <label style="display:flex; align-items:center; gap:8px; font-size:0.9rem; cursor:pointer;">
                    <input type="checkbox" name="fields[]" value="created_at" checked class="custom-checkbox"> Date Added
                </label>
                <label style="display:flex; align-items:center; gap:8px; font-size:0.9rem; cursor:pointer;">
                    <input type="checkbox" name="fields[]" value="building_name" checked class="custom-checkbox"> Building / Door No
                </label>
                <label style="display:flex; align-items:center; gap:8px; font-size:0.9rem; cursor:pointer;">
                    <input type="checkbox" name="fields[]" value="area" checked class="custom-checkbox"> Area / Street
                </label>
                <label style="display:flex; align-items:center; gap:8px; font-size:0.9rem; cursor:pointer;">
                    <input type="checkbox" name="fields[]" value="city" checked class="custom-checkbox"> City
                </label>
                <label style="display:flex; align-items:center; gap:8px; font-size:0.9rem; cursor:pointer;">
                    <input type="checkbox" name="fields[]" value="district" checked class="custom-checkbox"> District
                </label>
                <label style="display:flex; align-items:center; gap:8px; font-size:0.9rem; cursor:pointer;">
                    <input type="checkbox" name="fields[]" value="pincode" checked class="custom-checkbox"> Pincode
                </label>
                <label style="display:flex; align-items:center; gap:8px; font-size:0.9rem; cursor:pointer;">
                    <input type="checkbox" name="fields[]" value="state" checked class="custom-checkbox"> State
                </label>
                <label style="display:flex; align-items:center; gap:8px; font-size:0.9rem; cursor:pointer;">
                    <input type="checkbox" name="fields[]" value="notes" class="custom-checkbox"> Internal Notes
                </label>
            </div>

            <!-- Keep filters -->
            <input type="hidden" name="search" value="<?= htmlspecialchars($search) ?>">
            <input type="hidden" name="status_id" value="<?= htmlspecialchars($filter_status) ?>">
            <input type="hidden" name="source_id" value="<?= htmlspecialchars($filter_source) ?>">
            <input type="hidden" name="agent_id" value="<?= htmlspecialchars($filter_agent) ?>">
            <input type="hidden" name="project_type" value="<?= htmlspecialchars($filter_project) ?>">
            <input type="hidden" name="date_from" value="<?= htmlspecialchars($filter_from) ?>">
            <input type="hidden" name="date_to" value="<?= htmlspecialchars($filter_to) ?>">
            <input type="hidden" name="selected_ids" id="export_selected_ids" value="">

            <div style="display:flex; gap:10px;">
                <button type="submit" style="flex:1; padding:12px; background:#16a34a; color:#fff; border:none; border-radius:8px; font-weight:700; cursor:pointer; font-size:1rem; display:inline-flex; align-items:center; justify-content:center; gap:8px;">
                    <i class="fa-solid fa-download"></i> Download Excel
                </button>
                <button type="button" onclick="document.getElementById('exportModal').style.display='none'" style="padding:12px 20px; background:#f1f5f9; color:#64748b; border:none; border-radius:8px; font-weight:600; cursor:pointer;">Cancel</button>
            </div>
        </form>
    </div>
</div>

<script>
document.getElementById('selectAll').addEventListener('change', function() {
    document.querySelectorAll('.lead-checkbox').forEach(cb => cb.checked = this.checked);
});

// Capture selected IDs for export
const exportForm = document.querySelector('#exportModal form');
exportForm.addEventListener('submit', function() {
    const selected = Array.from(document.querySelectorAll('.lead-checkbox:checked')).map(cb => cb.value);
    document.getElementById('export_selected_ids').value = selected.join(',');
});
</script>

<?php require_once 'includes/footer.php'; ?>
