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

// Load funnels, filters
$all_funnels = $pdo->query("SELECT * FROM lead_funnels ORDER BY name ASC")->fetchAll();
$all_statuses = $pdo->query("SELECT * FROM lead_statuses ORDER BY name ASC")->fetchAll();
$all_sources = $pdo->query("SELECT * FROM lead_sources ORDER BY name ASC")->fetchAll();

$selected_funnel = isset($_GET['funnel_id']) && !empty($_GET['funnel_id']) ? (int)$_GET['funnel_id'] : ($all_funnels[0]['id'] ?? null);
$filter_status = $_GET['status_id'] ?? '';
$filter_source = $_GET['source_id'] ?? '';
$filter_date_from = $_GET['date_from'] ?? '';
$filter_date_to = $_GET['date_to'] ?? '';

// Load stages for selected funnel
$stages = [];
if ($selected_funnel) {
    $stages = $pdo->prepare("SELECT * FROM lead_stages WHERE funnel_id = ? ORDER BY stage_order ASC, name ASC");
    $stages->execute([$selected_funnel]);
    $stages = $stages->fetchAll();
}

// Build leads query with filters
$params = [$selected_funnel];
$filter_clauses = "l.funnel_id = ? AND l.is_junk = 0";

if (!empty($filter_status)) {
    $filter_clauses .= " AND l.status_id = ?";
    $params[] = (int)$filter_status;
}
if (!empty($filter_source)) {
    $filter_clauses .= " AND l.source_id = ?";
    $params[] = (int)$filter_source;
}
if (!empty($filter_date_from)) {
    $filter_clauses .= " AND DATE(l.created_at) >= ?";
    $params[] = $filter_date_from;
}
if (!empty($filter_date_to)) {
    $filter_clauses .= " AND DATE(l.created_at) <= ?";
    $params[] = $filter_date_to;
}

