<?php
require_once 'includes/header.php';

// Handle Bulk Action (Junk)
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) AND assigned_agent_id = $agent_id");
            header("Location: my_leads.php?msg=bulk_junked"); exit;
        }
    } catch (PDOException $e) { $error = "Bulk Error: " . $e->getMessage(); }
}

// Filters
$search      = trim($_GET['search']    ?? '');
$filter_stage= $_GET['status_id']     ?? '';
$filter_from = $_GET['date_from']     ?? '';
$filter_to   = $_GET['date_to']       ?? '';
$filter_project = $_GET['project_type'] ?? '';

$sql = "SELECT l.*, st.name as stage, st.color_code,
               (SELECT COUNT(*) FROM lead_followups f WHERE f.lead_id=l.id AND f.status='pending' AND f.followup_date >= NOW()) as upcoming_fups
        FROM leads l
        LEFT JOIN lead_statuses st ON l.status_id = st.id
        WHERE l.assigned_agent_id = ? AND l.is_junk = 0";
// Build filter SQL and params
$filter_sql = "";
$params = [$agent_id];
if (!empty($search))       { $filter_sql .= " AND (l.phone LIKE ? OR l.name LIKE ?)"; $p="%$search%"; $params[]=$p; $params[]=$p; }
if (!empty($filter_stage)) { $filter_sql .= " AND l.status_id = ?"; $params[] = $filter_stage; }
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; }
if (!empty($filter_project)) { $filter_sql .= " AND l.project_type = ?"; $params[] = $filter_project; }

// Count total leads (with filters)
$sql_count = "SELECT COUNT(*) FROM leads l WHERE l.assigned_agent_id = ? AND l.is_junk = 0" . $filter_sql;
$stmt_cnt = $pdo->prepare($sql_count);
$stmt_cnt->execute($params);
$total_leads = $stmt_cnt->fetchColumn();

// Pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$limit = 10;
$offset = ($page - 1) * $limit;
$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();

$all_stages = $pdo->query("SELECT * FROM lead_statuses ORDER BY name")->fetchAll();
$all_services = $pdo->query("SELECT name FROM lead_services WHERE status='active' ORDER BY name")->fetchAll(PDO::FETCH_COLUMN);
$has_filter = (!empty($search)||!empty($filter_stage)||!empty($filter_from)||!empty($filter_to)||!empty($filter_project));
?>
<script>document.getElementById('page-title').textContent='My Leads';</script>

<!-- Filter Bar -->
<div class="ag-card" style="padding:18px 22px;margin-bottom:20px;">
    <form method="GET" style="display:flex;gap:12px;flex-wrap:wrap;align-items:flex-end;">
        <div style="flex:2;min-width:160px;">
            <label>Search</label>
            <input type="text" name="search" value="<?=htmlspecialchars($search)?>" placeholder="Phone or name...">
        </div>
        <div style="flex:1;min-width:140px;">
            <label>Pipeline Stage</label>
            <select name="status_id">
                <option value="">All Stages</option>
                <?php foreach($all_stages as $s): ?>
                <option value="<?=$s['id']?>" <?=$filter_stage==$s['id']?'selected':''?>><?=htmlspecialchars($s['name'])?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div style="flex:1;min-width:140px;">
            <label>Service/Type</label>
            <select name="project_type">
                <option value="">All Services</option>
                <?php foreach($all_services as $srv): ?>
                <option value="<?=$srv?>" <?=$filter_project==$srv?'selected':''?>><?=$srv?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div style="flex:1;min-width:130px;">
            <label>From</label>
            <input type="date" name="date_from" value="<?=htmlspecialchars($filter_from)?>">
        </div>
        <div style="flex:1;min-width:130px;">
            <label>To</label>
            <input type="date" name="date_to" value="<?=htmlspecialchars($filter_to)?>">
        </div>
        <div style="display:flex;gap:8px;align-items:flex-end;">
            <button type="submit" class="btn-primary"><i class="fa-solid fa-filter"></i> Filter</button>
            <button type="button" onclick="document.getElementById('exportModal').style.display='flex'" class="btn-primary" style="background:#f0fdf4;color:#16a34a;border:1px solid #bbf7d0;"><i class="fa-solid fa-file-export"></i> Export</button>
            <?php if($has_filter): ?><a href="my_leads.php" class="btn-primary" style="background:#f1f5f9;color:#64748b;"><i class="fa-solid fa-xmark"></i> Clear</a><?php endif; ?>
        </div>
    </form>
</div>

