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

// ------- Filters -------
$f_from     = $_GET['date_from']    ?? date('Y-m-01');
$f_to       = $_GET['date_to']      ?? date('Y-m-d');
$f_stage    = $_GET['stage_id']     ?? '';
$f_source   = $_GET['source_id']    ?? '';
$f_project  = $_GET['project_type'] ?? '';

$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();
$project_types = ['Residential Construction','Commercial Construction','Renovation & Repair','Interior Works','Civil Works','Other'];

// ------- Base WHERE (for most queries) -------
$base_where  = "l.assigned_agent_id = ? AND l.is_junk = 0 AND DATE(l.created_at) BETWEEN ? AND ?";
$base_params = [$agent_id, $f_from, $f_to];

if ($f_stage  != '') { $base_where .= " AND l.status_id = ?";    $base_params[] = (int)$f_stage;  }
if ($f_source != '') { $base_where .= " AND l.source_id = ?";    $base_params[] = (int)$f_source; }
if ($f_project != '') { $base_where .= " AND l.project_type = ?"; $base_params[] = $f_project;   }

function run($pdo, $sql, $params = []) {
    $s = $pdo->prepare($sql);
    $s->execute($params);
    return $s->fetchAll();
}
function runVal($pdo, $sql, $params = []) {
    $s = $pdo->prepare($sql);
    $s->execute($params);
    return $s->fetchColumn();
}

// ------- 1. Summary -------
$total      = runVal($pdo, "SELECT COUNT(*) FROM leads l WHERE $base_where", $base_params);
$converted  = runVal($pdo, "SELECT COUNT(*) FROM leads l LEFT JOIN lead_statuses ls ON l.status_id=ls.id WHERE $base_where AND ls.name='Converted'", $base_params);
$lost       = runVal($pdo, "SELECT COUNT(*) FROM leads l LEFT JOIN lead_statuses ls ON l.status_id=ls.id WHERE $base_where AND ls.name='Lost'", $base_params);
$active     = $total - $converted - $lost;

