<?php
session_start();
require_once 'config/db.php';

// Authentication Check
if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit;
}

// Date Filter Logic
$date_from = $_GET['date_from'] ?? date('Y-m-d', strtotime('-30 days'));
$date_to   = $_GET['date_to']   ?? date('Y-m-d');

// Helper for date params
$date_params = [$date_from . ' 00:00:00', $date_to . ' 23:59:59'];

// --- GET METRICS ---

// 1. Agent Stats (Master)
$total_agents    = $pdo->query("SELECT COUNT(*) FROM sales_agents")->fetchColumn();
$active_agents   = $pdo->query("SELECT COUNT(*) FROM sales_agents WHERE is_active = 1")->fetchColumn();
$inactive_agents = $pdo->query("SELECT COUNT(*) FROM sales_agents WHERE is_active = 0")->fetchColumn();

// 2. Lead Stats (Master)
$global_total_leads = $pdo->query("SELECT COUNT(*) FROM leads WHERE is_junk = 0")->fetchColumn();
$unassigned_leads   = $pdo->query("SELECT COUNT(*) FROM leads WHERE assigned_agent_id IS NULL AND is_junk = 0")->fetchColumn();

// 3. Converted Customers (Master)
$total_conversions_stmt = $pdo->prepare("SELECT COUNT(*) FROM leads WHERE status_id = (SELECT id FROM lead_statuses WHERE name = 'Converted' LIMIT 1) AND created_at BETWEEN ? AND ? AND is_junk = 0");
$total_conversions_stmt->execute($date_params);
$converted_leads = $total_conversions_stmt->fetchColumn();

$global_converted = $pdo->query("SELECT COUNT(*) FROM leads WHERE status_id = (SELECT id FROM lead_statuses WHERE name = 'Converted' LIMIT 1) AND is_junk = 0")->fetchColumn();

// 4. Enquiry Stats (Master)
$total_enquiries_stmt = $pdo->prepare("SELECT COUNT(*) FROM enquiries WHERE created_at BETWEEN ? AND ?");
$total_enquiries_stmt->execute($date_params);
$total_enquiries = $total_enquiries_stmt->fetchColumn();

$enq_to_leads = $pdo->prepare("SELECT COUNT(*) FROM enquiries WHERE status = 'converted' AND created_at BETWEEN ? AND ?");
$enq_to_leads->execute($date_params);
$enq_to_leads = $enq_to_leads->fetchColumn();

$junk_enquiries = $pdo->prepare("SELECT COUNT(*) FROM enquiries WHERE status = 'junk' AND created_at BETWEEN ? AND ?");
$junk_enquiries->execute($date_params);
$junk_enquiries = $junk_enquiries->fetchColumn();

// 5. Meeting Stats (Master)
$total_meetings_stmt = $pdo->prepare("SELECT COUNT(*) FROM meetings WHERE created_at BETWEEN ? AND ?");
$total_meetings_stmt->execute($date_params);
$total_meetings = $total_meetings_stmt->fetchColumn();

$completed_meetings_stmt = $pdo->prepare("SELECT COUNT(*) FROM meetings WHERE status = 'completed' AND created_at BETWEEN ? AND ?");
$completed_meetings_stmt->execute($date_params);
$completed_meetings = $completed_meetings_stmt->fetchColumn();

