266 lines
12 KiB
PHP
266 lines
12 KiB
PHP
<?php
|
|
// dashboard.php
|
|
|
|
// Start session to store GA data and manage state
|
|
session_start();
|
|
|
|
// Configuration and token management
|
|
$google_analytics_connected = file_exists('db/google_tokens.json');
|
|
$ga_property_id = null;
|
|
$ga_data = null;
|
|
$ga_error = null;
|
|
|
|
// Handle GA Property ID submission
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ga_property_id'])) {
|
|
$property_id = trim($_POST['ga_property_id']);
|
|
if (!empty($property_id)) {
|
|
file_put_contents('db/ga_property_id.txt', $property_id);
|
|
// Clear previous GA data on new ID
|
|
if (isset($_SESSION['ga_data'])) unset($_SESSION['ga_data']);
|
|
if (isset($_SESSION['ga_error'])) unset($_SESSION['ga_error']);
|
|
|
|
// Set a flag to indicate we need to fetch data
|
|
$_SESSION['ga_fetch_required'] = true;
|
|
|
|
header('Location: dashboard.php');
|
|
exit();
|
|
}
|
|
}
|
|
|
|
// Load GA Property ID if it exists
|
|
if (file_exists('db/ga_property_id.txt')) {
|
|
$ga_property_id = file_get_contents('db/ga_property_id.txt');
|
|
}
|
|
|
|
// --- GOOGLE ANALYTICS DATA FETCHING ---
|
|
// Fetch data only if connected, property ID is set, and a fetch is required
|
|
if ($google_analytics_connected && $ga_property_id && isset($_SESSION['ga_fetch_required'])) {
|
|
unset($_SESSION['ga_fetch_required']); // Unset the flag to prevent re-fetching on every page load
|
|
|
|
require_once 'google-config.php';
|
|
$tokens_json = file_get_contents('db/google_tokens.json');
|
|
$tokens = json_decode($tokens_json, true);
|
|
|
|
if (!is_array($tokens) || !isset($tokens['access_token']) || !isset($tokens['refresh_token'])) {
|
|
$_SESSION['ga_error'] = "Google token file is corrupt or invalid. Please disconnect and reconnect.";
|
|
error_log("Invalid google_tokens.json content: " . $tokens_json);
|
|
header('Location: dashboard.php');
|
|
exit();
|
|
}
|
|
|
|
$access_token = $tokens['access_token'];
|
|
$refresh_token = $tokens['refresh_token'];
|
|
|
|
// --- 1. Refresh Access Token ---
|
|
$token_url = 'https://oauth2.googleapis.com/token';
|
|
$token_params = [
|
|
'client_id' => GOOGLE_CLIENT_ID,
|
|
'client_secret' => GOOGLE_CLIENT_SECRET,
|
|
'refresh_token' => $refresh_token,
|
|
'grant_type' => 'refresh_token'
|
|
];
|
|
|
|
$ch = curl_init($token_url);
|
|
curl_setopt($ch, CURLOPT_POST, true);
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($token_params));
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
$response = curl_exec($ch);
|
|
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
curl_close($ch);
|
|
|
|
if ($http_code == 200) {
|
|
$new_token_data = json_decode($response, true);
|
|
if (isset($new_token_data['access_token'])) {
|
|
$tokens['access_token'] = $new_token_data['access_token'];
|
|
file_put_contents('db/google_tokens.json', json_encode($tokens));
|
|
$access_token = $new_token_data['access_token'];
|
|
|
|
// --- 2. Fetch Data from Google Analytics Data API ---
|
|
$analytics_api_url = "https://analyticsdata.googleapis.com/v1beta/properties/{$ga_property_id}:runReport";
|
|
|
|
$api_request_body = [
|
|
'dateRanges' => [['startDate' => '28daysAgo', 'endDate' => 'today']],
|
|
'metrics' => [
|
|
['name' => 'sessions'],
|
|
['name' => 'totalUsers'],
|
|
['name' => 'screenPageViews'],
|
|
['name' => 'bounceRate']
|
|
]
|
|
];
|
|
|
|
$ch_analytics = curl_init($analytics_api_url);
|
|
curl_setopt($ch_analytics, CURLOPT_HTTPHEADER, [
|
|
'Authorization: Bearer ' . $access_token,
|
|
'Content-Type: application/json'
|
|
]);
|
|
curl_setopt($ch_analytics, CURLOPT_POST, true);
|
|
curl_setopt($ch_analytics, CURLOPT_POSTFIELDS, json_encode($api_request_body));
|
|
curl_setopt($ch_analytics, CURLOPT_RETURNTRANSFER, true);
|
|
|
|
$analytics_response = curl_exec($ch_analytics);
|
|
$analytics_http_code = curl_getinfo($ch_analytics, CURLINFO_HTTP_CODE);
|
|
curl_close($ch_analytics);
|
|
|
|
if ($analytics_http_code == 200) {
|
|
$report = json_decode($analytics_response, true);
|
|
if (isset($report['rows'][0]['metricValues'])) {
|
|
$metricValues = $report['rows'][0]['metricValues'];
|
|
$_SESSION['ga_data'] = [
|
|
'sessions' => $metricValues[0]['value'] ?? '0',
|
|
'users' => $metricValues[1]['value'] ?? '0',
|
|
'page_views' => $metricValues[2]['value'] ?? '0',
|
|
'bounce_rate' => isset($metricValues[3]['value']) ? round($metricValues[3]['value'] * 100, 2) . '%' : '0%',
|
|
];
|
|
} else {
|
|
$_SESSION['ga_error'] = "No data returned from Analytics. Check if the property ID is correct and has recent data.";
|
|
}
|
|
} else {
|
|
$error_response = json_decode($analytics_response, true);
|
|
$error_message = "HTTP {$analytics_http_code}";
|
|
if (is_array($error_response) && isset($error_response['error']['message'])) {
|
|
$error_message = $error_response['error']['message'];
|
|
} else {
|
|
error_log("Unknown Google API Error. Code: {$analytics_http_code}. Response: " . $analytics_response);
|
|
}
|
|
$_SESSION['ga_error'] = "Error fetching Analytics data: " . $error_message;
|
|
}
|
|
} else {
|
|
$_SESSION['ga_error'] = "Failed to refresh token, new access token not found.";
|
|
}
|
|
} else {
|
|
$_SESSION['ga_error'] = "Error refreshing Google token. Please try disconnecting and reconnecting.";
|
|
}
|
|
|
|
// Redirect to clean the URL and prevent re-submission
|
|
header('Location: dashboard.php');
|
|
exit();
|
|
}
|
|
|
|
// Load data from session if available
|
|
if (isset($_SESSION['ga_data'])) {
|
|
$ga_data = $_SESSION['ga_data'];
|
|
unset($_SESSION['ga_data']); // Clear after loading
|
|
}
|
|
if (isset($_SESSION['ga_error'])) {
|
|
$ga_error = $_SESSION['ga_error'];
|
|
unset($_SESSION['ga_error']); // Clear after loading
|
|
}
|
|
|
|
|
|
// Dummy data for other sections (can be replaced later)
|
|
$client_name = "Example Client";
|
|
$chart_data = [
|
|
"labels" => ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
|
|
"values" => [5000, 5500, 6200, 7100, 8000, 8500, 9200, 9800, 10500, 11200, 12000, 12345],
|
|
];
|
|
?>
|
|
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title><?php echo htmlspecialchars($client_name); ?> - Marketing Dashboard</title>
|
|
<link href="https://fonts.googleapis.com/css2?family=Georgia:wght@700&family=Helvetica+Neue:wght@400&display=swap" rel="stylesheet">
|
|
<link rel="stylesheet" href="assets/css/custom.css">
|
|
</head>
|
|
<body>
|
|
|
|
<header class="dashboard-header">
|
|
<div class="logo">
|
|
<a href="index.php">AgencyMoguls</a>
|
|
</div>
|
|
<nav class="dashboard-nav">
|
|
<a href="#overview" class="active">Overview</a>
|
|
<a href="#reports">Reports</a>
|
|
<a href="#settings">Settings</a>
|
|
<a href="index.php" class="logout-btn">Logout</a>
|
|
</nav>
|
|
</header>
|
|
|
|
<main class="dashboard-main">
|
|
<div class="integration-connect">
|
|
<?php if ($google_analytics_connected): ?>
|
|
<div class="ga-status-connected">Connected to Google Analytics</div>
|
|
<a href="google_disconnect.php" class="btn btn-secondary">Disconnect</a>
|
|
<?php else: ?>
|
|
<a href="google_auth.php" class="btn btn-primary">Connect to Google Analytics</a>
|
|
<?php endif; ?>
|
|
</div>
|
|
<div class="dashboard-title">
|
|
<h1><?php echo htmlspecialchars($client_name); ?>'s Dashboard</h1>
|
|
<div class="date-range-picker">
|
|
<input type="text" value="Last 28 Days">
|
|
<svg width="14" height="8" viewBox="0 0 14 8" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 1L7 7L13 1" stroke="#6C757D" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
|
|
</div>
|
|
</div>
|
|
|
|
<?php if ($google_analytics_connected): ?>
|
|
<?php if (!$ga_property_id): ?>
|
|
<section class="ga-property-id-section">
|
|
<h2>Enter your Google Analytics Property ID</h2>
|
|
<p>This is required to fetch data from your Analytics account.</p>
|
|
<form method="POST" action="dashboard.php">
|
|
<input type="text" name="ga_property_id" placeholder="Enter your Property ID (e.g., 123456789)" required>
|
|
<button type="submit" class="btn btn-primary">Save and Fetch Data</button>
|
|
</form>
|
|
</section>
|
|
<?php else: ?>
|
|
<section class="ga-data-section">
|
|
<h2>Google Analytics Overview <span class="ga-property-id">(Property ID: <?php echo htmlspecialchars($ga_property_id); ?>)</span></h2>
|
|
|
|
<?php if ($ga_error): ?>
|
|
<div class="ga-error-notice">
|
|
<strong>Error:</strong> <?php echo htmlspecialchars($ga_error); ?>
|
|
</div>
|
|
<?php endif; ?>
|
|
|
|
<?php if ($ga_data): ?>
|
|
<div class="ga-data-grid">
|
|
<div class="ga-data-card">
|
|
<h3>Sessions</h3>
|
|
<p class="ga-data-value"><?php echo htmlspecialchars($ga_data['sessions']); ?></p>
|
|
</div>
|
|
<div class="ga-data-card">
|
|
<h3>Users</h3>
|
|
<p class="ga-data-value"><?php echo htmlspecialchars($ga_data['users']); ?></p>
|
|
</div>
|
|
<div class="ga-data-card">
|
|
<h3>Page Views</h3>
|
|
<p class="ga-data-value"><?php echo htmlspecialchars($ga_data['page_views']); ?></p>
|
|
</div>
|
|
<div class="ga-data-card">
|
|
<h3>Bounce Rate</h3>
|
|
<p class="ga-data-value"><?php echo htmlspecialchars($ga_data['bounce_rate']); ?></p>
|
|
</div>
|
|
</div>
|
|
<?php else: ?>
|
|
<div class="ga-loading-notice">
|
|
Attempting to fetch live data from Google Analytics... If this message persists, please check your Property ID or try reconnecting.
|
|
</div>
|
|
<?php endif; ?>
|
|
</section>
|
|
<?php endif; ?>
|
|
<?php endif; ?>
|
|
|
|
<section class="chart-section">
|
|
<div class="chart-container">
|
|
<h2 class="chart-title">Sessions Over Time (Sample)</h2>
|
|
<div class="chart">
|
|
<?php
|
|
$max_value = max($chart_data['values']);
|
|
foreach ($chart_data['values'] as $index => $value):
|
|
$height_percentage = ($value / $max_value) * 100;
|
|
?>
|
|
<div class="chart-bar-wrapper">
|
|
<div class="chart-bar" style="height: <?php echo $height_percentage; ?>%;"></div>
|
|
<span class="chart-label"><?php echo $chart_data['labels'][$index]; ?></span>
|
|
</div>
|
|
<?php endforeach; ?>
|
|
</div>
|
|
</div>
|
|
</section>
|
|
|
|
</main>
|
|
|
|
</body>
|
|
</html>
|