<?php
session_start();
include "includes/layout.php";
include __DIR__ . '/../database/search_log_config.php';

/* TOTAL SEARCHES */
$totalSearches = $log_conn->query("
SELECT COUNT(*) as total FROM search_logs
")->fetch_assoc()['total'];

/* TOTAL SPONSORED CLICKS */
$totalClicks = $log_conn->query("
SELECT SUM(click_count) as total FROM sponsored_keywords
")->fetch_assoc()['total'] ?? 0;

/* TOP SEARCHED KEYWORDS */
$topKeywords = $log_conn->query("
SELECT keyword, COUNT(*) as total
FROM search_logs
GROUP BY keyword
ORDER BY total DESC
LIMIT 5
");

/* TOP SPONSORED BY CLICKS */
$topSponsored = $log_conn->query("
SELECT keyword, click_count
FROM sponsored_keywords
ORDER BY click_count DESC
LIMIT 5
");

/* LAST 7 DAYS CHART */
$chartData = $log_conn->query("
SELECT DATE(searched_at) as day, COUNT(*) as total
FROM search_logs
GROUP BY day
ORDER BY day DESC
LIMIT 7
");

$labels = [];
$data = [];

while($row = $chartData->fetch_assoc()){
    $labels[] = $row['day'];
    $data[] = $row['total'];
}
?>

<h1>Dashboard Analytics</h1>

<!-- Stats Cards -->
<div style="display:flex;flex-wrap:wrap;gap:20px;width:100%;">

<div class="card" style="flex:1 1 250px;min-width:250px;">
<h3>Total Searches</h3>
<p style="font-size:28px;color:#007185;font-weight:bold;">
<?= $totalSearches ?>
</p>
</div>

<div class="card" style="flex:1;min-width:250px;">
<h3>Total Sponsored Clicks</h3>
<p style="font-size:28px;color:#e67e22;font-weight:bold;">
<?= $totalClicks ?>
</p>
</div>

</div>

<!-- Chart -->
<div class="card">
<h3>Search Trend (Last 7 Days)</h3>
<canvas id="searchChart" style="width:100%;max-width:100%;"></canvas>
</div>

<script>
new Chart(document.getElementById('searchChart'), {
    type: 'line',
    data: {
        labels: <?= json_encode(array_reverse($labels)) ?>,
        datasets: [{
            label: 'Searches',
            data: <?= json_encode(array_reverse($data)) ?>,
            borderWidth: 2,
            tension: 0.3
        }]
    }
});
</script>

<!-- Top Keywords -->
<div style="display:flex;flex-wrap:wrap;gap:20px;width:100%;align-items:flex-start;">

<div class="card" style="flex:1;min-width:300px;">
<h3>Top 5 Searched Keywords</h3>
<ul>
<?php while($row = $topKeywords->fetch_assoc()): ?>
<li>
<?= htmlspecialchars($row['keyword']) ?> 
(<?= $row['total'] ?> searches)
</li>
<?php endwhile; ?>
</ul>
</div>

<div class="card" style="flex:1;min-width:300px;">
<h3>Top 5 Sponsored Clicks</h3>
<ul>
<?php while($row = $topSponsored->fetch_assoc()): ?>
<li>
<?= htmlspecialchars($row['keyword']) ?> 
(<?= $row['click_count'] ?> clicks)
</li>
<?php endwhile; ?>
</ul>
</div>

</div>

<?php
$log_conn->close();
include "includes/footer.php";
?>