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

// Fetch all agents with aggregated stats
$agents = $pdo->query("
    SELECT
        a.*,
        COUNT(DISTINCT l.id)     AS total_leads,
        SUM(CASE WHEN l.is_junk=0 AND st.name NOT IN ('Converted','Lost') THEN 1 ELSE 0 END) AS active_leads,
        SUM(CASE WHEN l.is_junk=0 AND st.name='Converted' THEN 1 ELSE 0 END)                 AS converted_leads,
        COUNT(DISTINCT m.id)     AS total_meetings,
        COUNT(DISTINCT f.id)     AS total_followups,
        SUM(CASE WHEN f.status='pending' AND f.followup_date >= NOW() THEN 1 ELSE 0 END)     AS upcoming_followups,
        SUM(CASE WHEN f.status='pending' AND f.followup_date < NOW()  THEN 1 ELSE 0 END)     AS missed_followups
    FROM sales_agents a
    LEFT JOIN leads l       ON l.assigned_agent_id = a.id
    LEFT JOIN lead_statuses st ON l.status_id = st.id
    LEFT JOIN meetings m    ON m.lead_id = l.id
    LEFT JOIN lead_followups f ON f.lead_id = l.id
    GROUP BY a.id
    ORDER BY total_leads DESC, a.name ASC
")->fetchAll();

// Summary totals
$totals = [
    'agents'       => count($agents),
    'active_agents'=> array_sum(array_column($agents,'is_active')),
    'total_leads'  => array_sum(array_column($agents,'total_leads')),
    'converted'    => array_sum(array_column($agents,'converted_leads')),
    'meetings'     => array_sum(array_column($agents,'total_meetings')),
    'upcoming'     => array_sum(array_column($agents,'upcoming_followups')),
    'missed'       => array_sum(array_column($agents,'missed_followups')),
];

// Recent leads for each agent (last 5 per agent)
$recent_leads_by_agent = [];
if (!empty($agents)) {
    foreach ($agents as $ag) {
        $rl = $pdo->prepare("
            SELECT l.id, l.phone, l.name, l.created_at, st.name as stage, st.color_code
            FROM leads l
            LEFT JOIN lead_statuses st ON l.status_id = st.id
            WHERE l.assigned_agent_id = ? AND l.is_junk = 0
            ORDER BY l.created_at DESC LIMIT 5
        ");
        $rl->execute([$ag['id']]);
        $recent_leads_by_agent[$ag['id']] = $rl->fetchAll();
    }
}
?>

<div class="dashboard-content">

    <!-- Header -->
    <div class="welcome-banner" style="margin-bottom:24px; padding:24px; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:12px;">
        <div>
            <h2 style="margin-bottom:4px;"><i class="fa-solid fa-user-tie"></i> Sales Agents Dashboard</h2>
            <p>Live overview of all agents, their lead counts, meetings and follow-ups.</p>
        </div>
        <a href="sales_agents.php" style="background:#fff; color:var(--primary); padding:10px 20px; border-radius:8px; font-weight:700; text-decoration:none; display:inline-flex; align-items:center; gap:8px;">
            <i class="fa-solid fa-gear"></i> Manage Agents
        </a>
    </div>

    <!-- Summary KPI Cards -->
    <div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(150px,1fr)); gap:16px; margin-bottom:28px;">
        <?php
        $kpis = [
            ['fa-user-tie',       '#3b82f6', 'Total Agents',     $totals['agents']],
            ['fa-circle-check',   '#22c55e', 'Active Agents',    $totals['active_agents']],
            ['fa-users',          '#8b5cf6', 'Assigned Leads',   $totals['total_leads']],
            ['fa-trophy',         '#f59e0b', 'Converted',        $totals['converted']],
            ['fa-calendar-check', '#06b6d4', 'Meetings',         $totals['meetings']],
            ['fa-bell',           '#ef4444', 'Missed Follow-ups',$totals['missed']],
        ];
        foreach ($kpis as [$icon, $color, $label, $val]):
        ?>
        <div style="background:#fff; border:2px solid #e2e8f0; border-radius:14px; padding:20px 18px; display:flex; flex-direction:column; gap:8px;">
            <div style="width:40px; height:40px; background:<?= $color ?>15; border-radius:10px; display:flex; align-items:center; justify-content:center;">
                <i class="fa-solid <?= $icon ?>" style="color:<?= $color ?>; font-size:1.1rem;"></i>
            </div>
            <div style="font-size:1.8rem; font-weight:800; color:var(--dark); line-height:1;"><?= $val ?></div>
            <div style="font-size:0.78rem; font-weight:700; color:#94a3b8; text-transform:uppercase; letter-spacing:0.05em;"><?= $label ?></div>
        </div>
        <?php endforeach; ?>
    </div>

    <?php if (empty($agents)): ?>
        <div style="background:#fff; border:2px solid #e2e8f0; border-radius:14px; padding:60px; text-align:center; color:#94a3b8;">
            <i class="fa-solid fa-user-tie" style="font-size:3rem; color:#e2e8f0; display:block; margin-bottom:16px;"></i>
            <p style="font-size:1.1rem; font-weight:600;">No sales agents yet.</p>
            <a href="sales_agents.php" style="display:inline-block; margin-top:12px; background:var(--primary); color:#fff; padding:10px 24px; border-radius:8px; font-weight:700; text-decoration:none;">+ Create First Agent</a>
        </div>
    <?php else: ?>

        <!-- Per-Agent Cards Grid -->
        <div style="display:grid; grid-template-columns:repeat(auto-fill,minmax(340px,1fr)); gap:20px;">
        <?php foreach ($agents as $ag): ?>
            <div style="background:#fff; border:2px solid #e2e8f0; border-radius:14px; overflow:hidden;">

                <!-- Agent Header -->
                <div style="background:linear-gradient(135deg,#1e293b 0%,#334155 100%); padding:20px 22px; display:flex; align-items:center; gap:14px;">
                    <div style="width:48px; height:48px; border-radius:50%; background:rgba(255,255,255,0.15); display:flex; align-items:center; justify-content:center; font-size:1.3rem; color:#fff; font-weight:800; flex-shrink:0;">
                        <?= strtoupper(substr($ag['name'],0,1)) ?>
                    </div>
                    <div style="flex:1; min-width:0;">
                        <div style="font-weight:800; color:#fff; font-size:1.05rem; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;"><?= htmlspecialchars($ag['name']) ?></div>
                        <div style="font-size:0.8rem; color:#94a3b8; margin-top:2px;"><?= htmlspecialchars($ag['designation'] ?? 'Sales Agent') ?></div>
                    </div>
                    <span style="background:<?= $ag['is_active'] ? '#22c55e' : '#ef4444' ?>25; color:<?= $ag['is_active'] ? '#22c55e' : '#ef4444' ?>; padding:4px 10px; border-radius:14px; font-size:0.75rem; font-weight:700; flex-shrink:0;">
                        <?= $ag['is_active'] ? 'Active' : 'Inactive' ?>
                    </span>
                </div>

                <!-- Contact Info -->
                <?php if(!empty($ag['phone']) || !empty($ag['email'])): ?>
                <div style="padding:10px 22px; background:#f8fafc; border-bottom:1px solid #e2e8f0; display:flex; gap:16px; flex-wrap:wrap;">
                    <?php if(!empty($ag['phone'])): ?>
                        <a href="tel:<?= htmlspecialchars($ag['phone']) ?>" style="display:inline-flex; align-items:center; gap:5px; font-size:0.82rem; color:#475569; text-decoration:none; font-weight:600;">
                            <i class="fa-solid fa-phone" style="color:#94a3b8; width:14px;"></i><?= htmlspecialchars($ag['phone']) ?>
                        </a>
                    <?php endif; ?>
                    <?php if(!empty($ag['email'])): ?>
                        <a href="mailto:<?= htmlspecialchars($ag['email']) ?>" style="display:inline-flex; align-items:center; gap:5px; font-size:0.82rem; color:#475569; text-decoration:none; font-weight:600;">
                            <i class="fa-solid fa-envelope" style="color:#94a3b8; width:14px;"></i><?= htmlspecialchars($ag['email']) ?>
                        </a>
                    <?php endif; ?>
                </div>
                <?php endif; ?>

                <!-- Stats Grid -->
                <div style="display:grid; grid-template-columns:repeat(3,1fr); gap:0; border-bottom:1px solid #e2e8f0;">
                    <?php
                    $stats = [
                        ['fa-users',         '#3b82f6', 'Leads',     $ag['total_leads']],
                        ['fa-fire',          '#f59e0b', 'Active',    $ag['active_leads']],
                        ['fa-trophy',        '#22c55e', 'Converted', $ag['converted_leads']],
                        ['fa-calendar',      '#8b5cf6', 'Meetings',  $ag['total_meetings']],
                        ['fa-clock',         '#06b6d4', 'Upcoming',  $ag['upcoming_followups']],
                        ['fa-triangle-exclamation','#ef4444','Missed',$ag['missed_followups']],
                    ];
                    foreach ($stats as $i => [$icon,$color,$label,$val]):
                    ?>
                    <div style="padding:14px 12px; text-align:center; <?= ($i%3 !== 2) ? 'border-right:1px solid #e2e8f0;' : '' ?> <?= ($i >= 3) ? 'border-top:1px solid #e2e8f0;' : '' ?>">
                        <div style="font-size:1.4rem; font-weight:800; color:<?= $color ?>;"><?= $val ?></div>
                        <div style="font-size:0.7rem; font-weight:700; color:#94a3b8; text-transform:uppercase; margin-top:2px; display:flex; align-items:center; justify-content:center; gap:4px;">
                            <i class="fa-solid <?= $icon ?>" style="font-size:0.65rem;"></i><?= $label ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>

                <!-- Recent Leads -->
                <?php $rl = $recent_leads_by_agent[$ag['id']] ?? []; ?>
                <div style="padding:14px 22px;">
                    <div style="font-size:0.75rem; font-weight:800; color:#94a3b8; text-transform:uppercase; letter-spacing:0.06em; margin-bottom:10px;">Recent Leads</div>
                    <?php if(empty($rl)): ?>
                        <p style="color:#cbd5e1; font-size:0.85rem; margin:0;">No leads assigned yet.</p>
                    <?php else: ?>
                        <?php foreach($rl as $lead): ?>
                        <div style="display:flex; align-items:center; justify-content:space-between; padding:7px 0; border-bottom:1px solid #f1f5f9;">
                            <div>
                                <a href="lead_view.php?id=<?= $lead['id'] ?>" style="font-weight:700; color:var(--dark); font-size:0.88rem; text-decoration:none;"><?= htmlspecialchars($lead['phone']) ?></a>
                                <?php if(!empty($lead['name'])): ?>
                                    <div style="font-size:0.75rem; color:#94a3b8;"><?= htmlspecialchars($lead['name']) ?></div>
                                <?php endif; ?>
                            </div>
                            <?php if($lead['stage']): ?>
                                <span style="background:<?= htmlspecialchars($lead['color_code']) ?>20; color:<?= htmlspecialchars($lead['color_code']) ?>; padding:3px 9px; border-radius:10px; font-size:0.72rem; font-weight:700;">
                                    <?= htmlspecialchars($lead['stage']) ?>
                                </span>
                            <?php endif; ?>
                        </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>

                <!-- Actions -->
                <div style="padding:14px 22px; background:#f8fafc; border-top:1px solid #e2e8f0; display:flex; gap:8px;">
                    <a href="leads.php?agent_id=<?= $ag['id'] ?>" style="flex:1; display:inline-flex; align-items:center; justify-content:center; gap:6px; padding:9px; background:var(--primary); color:#fff; border-radius:8px; font-weight:700; font-size:0.85rem; text-decoration:none;">
                        <i class="fa-solid fa-list"></i> View Leads
                    </a>
                    <a href="sales_agents.php?edit=<?= $ag['id'] ?>" style="padding:9px 14px; background:#e0f2fe; color:var(--primary); border-radius:8px; font-weight:700; font-size:0.85rem; text-decoration:none; display:inline-flex; align-items:center; gap:5px;">
                        <i class="fa-solid fa-pen"></i> Edit
                    </a>
                </div>
            </div>
        <?php endforeach; ?>
        </div>

    <?php endif; ?>
</div>

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