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

// Fetch pipeline stages and sources for filter
$all_stages = $pdo->query("SELECT * FROM lead_statuses ORDER BY id ASC")->fetchAll();
$all_sources = $pdo->query("SELECT * FROM lead_sources ORDER BY name ASC")->fetchAll();

// Filters
$f_source = $_GET['source_id'] ?? '';
$f_project = $_GET['project_type'] ?? '';
$f_search = $_GET['search'] ?? '';

$project_types = $pdo->query("SELECT name FROM lead_services WHERE status='active' ORDER BY name ASC")->fetchAll(PDO::FETCH_COLUMN);

// Build base leads query — all active
$where = "l.is_junk = 0";
$params = [];
if (!empty($f_source)) { $where .= " AND l.source_id = ?"; $params[] = (int)$f_source; }
if (!empty($f_project)) { $where .= " AND l.project_type = ?"; $params[] = $f_project; }
if (!empty($f_search)) { $where .= " AND (l.name LIKE ? OR l.phone LIKE ?)"; $params[] = "%$f_search%"; $params[] = "%$f_search%"; }

$stmt = $pdo->prepare("
    SELECT l.*, ls.name as stage_name, ls.color_code as stage_color,
        (SELECT MIN(f.followup_date) FROM lead_followups f WHERE f.lead_id = l.id AND f.status = 'pending') as next_followup
    FROM leads l
    LEFT JOIN lead_statuses ls ON l.status_id = ls.id
    WHERE $where
");
$stmt->execute($params);
$all_leads = $stmt->fetchAll();

// Group by pipeline stage
$by_stage = [];
foreach ($all_stages as $stage) {
    $by_stage[$stage['id']] = ['stage' => $stage, 'leads' => []];
}
$unassigned = ['stage' => ['name' => 'Unassigned', 'color_code' => '#94a3b8', 'id' => 0], 'leads' => []];

foreach ($all_leads as $lead) {
    if ($lead['status_id'] && isset($by_stage[$lead['status_id']])) {
        $by_stage[$lead['status_id']]['leads'][] = $lead;
    } else {
        $unassigned['leads'][] = $lead;
    }
}

// Funnel Data Calculation
$funnel_data = [];
$total_leads_count = count($all_leads);
foreach ($all_stages as $st) {
    $count = count($by_stage[$st['id']]['leads'] ?? []);
    $funnel_data[] = [
        'name'  => $st['name'],
        'count' => $count,
        'color' => $st['color_code'],
        'pct'   => $total_leads_count > 0 ? round(($count / $total_leads_count) * 100) : 0
    ];
}
?>
<div class="dashboard-content" style="max-width:100%;">
    <div class="welcome-banner" style="margin-bottom:20px; padding:20px; display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:15px;">
        <div>
            <h2><i class="fa-solid fa-diagram-project"></i> Pipeline View</h2>
            <p>See all your leads organized by their pipeline stage.</p>
        </div>
        <a href="lead_add_edit.php" style="padding:10px 18px; background:#fff; color:var(--primary); border-radius:8px; font-weight:600; text-decoration:none;"><i class="fa-solid fa-plus"></i> Add Lead</a>
    </div>

    <!-- Filters -->
    <div class="data-card" style="background:#fff; padding:20px; border-radius:12px; margin-bottom:20px; box-shadow:0 4px 15px rgba(0,0,0,0.03);">
        <form method="GET" style="display:flex; gap:15px; flex-wrap:wrap; align-items:flex-end;">
            <div style="flex:2; min-width:180px;">
                <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">Search</label>
                <input type="text" name="search" value="<?= htmlspecialchars($f_search) ?>" placeholder="Name or phone..." style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px;">
            </div>
            <div style="flex:1; min-width:150px;">
                <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">Project Type</label>
                <select name="project_type" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px; background:#fff;">
                    <option value="">All Types</option>
                    <?php foreach ($project_types as $pt): ?>
                        <option value="<?= $pt ?>" <?= $f_project === $pt ? 'selected' : '' ?>><?= $pt ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div style="flex:1; min-width:150px;">
                <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">Lead Source</label>
                <select name="source_id" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px; background:#fff;">
                    <option value="">All Sources</option>
                    <?php foreach ($all_sources as $src): ?>
                        <option value="<?= $src['id'] ?>" <?= $f_source == $src['id'] ? 'selected' : '' ?>><?= htmlspecialchars($src['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <button type="submit" style="padding:10px 20px; background:var(--dark); color:#fff; border:none; border-radius:6px; font-weight:600; cursor:pointer;"><i class="fa-solid fa-filter"></i> Filter</button>
                <?php if (!empty($f_source) || !empty($f_project) || !empty($f_search)): ?>
                    <a href="lead_pipeline.php" style="margin-left:5px; padding:10px 15px; background:#e2e8f0; color:var(--dark); text-decoration:none; border-radius:6px; font-weight:600; display:inline-block;">Reset</a>
                <?php endif; ?>
            </div>
        </form>
    </div>

    <!-- Lead Funnel -->
    <div class="ag-card" style="padding:25px; margin-bottom:25px; background:#fff; text-align:center;">
        <h3 style="margin:0 0 25px; font-size:1.1rem; color:#1e293b; font-weight:800; text-transform:uppercase; letter-spacing:0.05em;">
            <i class="fa-solid fa-filter" style="color:var(--primary); margin-right:8px;"></i> Conversion Funnel
        </h3>
        
        <div class="funnel-container">
            <?php 
            $count_stages = count($funnel_data);
            foreach ($funnel_data as $i => $item): 
                if ($item['count'] === 0 && $total_leads_count > 0) continue; // Skip empty if not empty overall
                // Calculate width reduction for funnel effect
                $width = 100 - ($i * (60 / max($count_stages, 1))); 
                $width = max($width, 30);
            ?>
                <div class="funnel-step" style="width: <?=$width?>%; background: <?=$item['color']?>;">
                    <span class="funnel-label"><?=htmlspecialchars($item['name'])?></span>
                    <span class="funnel-value"><?=$item['count']?> <small>(<?=$item['pct']?>%)</small></span>
                </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- Stats bar (Minimal version) -->
    <div style="display:flex; gap:10px; flex-wrap:wrap; margin-bottom:20px; justify-content:center;">
        <div style="background:#f1f5f9; border-radius:30px; padding:6px 20px; font-size:0.85rem; font-weight:700; color:#64748b; border:1px solid #e2e8f0;">
            Total Leads in Pipeline: <span style="color:var(--dark); margin-left:5px;"><?=$total_leads_count?></span>
        </div>
    </div>

</div>

<style>
/* Funnel Styling */
.funnel-container { display: flex; flex-direction: column; align-items: center; gap: 4px; max-width: 800px; margin: 0 auto; }
.funnel-step { height: 45px; position: relative; display: flex; align-items: center; justify-content: space-between; padding: 0 25px; color: #fff; font-weight: 700; border-radius: 4px; box-shadow: 0 4px 10px rgba(0,0,0,0.1); transition: transform 0.2s; cursor: pointer; }
.funnel-step:hover { transform: scale(1.02); z-index: 10; }
.funnel-step:after { content: ""; position: absolute; bottom: -12px; left: 50%; transform: translateX(-50%); border-left: 10px solid transparent; border-right: 10px solid transparent; border-top: 10px solid rgba(0,0,0,0.05); z-index: 1; }
.funnel-step:last-child:after { display: none; }
.funnel-label { font-size: 0.95rem; text-shadow: 0 1px 2px rgba(0,0,0,0.2); }
.funnel-value { font-size: 1rem; background: rgba(255,255,255,0.15); padding: 3px 12px; border-radius: 20px; text-shadow: 0 1px 2px rgba(0,0,0,0.2); }

@media (max-width:768px) { .funnel-step { padding: 0 15px; height: 40px; } .funnel-label { font-size: 0.8rem; } .funnel-value { font-size: 0.85rem; } }
</style>

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