// --- DATA FOR CHARTS ---
$status_pipeline_stmt = $pdo->prepare("
    SELECT s.name, (SELECT COUNT(*) FROM leads l WHERE l.status_id = s.id AND l.created_at BETWEEN ? AND ? AND l.is_junk = 0) as count 
    FROM lead_statuses s
");
$status_pipeline_stmt->execute($date_params);
$status_pipeline = $status_pipeline_stmt->fetchAll();

$source_distribution_stmt = $pdo->prepare("
    SELECT src.name, COUNT(l.id) as count
    FROM lead_sources src
    LEFT JOIN leads l ON l.source_id = src.id AND l.created_at BETWEEN ? AND ? AND l.is_junk = 0
    GROUP BY src.id, src.name
");
$source_distribution_stmt->execute($date_params);
$source_distribution = $source_distribution_stmt->fetchAll();

// --- TABLES DATA ---
$agent_monitoring = $pdo->query("
    SELECT a.*, 
    (SELECT COUNT(*) FROM leads WHERE assigned_agent_id = a.id AND is_junk = 0) as total_leads,
    (SELECT COUNT(*) FROM leads WHERE assigned_agent_id = a.id AND status_id = (SELECT id FROM lead_statuses WHERE name = 'Converted' LIMIT 1)) as conversions
    FROM sales_agents a ORDER BY a.is_active DESC, conversions DESC
")->fetchAll();

$all_followups = $pdo->query("
    SELECT f.*, l.name as lead_name, l.phone as lead_phone, s.name as status_name
    FROM lead_followups f JOIN leads l ON f.lead_id = l.id LEFT JOIN lead_statuses s ON l.status_id = s.id
    WHERE f.status = 'pending' ORDER BY f.followup_date ASC LIMIT 10
")->fetchAll();

$completed_activity = $pdo->query("
    SELECT f.*, l.name as lead_name, l.phone as lead_phone, a.name as agent_name
    FROM lead_followups f JOIN leads l ON f.lead_id = l.id LEFT JOIN sales_agents a ON l.assigned_agent_id = a.id
    WHERE f.status = 'done' ORDER BY f.completed_at DESC LIMIT 10
")->fetchAll();

$unassigned_list = $pdo->query("SELECT * FROM leads WHERE assigned_agent_id IS NULL AND is_junk = 0 ORDER BY created_at DESC LIMIT 10")->fetchAll();

require_once 'includes/header.php';
?>

<div class="dashboard-content">
    
    <!-- Top Bar -->
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; flex-wrap: wrap; gap: 20px;">
        <div>
            <h2 style="font-weight: 800; color: var(--dark);">Intelligence Dashboard</h2>
            <p style="color: #64748b;">Complete business monitoring console.</p>
        </div>
        
        <form action="index.php" method="GET" style="display: flex; gap: 10px; background: #fff; padding: 10px; border-radius: 12px; border: 2px solid var(--border); box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05);">
            <div style="display: flex; align-items: center; gap: 8px;">
                <label style="font-size: 0.75rem; font-weight: 700; color: #94a3b8; text-transform: uppercase;">From</label>
                <input type="date" name="date_from" value="<?= $date_from ?>" style="padding: 6px 10px; border: 1px solid #e2e8f0; border-radius: 6px; font-size: 0.85rem;">
            </div>
            <div style="display: flex; align-items: center; gap: 8px;">
                <label style="font-size: 0.75rem; font-weight: 700; color: #94a3b8; text-transform: uppercase;">To</label>
                <input type="date" name="date_to" value="<?= $date_to ?>" style="padding: 6px 10px; border: 1px solid #e2e8f0; border-radius: 6px; font-size: 0.85rem;">
            </div>
            <button type="submit" style="background: var(--primary); color: #fff; border: none; padding: 0 15px; border-radius: 6px; font-weight: 700; cursor: pointer; transition: 0.3s;"><i class="fa-solid fa-sync"></i></button>
        </form>
    </div>

    <!-- MASTER WIDGETS (6 Cards Row) -->
    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 15px; margin-bottom: 30px;">
        <div class="premium-card" style="border-top: 4px solid #3b82f6;">
            <div class="p-card-info">
                <h4>Total Agents</h4>
                <div class="p-card-value"><?= $total_agents ?></div>
                <div style="font-size: 0.7rem; color: #64748b; margin-top: 8px;"><?= $active_agents ?> Active / <?= $inactive_agents ?> Inactive</div>
            </div>
        </div>
        <div class="premium-card" style="border-top: 4px solid #10b981;">
            <div class="p-card-info">
                <h4>Total Leads</h4>
                <div class="p-card-value"><?= $global_total_leads ?></div>
                <div style="font-size: 0.7rem; color: #10b981; font-weight: 700; margin-top: 8px;"><i class="fa-solid fa-clock"></i> Lifetime Global</div>
            </div>
        </div>
        <div class="premium-card" style="border-top: 4px solid #f59e0b;">
            <div class="p-card-info">
                <h4>Converted</h4>
                <div class="p-card-value"><?= $global_converted ?></div>
                <div style="font-size: 0.7rem; color: #d97706; font-weight: 700; margin-top: 8px;">Success: <?= $converted_leads ?> in period</div>
            </div>
        </div>
        <div class="premium-card" style="border-top: 4px solid #ef4444;">
            <div class="p-card-info">
                <h4>Unassigned</h4>
                <div class="p-card-value" style="color:#ef4444;"><?= $unassigned_leads ?></div>
                <div style="font-size: 0.7rem; color: #64748b; margin-top: 8px;">Waiting for assignment</div>
            </div>
        </div>
        <div class="premium-card" style="border-top: 4px solid #8b5cf6;">
            <div class="p-card-info">
                <h4>Meetings</h4>
                <div class="p-card-value"><?= $total_meetings ?></div>
                <div style="font-size: 0.7rem; color: #64748b; margin-top: 8px;">Completed: <?= $completed_meetings ?> in period</div>
            </div>
        </div>
        <div class="premium-card" style="border-top: 4px solid #06b6d4;">
            <div class="p-card-info">
                <h4>Enquiries</h4>
                <div class="p-card-value"><?= $total_enquiries ?></div>
                <div style="font-size: 0.7rem; color: #64748b; margin-top: 8px;">C: <?= $enq_to_leads ?> / J: <?= $junk_enquiries ?></div>
            </div>
        </div>
    </div>

    <!-- CHARTS ROW -->
    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 25px; margin-bottom: 40px;" class="stackable">
        <div class="data-card" style="padding: 25px;">
            <h3 style="margin-bottom: 20px; font-weight: 800; border-bottom: 2px solid var(--border); padding-bottom: 12px;"><i class="fa-solid fa-chart-column" style="margin-right: 8px; color: var(--primary);"></i> Pipeline Heatmap (By Status)</h3>
            <div style="height: 320px; position: relative;">
                <canvas id="pipelineHeatmap"></canvas>
            </div>
        </div>
        <div class="data-card" style="padding: 25px;">
            <h3 style="margin-bottom: 20px; font-weight: 800; border-bottom: 2px solid var(--border); padding-bottom: 12px;"><i class="fa-solid fa-chart-pie" style="margin-right: 8px; color: var(--primary);"></i> Lead Source Distribution</h3>
            <div style="height: 320px; position: relative;">
                <canvas id="sourceDistribution"></canvas>
            </div>
        </div>
    </div>

    <!-- GRANULAR TABLES (The 4 Requested Tables) -->
    
    <!-- Row 1: Agents & Unassigned -->
    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 25px; margin-bottom: 30px;" class="stackable">
        <div class="data-card">
            <div class="table-header" style="background: #f8fafc;">
                <h3><i class="fa-solid fa-user-tie"></i> Agent Monitoring (Wigent Table)</h3>
                <a href="sales_agents.php" class="lite-btn">Full List</a>
            </div>
            <div class="table-responsive">
                <table class="admin-table">
                    <thead><tr><th>Agent</th><th>Status</th><th style="text-align: right;">Sales</th></tr></thead>
                    <tbody>
                        <?php foreach($agent_monitoring as $am): ?>
                        <tr>
                            <td data-label="Agent"><strong><?= htmlspecialchars($am['name']) ?></strong><br><small><?= $am['total_leads'] ?> Leads</small></td>
                            <td data-label="Status"><span class="badge" style="background:<?= $am['is_active'] ? '#dcfce7;color:#15803d;' : '#fee2e2;color:#b91c1c;' ?>"><?= $am['is_active'] ? 'Active' : 'Inactive' ?></span></td>
                            <td data-label="Sales" style="text-align: right;"><span class="badge badge-completed"><?= $am['conversions'] ?></span></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <div class="data-card">
            <div class="table-header" style="background: #fff5f5;">
                <h3 style="color:#991b1b;"><i class="fa-solid fa-user-plus"></i> Unassigned Lead Queue</h3>
                <a href="leads.php?agent_id=none" class="lite-btn">Assign</a>
            </div>
            <div class="table-responsive">
                <table class="admin-table">
                    <thead><tr><th>Lead Contact</th><th>Date</th><th style="text-align: right;">Action</th></tr></thead>
                    <tbody>
                        <?php if($unassigned_list): foreach($unassigned_list as $ul): ?>
                        <tr>
                            <td data-label="Lead Contact"><strong><?= $ul['phone'] ?></strong><br><small><?= htmlspecialchars($ul['name'] ?? 'Contact') ?></small></td>
                            <td data-label="Date" style="font-size:0.8rem;"><?= date('d M', strtotime($ul['created_at'])) ?></td>
                            <td data-label="Action" style="text-align: right;"><a href="lead_view.php?id=<?= $ul['id'] ?>" class="lite-btn" style="background:#3b82f6;color:#fff;">Assign</a></td>
                        </tr>
                        <?php endforeach; else: ?>
                        <tr><td colspan="3" style="text-align:center; padding:30px; color:#94a3b8;">No unassigned leads.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Row 2: Follow-ups & Activity -->
    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 25px;" class="stackable">
        <div class="data-card">
            <div class="table-header" style="background: #fffbeb;">
                <h3 style="color:#92400e;"><i class="fa-solid fa-clock-rotate-left"></i> Followup Leads Table (Pending)</h3>
                <a href="lead_followups.php" class="lite-btn">Calendar</a>
            </div>
            <div class="table-responsive">
                <table class="admin-table">
                    <thead><tr><th>Lead</th><th>Schedule</th><th style="text-align: right;">Stage</th></tr></thead>
                    <tbody>
                        <?php if($all_followups): foreach($all_followups as $af): ?>
                        <tr>
                            <td data-label="Lead"><strong><?= $af['lead_phone'] ?></strong></td>
                            <td data-label="Schedule" style="color:#d97706; font-weight:700; font-size:0.8rem;"><?= date('d M, H:i', strtotime($af['followup_date'])) ?></td>
                            <td data-label="Stage" style="text-align: right; font-size:0.75rem; font-weight:700; color:#64748b;"><?= htmlspecialchars($af['status_name'] ?? 'New') ?></td>
                        </tr>
                        <?php endforeach; else: ?>
                        <tr><td colspan="3" style="text-align:center; padding:30px; color:#94a3b8;">No pending follow-ups.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <div class="data-card">
            <div class="table-header" style="background: #f0fdf4;">
                <h3 style="color:#166534;"><i class="fa-solid fa-circle-check"></i> Followed Leads Table (Completed)</h3>
                <a href="lead_followups.php" class="lite-btn">History</a>
            </div>
            <div class="table-responsive">
                <table class="admin-table">
                    <thead><tr><th>Lead</th><th>Agent</th><th style="text-align: right;">Time</th></tr></thead>
                    <tbody>
                        <?php if($completed_activity): foreach($completed_activity as $ca): ?>
                        <tr>
                            <td data-label="Lead"><strong><?= $ca['lead_phone'] ?></strong></td>
                            <td data-label="Agent"><?= htmlspecialchars($ca['agent_name'] ?? 'System') ?></td>
                            <td data-label="Time" style="text-align: right; color:#16a34a; font-weight:700; font-size:0.8rem;"><?= date('d M', strtotime($ca['completed_at'] ?? $ca['followup_date'])) ?></td>
                        </tr>
                        <?php endforeach; else: ?>
                        <tr><td colspan="3" style="text-align:center; padding:30px; color:#94a3b8;">No recent activity.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

</div>

<!-- CHART.JS CDN -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
document.addEventListener("DOMContentLoaded", function() {
    // 1. Pipeline Heatmap
    const pipelineCtx = document.getElementById('pipelineHeatmap').getContext('2d');
    new Chart(pipelineCtx, {
        type: 'bar',
        data: {
            labels: [<?php foreach($status_pipeline as $sp) echo "'" . addslashes($sp['name']) . "',"; ?>],
            datasets: [{
                label: 'Volume',
                data: [<?php foreach($status_pipeline as $sp) echo $sp['count'] . ","; ?>],
                backgroundColor: '#3b82f6',
                borderRadius: 8,
                barThickness: 40
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: { display: false } },
            scales: { y: { beginAtZero: true, ticks: { precision: 0 } }, x: { grid: { display: false } } }
        }
    });

    // 2. Source Distribution
    const sourceCtx = document.getElementById('sourceDistribution').getContext('2d');
    new Chart(sourceCtx, {
        type: 'doughnut',
        data: {
            labels: [<?php foreach($source_distribution as $sd) echo "'" . addslashes($sd['name']) . "',"; ?>],
            datasets: [{
                data: [<?php foreach($source_distribution as $sd) echo $sd['count'] . ","; ?>],
                backgroundColor: ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#06b6d4', '#6366f1', '#ec4899'],
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { 
                legend: { position: 'right', labels: { boxWidth: 12, font: { weight: 'bold', size: 11 } } }
            },
            cutout: '65%'
        }
    });

});
</script>

<style>
    .premium-card { background: #fff; padding: 25px; border-radius: 18px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); border: 1px solid var(--border); }
    .data-card { background: #fff; border-radius: 20px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); border: 1px solid var(--border); overflow: hidden; }
    .table-header { padding: 18px 25px; border-bottom: 2px solid var(--border); display: flex; justify-content: space-between; align-items: center; }
    .table-header h3 { font-weight: 800; font-size: 1.05rem; margin: 0; }
    
    .p-card-info h4 { font-size: 0.72rem; color: #adb5bd; margin: 0; text-transform: uppercase; letter-spacing: 0.1em; font-weight: 800; }
    .p-card-value { font-size: 2.1rem; font-weight: 900; color: var(--dark); margin-top: 5px; line-height: 1; }

    .lite-btn { padding: 5px 14px; background: #fff; color: #1e293b; border: 1px solid #e2e8f0; border-radius: 6px; text-decoration: none; font-size: 0.72rem; font-weight: 800; transition: 0.2s; }
    .lite-btn:hover { background: var(--primary); color: #fff; border-color: var(--primary); }

    .admin-table th { padding: 15px 25px; font-size: 0.72rem; text-transform: uppercase; color: #94a3b8; border-bottom: 1px solid #f1f5f9; text-align: left; }
    .admin-table td { padding: 15px 25px; border-bottom: 1px solid #f8f9fa; font-size: 0.85rem; }

    @media (max-width: 1100px) { .stackable { grid-template-columns: 1fr !important; } }
    
    @media (max-width: 768px) {
        /* Force compact ROW view — override the global card transform */
        .admin-table, .admin-table thead, .admin-table tbody,
        .admin-table th, .admin-table td, .admin-table tr {
            display: revert !important;
        }
        .admin-table { width:100%; border-collapse:collapse; }
        .admin-table thead tr { position: relative !important; top: auto !important; left: auto !important; }
        .admin-table th, .admin-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;
        }
        .admin-table tr {
            border: none !important;
            border-radius: 0 !important;
            margin-bottom: 0 !important;
            padding: 0 !important;
            box-shadow: none !important;
            display: table-row !important;
        }
        .admin-table td:before { display: none !important; content: none !important; }
        .dashboard-content { padding: 10px !important; }
    }
</style>

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