<style>
    .btn-3d { 
        display:inline-flex; align-items:center; justify-content:center; 
        width:32px; height:32px; 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:active { top:4px; box-shadow:none !important; }

    @media (max-width: 768px) {
        /* Force compact ROW view — override any global transforms or default overflows */
        .ag-table, .ag-table thead, .ag-table tbody,
        .ag-table th, .ag-table td, .ag-table tr {
            display: revert !important;
        }
        .ag-table { width:100%; border-collapse:collapse; display: table !important; }
        .ag-table thead tr { position: relative !important; top: auto !important; left: auto !important; }
        .ag-table th, .ag-table td {
            padding: 10px 5px !important;
            font-size: 0.78rem !important;
            vertical-align: middle !important;
            min-height: auto !important;
            padding-left: 5px !important;
            border-bottom: 1px solid #f1f5f9 !important;
            border: none !important;
            border-bottom: 1px solid #f1f5f9 !important;
        }
        .ag-table tr {
            border: none !important;
            border-radius: 0 !important;
            margin-bottom: 0 !important;
            padding: 0 !important;
            box-shadow: none !important;
            display: table-row !important;
        }
        .ag-table td:before { display: none !important; content: none !important; }
        
        .btn-3d { width: 30px !important; height: 30px !important; font-size: 0.8rem !important; margin-left: 4px !important; }
    }
</style>

<div class="ag-card" style="padding:0;overflow:hidden;">
    <form action="my_leads.php" method="POST" id="bulkForm">
        <div style="padding:16px 22px;border-bottom:2px solid var(--border);display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;">
            <label style="display:flex;align-items:center;cursor:pointer;font-weight:700;font-size:0.95rem;color:#0f172a;gap:10px;">
                <input type="checkbox" id="selectAll" style="width:18px;height:18px;accent-color:var(--primary);cursor:pointer;"> 
                <i class="fa-solid fa-users" style="color:var(--primary);"></i><?= $total_leads ?> Lead<?= $total_leads != 1 ? 's' : '' ?>
                <span style="color:#94a3b8; font-size:0.82rem; font-weight:500;">(Showing <?= count($leads) ?>)</span>
            </label>
            <div style="display:flex;gap:10px;align-items:center;">
                <button type="submit" name="bulk_action" value="junk" class="btn-primary btn-sm" style="background:#f59e0b; border:none;" onclick="return confirm('Move selected leads to junk?');">
                    <i class="fa-solid fa-ban"></i> Bulk Junk
                </button>
                <a href="lead_add.php" class="btn-primary btn-sm"><i class="fa-solid fa-plus"></i> Add Lead</a>
            </div>
        </div>
    <div style="overflow-x:auto;">
        <table class="ag-table">
            <thead>
                <tr>
                    <th style="width:40px;"></th>
                    <th style="width:60px;">#</th>
                    <th>Contact</th>
                    <th style="text-align:right;">Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php if(empty($leads)): ?>
                <tr><td colspan="4" style="text-align:center;padding:40px;color:#94a3b8;"><i class="fa-solid fa-box-open" style="font-size:2rem;display:block;margin-bottom:10px;color:#e2e8f0;"></i>No leads found.</td></tr>
            <?php else: $sno = $offset + 1; foreach($leads as $l): ?>
                <tr>
                    <td><input type="checkbox" name="selected_leads[]" value="<?=$l['id']?>" class="lead-checkbox" style="width:17px;height:17px;accent-color:var(--primary);cursor:pointer;"></td>
                    <td style="color:#94a3b8;font-size:0.82rem;">#<?=$sno++?></td>
                    <td>
                        <div style="font-weight:700;color:#0f172a;"><?=htmlspecialchars($l['phone'])?></div>
                        <?php if(!empty($l['name'])): ?><div style="font-size:0.78rem;color:#94a3b8;"><?=htmlspecialchars($l['name'])?></div><?php endif; ?>
                    </td>
                    <td style="text-align:right; white-space:nowrap;">
                        <a href="lead_view.php?id=<?=$l['id']?>" class="btn-3d btn-3d-view" title="View Lead"><i class="fa-solid fa-eye"></i></a>
                        <a href="lead_add.php?edit=<?=$l['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>
                    </td>
                </tr>
            <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
    </form>

    <!-- Pagination Controls -->
    <?php if ($total_pages > 1): ?>
    <div style="padding:16px 22px; border-top:1px solid var(--border); display:flex; justify-content:center; align-items:center; gap:10px; background:#f8fafc;">
        <?php
        $q_str = $_GET;
        unset($q_str['page']);
        $b_url = "my_leads.php?" . http_build_query($q_str);
        if ($b_url !== "my_leads.php?") $b_url .= "&";
        ?>
        
        <?php if ($page > 1): ?>
            <a href="<?= $b_url ?>page=<?= $page - 1 ?>" style="padding:6px 12px; background:#fff; border:1px solid #e2e8f0; border-radius:6px; color:#64748b; text-decoration:none; font-weight:700; font-size:0.8rem;"><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="<?= $b_url ?>page=<?= $i ?>" style="width:30px; height:30px; display:inline-flex; align-items:center; justify-content:center; border-radius:6px; text-decoration:none; font-weight:700; font-size:0.8rem; <?= $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="<?= $b_url ?>page=<?= $page + 1 ?>" style="padding:6px 12px; background:#fff; border:1px solid #e2e8f0; border-radius:6px; color:#64748b; text-decoration:none; font-weight:700; font-size:0.8rem;">Next <i class="fa-solid fa-chevron-right"></i></a>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</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 My 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 style="width:16px;height:16px;"> 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 style="width:16px;height:16px;"> 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 style="width:16px;height:16px;"> 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 style="width:16px;height:16px;"> Pipeline Status
                </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 style="width:16px;height:16px;"> 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 style="width:16px;height:16px;"> Date Added
                </label>
                <label style="display:flex; align-items:center; gap:8px; font-size:0.9rem; cursor:pointer;">
                    <input type="checkbox" name="fields[]" value="notes" style="width:16px;height:16px;"> Internal Notes
                </label>
            </div>

            <!-- Keep filters -->
            <input type="hidden" name="search" value="<?= htmlspecialchars($search) ?>">
            <input type="hidden" name="status_id" value="<?= htmlspecialchars($filter_stage) ?>">
            <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" class="btn-primary" style="flex:1; background:#16a34a; color:#fff; border:none; height:45px; justify-content:center;">
                    <i class="fa-solid fa-download"></i> Download Excel
                </button>
                <button type="button" onclick="document.getElementById('exportModal').style.display='none'" class="btn-primary" style="background:#f1f5f9; color:#64748b; border:none; height:45px; justify-content:center;">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'; ?>
