<?php
session_start();

// 1. SECURITY CHECK
if (($_SESSION['is_admin'] ?? 0) != 1) {
    die("Access Denied. Admins only.");
}

// 2. CONFIGURATION
$property_id = '515929468';
$key_file = __DIR__ . '/service-account.json';

// 3. AUTHENTICATION (The "No-Library" JWT Generator)
function getAccessToken($key_file) {
    if (!file_exists($key_file)) { die("Error: service-account.json is missing."); }
    $jsonKey = json_decode(file_get_contents($key_file), true);

    $header = json_encode(['alg' => 'RS256', 'typ' => 'JWT']);
    $now = time();
    $payload = json_encode([
        'iss' => $jsonKey['client_email'],
        'scope' => 'https://www.googleapis.com/auth/analytics.readonly',
        'aud' => 'https://oauth2.googleapis.com/token',
        'exp' => $now + 3600,
        'iat' => $now
    ]);

    $base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
    $base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));
    $signatureInput = $base64UrlHeader . "." . $base64UrlPayload;

    $signature = '';
    openssl_sign($signatureInput, $signature, $jsonKey['private_key'], 'SHA256');
    $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
    $jwt = $signatureInput . "." . $base64UrlSignature;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://oauth2.googleapis.com/token');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'assertion' => $jwt
    ]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = json_decode(curl_exec($ch), true);
    curl_close($ch);

    return $response['access_token'] ?? null;
}

// 4. API CALL HELPER
function callGA4($endpoint, $data, $token, $property_id) {
    $url = "https://analyticsdata.googleapis.com/v1beta/properties/{$property_id}:{$endpoint}";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $token",
        "Content-Type: application/json"
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = json_decode(curl_exec($ch), true);
    curl_close($ch);
    return $result;
}

// ================= FETCH DATA =================

$token = getAccessToken($key_file);

// --- A. REALTIME PULSE ---
$realtime = callGA4('runRealtimeReport', [
    "metrics" => [ ["name" => "activeUsers"] ]
], $token, $property_id);
$live_users = $realtime['rows'][0]['metricValues'][0]['value'] ?? 0;

// --- B. CORE KPI CARD (6 Metrics) ---
$kpiData = callGA4('runReport', [
    "dateRanges" => [ ["startDate" => "28daysAgo", "endDate" => "today"] ],
    "metrics" => [
        ["name" => "activeUsers"],               // 0
        ["name" => "newUsers"],                  // 1
        ["name" => "engagementRate"],            // 2
        ["name" => "averageSessionDuration"],    // 3
        ["name" => "screenPageViewsPerSession"], // 4 (Depth)
        ["name" => "eventCount"]                 // 5 (Total Interactions)
    ]
], $token, $property_id);

$kpi = $kpiData['rows'][0]['metricValues'] ?? [0,0,0,0,0,0];

$total_users = $kpi[0]['value'] ?? 0;
$new_users   = $kpi[1]['value'] ?? 0;
$returning_users = $total_users - $new_users; // Calc returning
$eng_rate    = round(($kpi[2]['value'] ?? 0) * 100, 1) . '%';
$avg_duration= gmdate("i:s", $kpi[3]['value'] ?? 0);
$views_per_sess = round($kpi[4]['value'] ?? 0, 1);
$total_events = number_format($kpi[5]['value'] ?? 0);

// --- C. TREND CHART (Last 28 Days) ---
$trendData = callGA4('runReport', [
    "dateRanges" => [ ["startDate" => "28daysAgo", "endDate" => "today"] ],
    "dimensions" => [ ["name" => "date"] ],
    "metrics" => [ ["name" => "activeUsers"] ],
    "orderBys" => [ ["dimension" => ["dimensionName" => "date"]] ]
], $token, $property_id);

$trend_labels = [];
$trend_values = [];
if (isset($trendData['rows'])) {
    foreach ($trendData['rows'] as $row) {
        $raw = $row['dimensionValues'][0]['value'];
        $trend_labels[] = substr($raw, 4, 2) . '/' . substr($raw, 6, 2);
        $trend_values[] = $row['metricValues'][0]['value'];
    }
}

// --- D. PEAK HOURS (Heatmap Data) ---
$hourData = callGA4('runReport', [
    "dateRanges" => [ ["startDate" => "28daysAgo", "endDate" => "today"] ],
    "dimensions" => [ ["name" => "hour"] ],
    "metrics" => [ ["name" => "activeUsers"] ],
    "orderBys" => [ ["dimension" => ["dimensionName" => "hour"]] ]
], $token, $property_id);