$leads_stmt = $pdo->prepare("
    SELECT l.*, 
        ls.name as status_name, ls.color_code as status_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 $filter_clauses
    ORDER BY l.created_at DESC
");
$leads_stmt->execute($params);
$all_leads = $leads_stmt->fetchAll();

// Group leads by stage_id
$leads_by_stage = [];
$unassigned = [];
foreach ($all_leads as $lead) {
    if ($lead['stage_id']) {
        $leads_by_stage[$lead['stage_id']][] = $lead;
    } else {
        $unassigned[] = $lead;
    }
}
?>

<div class="dashboard-content" style="max-width:100%;">
    <div class="welcome-banner" style="margin-bottom:20px; padding:20px; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:15px;">
        <div>
            <h2><i class="fa-solid fa-diagram-project"></i> Funnel View</h2>
            <p>Visualize your leads in their pipeline stages.</p>
        </div>
        <a href="lead_add_edit.php" style="color:var(--primary); background:#fff; padding:10px 20px; border-radius:6px; text-decoration:none; font-weight:600;"><i class="fa-solid fa-plus"></i> Add Lead</a>
    </div>

    <!-- Filters -->
    <div class="data-card" style="margin-bottom:20px; background:#fff; padding:20px; border-radius:12px; 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="min-width:160px; flex:1;">
                <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">Funnel</label>
                <select name="funnel_id" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px; background:#fff;" onchange="this.form.submit()">
                    <?php foreach ($all_funnels as $f): ?>
                        <option value="<?= $f['id'] ?>" <?= $f['id'] == $selected_funnel ? 'selected' : '' ?>><?= htmlspecialchars($f['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div style="min-width:140px; flex:1;">
                <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">Status</label>
                <select name="status_id" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px; background:#fff;">
                    <option value="">All Status</option>
                    <?php foreach ($all_statuses as $s): ?>
                        <option value="<?= $s['id'] ?>" <?= $s['id'] == $filter_status ? 'selected' : '' ?>><?= htmlspecialchars($s['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div style="min-width:140px; flex:1;">
                <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">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'] ?>" <?= $src['id'] == $filter_source ? 'selected' : '' ?>><?= htmlspecialchars($src['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div style="min-width:130px; flex:1;">
                <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">From Date</label>
                <input type="date" name="date_from" value="<?= htmlspecialchars($filter_date_from) ?>" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
            </div>
            <div style="min-width:130px; flex:1;">
                <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">To Date</label>
                <input type="date" name="date_to" value="<?= htmlspecialchars($filter_date_to) ?>" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
            </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($filter_status) || !empty($filter_source) || !empty($filter_date_from)): ?>
                    <a href="lead_funnel_view.php?funnel_id=<?= $selected_funnel ?>" 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>

    <!-- Kanban Board -->
    <?php if (empty($stages)): ?>
        <div class="data-card" style="background:#fff; padding:40px; text-align:center; border-radius:12px;">
            <i class="fa-solid fa-diagram-project" style="font-size:3rem; color:#cbd5e1; margin-bottom:15px; display:block;"></i>
            <p style="color:#64748b;">No stages found for this funnel. <a href="lead_stages.php">Create stages first</a>.</p>
        </div>
    <?php else: ?>
    <div class="funnel-board">
        <?php foreach ($stages as $stage): 
            $stage_leads = $leads_by_stage[$stage['id']] ?? [];
        ?>
        <div class="kanban-col">
            <div class="kanban-col-header">
                <span class="kanban-col-title"><?= htmlspecialchars($stage['name']) ?></span>
                <span class="kanban-count"><?= count($stage_leads) ?></span>
            </div>
            <div class="kanban-cards">
                <?php if (empty($stage_leads)): ?>
                    <div style="padding:15px; text-align:center; color:#cbd5e1; font-size:0.85rem; font-style:italic;">No leads</div>
                <?php endif; ?>
                <?php foreach ($stage_leads as $l): ?>
                    <a href="lead_view.php?id=<?= $l['id'] ?>" class="kanban-card">
                        <div class="kc-phone"><?= htmlspecialchars($l['phone']) ?></div>
                        <?php if ($l['status_name']): ?>
                            <span class="kc-badge" style="background:<?= $l['status_color'] ?>22; color:<?= $l['status_color'] ?>; border:1px solid <?= $l['status_color'] ?>44;"><?= htmlspecialchars($l['status_name']) ?></span>
                        <?php endif; ?>
                        <?php if ($l['next_followup']): ?>
                            <?php 
                            $diff = (int)((strtotime($l['next_followup']) - time()) / 86400);
                            $fup_color = $diff < 0 ? '#ef4444' : ($diff === 0 ? '#f59e0b' : '#64748b');
                            ?>
                            <div class="kc-followup" style="color:<?= $fup_color ?>;">
                                <i class="fa-regular fa-clock" style="margin-right:3px;"></i>
                                <?= $diff < 0 ? abs($diff).' days overdue' : ($diff === 0 ? 'Today' : 'In '.$diff.' days') ?>
                            </div>
                        <?php endif; ?>
                    </a>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endforeach; ?>

        <?php if (!empty($unassigned)): ?>
        <div class="kanban-col">
            <div class="kanban-col-header" style="background:#f1f5f9;">
                <span class="kanban-col-title">Unassigned</span>
                <span class="kanban-count"><?= count($unassigned) ?></span>
            </div>
            <div class="kanban-cards">
                <?php foreach ($unassigned as $l): ?>
                    <a href="lead_view.php?id=<?= $l['id'] ?>" class="kanban-card" style="border-left:3px solid #cbd5e1;">
                        <div class="kc-phone"><?= htmlspecialchars($l['phone']) ?></div>
                    </a>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>

<style>
.funnel-board {
    display: flex;
    gap: 18px;
    overflow-x: auto;
    padding-bottom: 20px;
    min-height: 400px;
}
.funnel-board::-webkit-scrollbar { height: 6px; }
.funnel-board::-webkit-scrollbar-thumb { background:#cbd5e1; border-radius:3px; }

.kanban-col {
    min-width: 240px;
    max-width: 260px;
    flex-shrink: 0;
    background: #f8fafc;
    border-radius: 12px;
    border: 1px solid var(--border);
}
.kanban-col-header {
    padding: 14px 15px;
    background: #fff;
    border-bottom: 1px solid var(--border);
    border-radius: 12px 12px 0 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.kanban-col-title { font-weight: 700; color: var(--dark); font-size: 0.95rem; }
.kanban-count {
    background: var(--primary);
    color: #fff;
    border-radius: 20px;
    padding: 2px 9px;
    font-size: 0.78rem;
    font-weight: 700;
}
.kanban-cards { padding: 10px; display: flex; flex-direction: column; gap: 8px; }
.kanban-card {
    background: #fff;
    border-radius: 8px;
    padding: 12px;
    border: 1px solid #e2e8f0;
    border-left: 4px solid var(--primary);
    text-decoration: none;
    display: block;
    transition: box-shadow 0.2s, transform 0.2s;
}
.kanban-card:hover { box-shadow: 0 4px 12px rgba(0,0,0,0.08); transform: translateY(-2px); }
.kc-phone { font-weight: 700; color: var(--dark); font-size: 0.95rem; margin-bottom: 6px; }
.kc-badge { font-size: 0.75rem; padding: 2px 8px; border-radius: 10px; font-weight: 600; display: inline-block; margin-bottom: 5px; }
.kc-followup { font-size: 0.78rem; margin-top: 5px; }
</style>

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