// ------- 2. By Pipeline Stage -------
$by_stage = run($pdo, "
    SELECT ls.name, ls.color_code, COUNT(l.id) as cnt
    FROM leads l LEFT JOIN lead_statuses ls ON l.status_id=ls.id
    WHERE $base_where
    GROUP BY l.status_id, ls.name, ls.color_code ORDER BY cnt DESC
", $base_params);

// ------- 3. By Source -------
$by_source = run($pdo, "
    SELECT IFNULL(src.name,'Unknown') as name, COUNT(l.id) as cnt
    FROM leads l LEFT JOIN lead_sources src ON l.source_id=src.id
    WHERE $base_where GROUP BY l.source_id, src.name ORDER BY cnt DESC
", $base_params);

// ------- 4. Daily New Leads -------
$daily = run($pdo, "
    SELECT DATE(l.created_at) as day, COUNT(*) as cnt
    FROM leads l WHERE $base_where
    GROUP BY DATE(l.created_at) ORDER BY day ASC
", $base_params);
$daily_map = array_column($daily, 'cnt', 'day');
$max_day   = max(array_values($daily_map) ?: [1]);

$total_src = max(array_sum(array_column($by_source, 'cnt')), 1);
$total_stg = max(array_sum(array_column($by_stage, 'cnt')), 1);
?>

<script>document.getElementById('page-title').textContent='Sales Reports';</script>

<div class="ag-card" style="padding:18px 22px;margin-bottom:20px;background:linear-gradient(135deg, #1e293b, #334155);color:#fff;border:none;">
    <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:15px;">
        <div>
            <h2 style="font-size:1.4rem;font-weight:800;margin-bottom:4px;"><i class="fa-solid fa-chart-line"></i> Sales Performance</h2>
            <p style="font-size:0.85rem;opacity:0.9;">Analyze your lead conversion and activity metrics.</p>
        </div>
        <a href="export_leads.php?date_from=<?=$f_from?>&date_to=<?=$f_to?>&agent_id=<?=$agent_id?>" class="btn-primary" style="background:#22c55e;border:none;color:#fff;">
            <i class="fa-solid fa-file-excel"></i> Export Leads
        </a>
    </div>
</div>

<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:1;min-width:130px;">
            <label>From</label>
            <input type="date" name="date_from" value="<?= $f_from ?>">
        </div>
        <div style="flex:1;min-width:130px;">
            <label>To</label>
            <input type="date" name="date_to" value="<?= $f_to ?>">
        </div>
        <div style="flex:1.5;min-width:150px;">
            <label>Stage</label>
            <select name="stage_id">
                <option value="">All Stages</option>
                <?php foreach($all_stages as $s): ?><option value="<?= $s['id'] ?>" <?= $f_stage==$s['id']?'selected':'' ?>><?= htmlspecialchars($s['name']) ?></option><?php endforeach; ?>
            </select>
        </div>
        <div style="flex:1.5;min-width:150px;">
            <label>Source</label>
            <select name="source_id">
                <option value="">All Sources</option>
                <?php foreach($all_sources as $s): ?><option value="<?= $s['id'] ?>" <?= $f_source==$s['id']?'selected':'' ?>><?= htmlspecialchars($s['name']) ?></option><?php endforeach; ?>
            </select>
        </div>
        <div style="display:flex;gap:8px;">
            <button type="submit" class="btn-primary"><i class="fa-solid fa-filter"></i> Apply</button>
            <a href="reports.php" class="btn-primary" style="background:#f1f5f9;color:#64748b;"><i class="fa-solid fa-xmark"></i> Reset</a>
        </div>
    </form>
</div>

<!-- Summary Cards -->
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:15px;margin-bottom:25px;">
    <?php
    $cards = [
        ['Assigned Leads', $total,     '#3b82f6', 'fa-users'],
        ['Active Pipeline', $active,    '#f59e0b', 'fa-user-clock'],
        ['Success (Conv)', $converted, '#22c55e', 'fa-handshake'],
        ['Lost Leads',     $lost,      '#ef4444', 'fa-user-minus'],
    ];
    foreach($cards as [$label, $val, $color, $icon]): ?>
    <div class="ag-card" style="padding:20px;text-align:center;">
        <div style="width:40px;height:40px;background:<?=$color?>18;border-radius:10px;display:flex;align-items:center;justify-content:center;margin:0 auto 12px;"><i class="fa-solid <?=$icon?>" style="color:<?=$color?>"></i></div>
        <div style="font-size:1.8rem;font-weight:800;color:<?=$color?>;line-height:1;"><?=$val?></div>
        <div style="font-size:0.75rem;font-weight:700;color:#94a3b8;margin-top:5px;text-transform:uppercase;letter-spacing:0.04em;"><?=$label?></div>
    </div>
    <?php endforeach; ?>
</div>

<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:25px;">
    <!-- Pipeline Bar Chart -->
    <div class="ag-card" style="padding:22px;">
        <h3 style="margin:0 0 18px;font-size:0.95rem;color:#0f172a;"><i class="fa-solid fa-diagram-project" style="color:#3b82f6;margin-right:8px;"></i> Pipeline Distribution</h3>
        <?php if(empty($by_stage)): ?><p style="padding:20px;text-align:center;color:#94a3b8;">No data available.</p>
        <?php else: foreach($by_stage as $row): $pct = round(($row['cnt']/$total_stg)*100); $color = $row['color_code'] ?: '#64748b'; ?>
            <div style="margin-bottom:14px;">
                <div style="display:flex;justify-content:space-between;margin-bottom:5px;font-size:0.85rem;font-weight:600;">
                    <span style="display:flex;align-items:center;gap:6px;"><div style="width:8px;height:8px;border-radius:50%;background:<?=$color?>"></div> <?=htmlspecialchars($row['name'])?></span>
                    <span><?=$row['cnt']?></span>
                </div>
                <div style="background:#f1f5f9;border-radius:10px;height:8px;"><div style="background:<?=$color?>;width:<?=$pct?>%;height:100%;border-radius:10px;"></div></div>
            </div>
        <?php endforeach; endif; ?>
    </div>

    <!-- Lead Source -->
    <div class="ag-card" style="padding:22px;">
        <h3 style="margin:0 0 18px;font-size:0.95rem;color:#0f172a;"><i class="fa-solid fa-share-nodes" style="color:#22c55e;margin-right:8px;"></i> Top Yielding Sources</h3>
        <?php if(empty($by_source)): ?><p style="padding:20px;text-align:center;color:#94a3b8;">No data available.</p>
        <?php else: 
        $colors = ['#22c55e','#3b82f6','#8b5cf6','#f59e0b'];
        foreach($by_source as $i => $row): $pct = round(($row['cnt']/$total_src)*100); $color = $colors[$i % count($colors)]; ?>
            <div style="margin-bottom:14px;">
                <div style="display:flex;justify-content:space-between;margin-bottom:5px;font-size:0.85rem;font-weight:600;">
                    <span><?=htmlspecialchars($row['name'])?></span>
                    <span><?=$row['cnt']?></span>
                </div>
                <div style="background:#f1f5f9;border-radius:10px;height:8px;"><div style="background:<?=$color?>;width:<?=$pct?>%;height:100%;border-radius:10px;"></div></div>
            </div>
        <?php endforeach; endif; ?>
    </div>
</div>

<div class="ag-card" style="padding:22px;">
    <h3 style="margin:0 0 15px;font-size:0.95rem;color:#0f172a;"><i class="fa-solid fa-calendar-day" style="color:#f59e0b;margin-right:8px;"></i> Daily Acquisition Trend</h3>
    <div style="display:flex;align-items:flex-end;gap:5px;height:120px;margin-top:20px;">
        <?php if(empty($daily_map)): ?><p style="flex:1;text-align:center;color:#94a3b8;padding-bottom:20px;">No leads found in this range.</p>
        <?php else: foreach($daily_map as $day => $cnt): $h = ($cnt/$max_day)*100; ?>
            <div style="flex:1;background:var(--primary);height:<?=$h?>%;border-radius:4px 4px 0 0;min-width:8px;position:relative;" title="<?=date('d M', strtotime($day))?>: <?=$cnt?> leads"></div>
        <?php endforeach; endif; ?>
    </div>
</div>

<style>
@media (max-width: 768px) {
    div[style*="grid-template-columns: 1fr 1fr"] { grid-template-columns: 1fr !important; }
}
</style>

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