<?php
// admin-report-dashboard.php
ini_set('display_errors', 0);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log');

session_start();
require_once '../config/config.php';

// === SECURITY: Must be admin ===
if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'admin') {
    header('Location: ../login.php'); exit;
}

// === IMPERSONATION DETECTION ===
$impersonating = false;
$company_id = null;
$url_param = '';
if (isset($_GET['id'])) {
    $imp_id = (int)$_GET['id'];
    $stmt = $conn->prepare("SELECT id, company_name FROM companies WHERE id = ?");
    $stmt->bind_param('i', $imp_id);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res->num_rows === 1) {
        $row = $res->fetch_assoc();
        $company_id = $imp_id;
        $impersonating = true;
        $url_param = "id=$company_id";
        $page_title = "Reports: " . htmlspecialchars($row['company_name']);
    }
    $stmt->close();
}
if (!$impersonating) {
    $page_title = "Global Reports Dashboard";
    $url_param = '';
}

// === DATE FILTER ===
$start = $_GET['start'] ?? date('Y-m-01'); // first day of current month
$end   = $_GET['end'] ?? date('Y-m-d');
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $start)) $start = date('Y-m-01');
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $end)) $end = date('Y-m-d');

// === BUILD WHERE CLAUSE ===
$where = $impersonating ? "WHERE l.company_id = ?" : "";
$date_clause = "WHERE DATE(l.created_at) BETWEEN ? AND ?";
$params = [$start, $end];
$types = 'ss';
if ($impersonating) {
    $where = "WHERE l.company_id = ? AND DATE(l.created_at) BETWEEN ? AND ?";
    $params = [$company_id, $start, $end];
    $types = 'iss';
}

// === GLOBAL STATS ===
$stats = [];
$stat_queries = [
    'total_leads' => "SELECT COUNT(*) FROM leads l $date_clause",
    'converted'   => "SELECT COUNT(*) FROM leads l $date_clause AND l.converted = 1",
    'pending'     => "SELECT COUNT(*) FROM leads l $date_clause AND l.converted = 0",
    'companies'   => "SELECT COUNT(DISTINCT l.company_id) FROM leads l $date_clause"
];
foreach ($stat_queries as $key => $sql) {
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $stmt->bind_result($val);
    $stmt->fetch();
    $stats[$key] = $val ?? 0;
    $stmt->close();
}
$conversion_rate = $stats['total_leads'] > 0 ? round(($stats['converted'] / $stats['total_leads']) * 100, 1) : 0;

// === LEADS BY COMPANY (FOR PIE CHART) ===
$company_leads = [];
$sql = "SELECT c.company_name, COUNT(l.id) AS leads 
        FROM companies c 
        LEFT JOIN leads l ON c.id = l.company_id AND DATE(l.created_at) BETWEEN ? AND ?
        $where
        GROUP BY c.id 
        ORDER BY leads DESC 
        LIMIT 10";
$stmt = $conn->prepare($sql);
if ($impersonating) {
    $stmt->bind_param('issi', $start, $end, $company_id, $company_id);
} else {
    $stmt->bind_param('ss', $start, $end);
}
$stmt->execute();
$res = $stmt->get_result();
while ($row = $res->fetch_assoc()) {
    $company_leads[] = $row;
}
$stmt->close();

// === MONTHLY TREND (LAST 6 MONTHS) ===
$trend = [];
$months = [];
for ($i = 5; $i >= 0; $i--) {
    $m = date('Y-m', strtotime("-$i months"));
    $months[] = date('M Y', strtotime("-$i months"));
    $trend[$m] = ['leads' => 0, 'converted' => 0];
}
$sql = "SELECT DATE_FORMAT(l.created_at, '%Y-%m') AS month, 
               COUNT(*) AS leads, 
               SUM(CASE WHEN l.converted = 1 THEN 1 ELSE 0 END) AS converted
        FROM leads l 
        $where
        GROUP BY month 
        HAVING month >= DATE_FORMAT(DATE_SUB(?, INTERVAL 5 MONTH), '%Y-%m')";
$stmt = $conn->prepare($sql);
$base = date('Y-m-01');
if ($impersonating) {
    $stmt->bind_param('is', $company_id, $base);
} else {
    $stmt->bind_param('s', $base);
}
$stmt->execute();
$res = $stmt->get_result();
while ($row = $res->fetch_assoc()) {
    if (isset($trend[$row['month']])) {
        $trend[$row['month']] = ['leads' => (int)$row['leads'], 'converted' => (int)$row['converted']];
    }
}
$stmt->close();