$hours = array_fill(0, 24, 0); // Init 0-23
if (isset($hourData['rows'])) {
    foreach ($hourData['rows'] as $row) {
        $h = (int)$row['dimensionValues'][0]['value'];
        $hours[$h] = $row['metricValues'][0]['value'];
    }
}

// --- E. TECH STACK (Browsers) ---
$browserData = callGA4('runReport', [
    "dateRanges" => [ ["startDate" => "28daysAgo", "endDate" => "today"] ],
    "dimensions" => [ ["name" => "browser"] ],
    "metrics" => [ ["name" => "activeUsers"] ],
    "limit" => 5
], $token, $property_id);

$browsers = [];
$browser_users = [];
if (isset($browserData['rows'])) {
    foreach ($browserData['rows'] as $row) {
        $browsers[] = $row['dimensionValues'][0]['value'];
        $browser_users[] = $row['metricValues'][0]['value'];
    }
}

// --- F. TOP PAGES & SOURCES ---
// Fetching Pages
$pagesData = callGA4('runReport', [
    "dateRanges" => [ ["startDate" => "28daysAgo", "endDate" => "today"] ],
    "dimensions" => [ ["name" => "pageTitle"] ],
    "metrics" => [ ["name" => "screenPageViews"] ],
    "limit" => 6
], $token, $property_id);

$top_pages = [];
if (isset($pagesData['rows'])) {
    foreach ($pagesData['rows'] as $row) {
        $title = str_replace(" • USC Student Marketplace", "", $row['dimensionValues'][0]['value']);
        $top_pages[] = ['title' => substr($title, 0, 30), 'views' => $row['metricValues'][0]['value']];
    }
}

// Fetching Sources
$sourceData = callGA4('runReport', [
    "dateRanges" => [ ["startDate" => "28daysAgo", "endDate" => "today"] ],
    "dimensions" => [ ["name" => "sessionSource"] ],
    "metrics" => [ ["name" => "activeUsers"] ],
    "limit" => 5
], $token, $property_id);

$sources = [];
if (isset($sourceData['rows'])) {
    foreach ($sourceData['rows'] as $row) {
        $sources[] = ['name' => $row['dimensionValues'][0]['value'], 'users' => $row['metricValues'][0]['value']];
    }
}

