<?php
/** @var \BotGuard\Core\View $this */
$this->layout('layouts.app');

$labels = array_map(static fn ($r) => $r['day'], $trend);
$humans = array_map(static fn ($r) => (int) $r['humans'], $trend);
$susp = array_map(static fn ($r) => (int) $r['suspicious'], $trend);
$bots = array_map(static fn ($r) => (int) $r['bots'], $trend);
?>
<h1 class="h4 mb-3">Analytics</h1>

<?= $this->partial('partials.stat_cards', ['summary' => $summary]) ?>

<div class="row g-3 mb-4">
    <div class="col-lg-8">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <h6 class="card-title mb-3">30-Day Traffic Trend</h6>
                <canvas id="trend" height="110"></canvas>
            </div>
        </div>
    </div>
    <div class="col-lg-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <h6 class="card-title mb-3">Classification Split</h6>
                <canvas id="split" height="200"></canvas>
            </div>
        </div>
    </div>
</div>

<div class="row g-3">
    <div class="col-lg-3"><?= $this->partial('partials.top_list', ['title' => 'Browsers', 'rows' => $browsers]) ?></div>
    <div class="col-lg-3"><?= $this->partial('partials.top_list', ['title' => 'Operating Systems', 'rows' => $os]) ?></div>
    <div class="col-lg-3"><?= $this->partial('partials.top_list', ['title' => 'Devices', 'rows' => $devices]) ?></div>
    <div class="col-lg-3"><?= $this->partial('partials.top_list', ['title' => 'Referrers', 'rows' => $referrers]) ?></div>
</div>

<?php $this->section('scripts', '<script>(function(){
    var t = document.getElementById("trend");
    if (t) new Chart(t, { type:"line", data:{ labels:' . json_encode($labels) . ', datasets:[
        {label:"Humans",data:' . json_encode($humans) . ',borderColor:"#16a34a",tension:.3},
        {label:"Suspicious",data:' . json_encode($susp) . ',borderColor:"#d97706",tension:.3},
        {label:"Bots",data:' . json_encode($bots) . ',borderColor:"#dc2626",tension:.3}
    ]}, options:{plugins:{legend:{position:"bottom"}},scales:{y:{beginAtZero:true}}} });
    var s = document.getElementById("split");
    if (s) new Chart(s, { type:"doughnut", data:{ labels:["Humans","Suspicious","Bots"], datasets:[{
        data:[' . (int) ($summary['humans'] ?? 0) . ',' . (int) ($summary['suspicious'] ?? 0) . ',' . (int) ($summary['bots'] ?? 0) . '],
        backgroundColor:["#16a34a","#d97706","#dc2626"] }] }, options:{plugins:{legend:{position:"bottom"}}} });
})();</script>'); ?>