// === EXPORT CSV ===
if (isset($_GET['export'])) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="report_' . ($impersonating ? $company_id : 'global') . '_'.date('Ymd').'.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['Company', 'Total Leads', 'Converted', 'Pending', 'Conversion %']);
    foreach ($company_leads as $c) {
        $total = $c['leads'];
        $conv = 0;
        $stmt = $conn->prepare("SELECT COUNT(*) FROM leads WHERE company_id = (SELECT id FROM companies WHERE company_name = ?) AND converted = 1 AND DATE(created_at) BETWEEN ? AND ?");
        $stmt->bind_param('sss', $c['company_name'], $start, $end);
        $stmt->execute();
        $stmt->bind_result($conv);
        $stmt->fetch();
        $stmt->close();
        $rate = $total > 0 ? round(($conv / $total) * 100, 1) : 0;
        fputcsv($out, [$c['company_name'], $total, $conv, $total - $conv, $rate . '%']);
    }
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $page_title ?> - Reports</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        :root {
            --primary:#7c3aed;--primary-light:#8b5cf6;--secondary:#06b6d4;--success:#10b981;
            --warning:#f59e0b;--danger:#ef4444;--dark:#0f172a;--darker:#020617;--card-bg:rgba(255,255,255,0.08);
            --border:rgba(255,255,255,0.1);--text:#f1f5f9;--text-light:#cbd5e1;--radius:1rem;--radius-sm:.75rem;
            --transition:all .3s ease;
        }
        *{margin:0;padding:0;box-sizing:border-box;}
        body{font-family:'Inter',sans-serif;background:linear-gradient(135deg,var(--darker),var(--dark));
            color:var(--text);min-height:100vh;}
        .background{position:fixed;top:0;left:0;width:100%;height:100%;z-index:-1;overflow:hidden;}
        .gradient-orb{position:absolute;border-radius:50%;filter:blur(80px);opacity:.3;
            animation:float 25s ease-in-out infinite;}
        .orb-1{width:500px;height:500px;background:linear-gradient(45deg,var(--primary),var(--secondary));top:-200px;left:-200px;}
        .orb-2{width:400px;height:400px;background:linear-gradient(45deg,var(--secondary),var(--success));bottom:-150px;right:-150px;animation-delay:-8s;}
        @keyframes float{0%,100%{transform:translate(0,0) scale(1);}25%{transform:translate(100px,100px) scale(1.1);}
            50%{transform:translate(0,200px) scale(.9);}75%{transform:translate(-100px,100px) scale(1.05);}}
        .container{max-width:1400px;margin:0 auto;padding:2rem;}
        .header{text-align:center;margin-bottom:3rem;}
        .header h1{font-size:2.8rem;font-weight:700;background:linear-gradient(135deg,var(--text),var(--primary-light));
            -webkit-background-clip:text;-webkit-text-fill-color:transparent;}
        .filters{display:flex;gap:1rem;flex-wrap:wrap;justify-content:center;margin-bottom:2rem;}
        .filter-input{width:180px;padding:.75rem 1rem;background:var(--card-bg);border:1px solid var(--border);
            border-radius:var(--radius-sm);color:var(--text);font-size:.95rem;}
        .filter-input:focus{outline:none;border-color:var(--primary-light);box-shadow:0 0 0 3px rgba(124,58,237,.2);}
        .btn{padding:.75rem 1.5rem;border:none;border-radius:var(--radius-sm);font-weight:600;
            cursor:pointer;transition:var(--transition);display:inline-flex;align-items:center;gap:.5rem;}
        .btn-primary{background:linear-gradient(135deg,var(--primary),var(--primary-light));color:white;}
        .btn-success{background:linear-gradient(135deg,var(--success),#34d399);color:white;}
        .btn:hover{transform:translateY(-2px);box-shadow:0 8px 20px rgba(0,0,0,.3);}
        .stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:1.5rem;margin-bottom:3rem;}
        .stat-card{background:var(--card-bg);backdrop-filter:blur(20px);border:1px solid var(--border);
            border-radius:var(--radius);padding:1.8rem;text-align:center;transition:var(--transition);}
        .stat-card:hover{transform:translateY(-5px);border-color:var(--primary-light);}
        .stat-icon{width:60px;height:60px;margin:0 auto 1rem;background:linear-gradient(135deg,var(--primary),var(--primary-light));
            border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:1.6rem;color:white;}
        .stat-value{font-size:2.2rem;font-weight:700;margin:.5rem 0;}
        .stat-label{color:var(--text-light);font-size:.95rem;}
        .chart-container{background:var(--card-bg);backdrop-filter:blur(20px);border:1px solid var(--border);
            border-radius:var(--radius);padding:2rem;margin-bottom:2rem;position:relative;}
        .chart-title{font-size:1.4rem;font-weight:600;margin-bottom:1.5rem;color:var(--text);text-align:center;}
        canvas{height:300px !important;}
        .back-btn{margin-bottom:1.5rem;}
        .back-btn a{background:var(--danger);color:white;}
        @keyframes fadeInUp{from{opacity:0;transform:translateY(20px);}to{opacity:1;transform:translateY(0);}}
        .fade-in-up{opacity:0;animation:fadeInUp .6s ease-out forwards;}
        @media(max-width:768px){
            .filters{flex-direction:column;align-items:center;}
            .filter-input{width:100%;max-width:300px;}
            .stats-grid{grid-template-columns:1fr;}
        }
    </style>
</head>
<body>
<div class="background">
    <div class="gradient-orb orb-1"></div>
    <div class="gradient-orb orb-2"></div>
</div>

<div class="container">

    <!-- Back Button -->
    <?php if ($impersonating): ?>
    <div class="back-btn fade-in-up">
        <a href="admin-dashboard.php" class="btn">Back to Admin Dashboard</a>
    </div>
    <?php endif; ?>

    <div class="header fade-in-up">
        <h1>Reports Dashboard</h1>
        <p><?= $impersonating ? 'Company-specific' : 'Global' ?> analytics from <?= date('M j, Y', strtotime($start)) ?> to <?= date('M j, Y', strtotime($end)) ?></p>
    </div>

    <!-- Date Filter -->
    <form method="GET" class="filters fade-in-up">
        <?php if ($impersonating): ?><input type="hidden" name="id" value="<?= $company_id ?>"><?php endif; ?>
        <input type="date" name="start" class="filter-input" value="<?= $start ?>" required>
        <input type="date" name="end" class="filter-input" value="<?= $end ?>" required>
        <button type="submit" class="btn btn-primary">Apply</button>
        <a href="?<?= $url_param ?>&export=1&start=<?= $start ?>&end=<?= $end ?>" class="btn btn-success">Export CSV</a>
    </form>

    <!-- Stats -->
    <div class="stats-grid">
        <div class="stat-card fade-in-up" style="animation-delay:.1s">
            <div class="stat-icon">Chart Line</div>
            <div class="stat-value"><?= number_format($stats['total_leads']) ?></div>
            <div class="stat-label">Total Leads</div>
        </div>
        <div class="stat-card fade-in-up" style="animation-delay:.2s">
            <div class="stat-icon">Check Circle</div>
            <div class="stat-value"><?= number_format($stats['converted']) ?></div>
            <div class="stat-label">Converted</div>
        </div>
        <div class="stat-card fade-in-up" style="animation-delay:.3s">
            <div class="stat-icon">Clock</div>
            <div class="stat-value"><?= number_format($stats['pending']) ?></div>
            <div class="stat-label">Pending</div>
        </div>
        <div class="stat-card fade-in-up" style="animation-delay:.4s">
            <div class="stat-icon">Arrow Up Right</div>
            <div class="stat-value"><?= $conversion_rate ?>%</div>
            <div class="stat-label">Conversion Rate</div>
        </div>
    </div>

    <!-- Charts -->
    <div class="chart-container fade-in-up" style="animation-delay:.5s">
        <div class="chart-title">Leads by Company (Top 10)</div>
        <canvas id="pieChart"></canvas>
    </div>

    <div class="chart-container fade-in-up" style="animation-delay:.6s">
        <div class="chart-title">Monthly Lead Trend (Last 6 Months)</div>
        <canvas id="lineChart"></canvas>
    </div>
</div>

<script>
    // Pie Chart
    const pieCtx = document.getElementById('pieChart').getContext('2d');
    new Chart(pieCtx, {
        type: 'doughnut',
        data: {
            labels: <?= json_encode(array_column($company_leads, 'company_name')) ?>,
            datasets: [{
                data: <?= json_encode(array_column($company_leads, 'leads')) ?>,
                backgroundColor: [
                    '#7c3aed', '#8b5cf6', '#06b6d4', '#10b981', '#f59e0b',
                    '#ef4444', '#ec4899', '#6366f1', '#14b8a6', '#f97316'
                ],
                borderWidth: 0,
                borderRadius: 8
            }]
        },
        options: {
            responsive: true,
            plugins: { legend: { position: 'bottom', labels: { color: '#cbd5e1', padding: 20 } } },
            animation: { duration: 1500 }
        }
    });

    // Line Chart
    const lineCtx = document.getElementById('lineChart').getContext('2d');
    const months = <?= json_encode($months) ?>;
    const leads = months.map(m => {
        const key = m.replace(' ', '-').slice(0,7);
        const found = Object.keys(<?= json_encode($trend) ?>).find(k => k === key.split('-').join('-'));
        return found ? <?= json_encode($trend) ?>[found].leads : 0;
    });
    const converted = months.map(m => {
        const key = m.replace(' ', '-').slice(0,7);
        const found = Object.keys(<?= json_encode($trend) ?>).find(k => k === key.split('-').join('-'));
        return found ? <?= json_encode($trend) ?>[found].converted : 0;
    });

    new Chart(lineCtx, {
        type: 'line',
        data: {
            labels: months,
            datasets: [
                {
                    label: 'Total Leads',
                    data: leads,
                    borderColor: '#7c3aed',
                    backgroundColor: 'rgba(124,58,237,0.1)',
                    tension: 0.4,
                    fill: true
                },
                {
                    label: 'Converted',
                    data: converted,
                    borderColor: '#10b981',
                    backgroundColor: 'rgba(16,185,129,0.1)',
                    tension: 0.4,
                    fill: true
                }
            ]
        },
        options: {
            responsive: true,
            plugins: { legend: { position: 'top' } },
            scales: { y: { beginAtZero: true, grid: { color: 'rgba(255,255,255,0.05)' } } }
        }
    });
</script>
</body>
</html>