// ENCODE JSON FOR JS
$js_trend_labels = json_encode($trend_labels);
$js_trend_values = json_encode($trend_values);
$js_hours = json_encode(array_values($hours));
$js_browsers = json_encode($browsers);
$js_browser_vals = json_encode($browser_users);

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Pro Analytics</title>
    <link rel="stylesheet" href="stylesheet.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body { background-color: #f3f4f6; }
        .dash-wrap { max-width: 1200px; margin: 30px auto; padding: 0 20px; }

        /* Layouts */
        .kpi-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 15px; margin-bottom: 25px; }
        .charts-row { display: grid; grid-template-columns: 2fr 1fr; gap: 20px; margin-bottom: 25px; }
        .lists-row { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }

        /* Cards */
        .card { background: white; padding: 20px; border-radius: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); border: 1px solid #e5e7eb; }
        .card h3 { margin: 0 0 10px 0; font-size: 0.8rem; text-transform: uppercase; letter-spacing: 0.5px; color: #6b7280; }

        /* Stats */
        .stat-val { font-size: 2rem; font-weight: 800; color: #111827; }
        .stat-label { font-size: 0.85rem; color: #166534; font-weight: 600; margin-top: 4px; }

        /* Live Pulse */
        .live-badge { background: #fee2e2; color: #990000; padding: 6px 12px; border-radius: 20px; font-weight: bold; font-size: 0.9rem; display: inline-flex; align-items: center; }
        .pulse-dot { width: 8px; height: 8px; background: #990000; border-radius: 50%; margin-right: 8px; animation: pulse 1.5s infinite; }

        /* Tables */
        .data-table { width: 100%; border-collapse: collapse; font-size: 0.9rem; }
        .data-table td { padding: 8px 0; border-bottom: 1px solid #f3f4f6; }
        .bar-bg { background: #f3f4f6; height: 6px; border-radius: 3px; width: 100%; margin-top: 6px; overflow: hidden; }
        .bar-fill { height: 100%; background: #990000; }

        @keyframes pulse { 0% { opacity: 1; } 50% { opacity: 0.3; } 100% { opacity: 1; } }
        @media(max-width: 900px) { .charts-row, .lists-row { grid-template-columns: 1fr; } }
    </style>
</head>
<body>

<?php include 'nav.php'; ?>

<div class="dash-wrap">

    <a href="Admin_Files/index.php" style="display:inline-block; margin-bottom:20px; color:#666; text-decoration:none; font-weight:600;">
        &larr; Back to Dashboard
    </a>

    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:25px;">
        <div>
            <h1 style="margin:0;">Command Center</h1>
            <p style="margin:5px 0 0; color:#666;">Performance over last 28 days</p>
        </div>
        <div class="live-badge">
            <div class="pulse-dot"></div> <?php echo $live_users; ?> Students Online
        </div>
    </div>

    <div class="kpi-grid">
        <div class="card">
            <h3>Total Traffic</h3>
            <div class="stat-val"><?php echo number_format($total_users); ?></div>
            <div class="stat-label">Unique Students</div>
        </div>
        <div class="card">
            <h3>Loyalty</h3>
            <div class="stat-val"><?php echo number_format($returning_users); ?></div>
            <div class="stat-label">Returning Users</div>
        </div>
        <div class="card">
            <h3>Engagement</h3>
            <div class="stat-val"><?php echo $eng_rate; ?></div>
            <div class="stat-label">Meaningful Visits</div>
        </div>
        <div class="card">
            <h3>Avg Time</h3>
            <div class="stat-val"><?php echo $avg_duration; ?></div>
            <div class="stat-label">Min : Sec</div>
        </div>
        <div class="card">
            <h3>Depth</h3>
            <div class="stat-val"><?php echo $views_per_sess; ?></div>
            <div class="stat-label">Listings / Session</div>
        </div>
        <div class="card">
            <h3>Activity</h3>
            <div class="stat-val"><?php echo $total_events; ?></div>
            <div class="stat-label">Total Clicks/Scrolls</div>
        </div>
    </div>

    <div class="charts-row">
        <div class="card">
            <h3>Traffic Trend (Last Month)</h3>
            <div style="height:250px;">
                <canvas id="trendChart"></canvas>
            </div>
        </div>
        <div class="card">
            <h3>Peak Shopping Hours</h3>
            <div style="height:250px;">
                <canvas id="hourChart"></canvas>
            </div>
        </div>
    </div>

    <div class="lists-row">
        <div class="card">
            <h3>Most Viewed Content</h3>
            <table class="data-table">
                <?php foreach($top_pages as $p): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($p['title']); ?></td>
                        <td style="text-align:right; font-weight:bold;"><?php echo number_format($p['views']); ?></td>
                    </tr>
                <?php endforeach; ?>
            </table>
        </div>

        <div class="card">
            <h3>Top Browsers (Tech Stack)</h3>
            <div style="height:150px; margin-bottom:20px;">
                <canvas id="browserChart"></canvas>
            </div>

            <h3>Top Traffic Sources</h3>
            <table class="data-table">
                <?php foreach($sources as $s): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($s['name']); ?></td>
                        <td style="text-align:right;"><?php echo $s['users']; ?></td>
                    </tr>
                <?php endforeach; ?>
            </table>
        </div>
    </div>

</div>

<script>
    // 1. TREND CHART (Line)
    new Chart(document.getElementById('trendChart'), {
        type: 'line',
        data: {
            labels: <?php echo $js_trend_labels; ?>,
            datasets: [{
                label: 'Active Students',
                data: <?php echo $js_trend_values; ?>,
                borderColor: '#990000',
                backgroundColor: 'rgba(153, 0, 0, 0.05)',
                fill: true,
                tension: 0.3,
                pointRadius: 2
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: {display:false} },
            scales: { x: { grid: {display:false} }, y: { beginAtZero: true } }
        }
    });

    // 2. HOUR CHART (Bar)
    new Chart(document.getElementById('hourChart'), {
        type: 'bar',
        data: {
            labels: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23],
            datasets: [{
                label: 'Users',
                data: <?php echo $js_hours; ?>,
                backgroundColor: '#FFC72C',
                borderRadius: 3
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: {display:false} },
            scales: { x: { grid: {display:false} } }
        }
    });

    // 3. BROWSER CHART (Doughnut)
    new Chart(document.getElementById('browserChart'), {
        type: 'doughnut',
        data: {
            labels: <?php echo $js_browsers; ?>,
            datasets: [{
                data: <?php echo $js_browser_vals; ?>,
                backgroundColor: ['#990000', '#FFC72C', '#333333', '#888888', '#cccccc'],
                borderWidth: 0
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: {position: 'right', labels: {boxWidth:12} } }
        }
    });
</script>

</body>
</html>