<?php
require_once __DIR__ . '/_common.php';
require_csrf_unless_get();

$now = unix_now();
$day = 86400;

// Period selector: ?period=24h|7d|14d|30d  (default 14d, matches IBO reference)
$period_seconds = [
    '24h' =>  1 * $day,
    '7d'  =>  7 * $day,
    '14d' => 14 * $day,
    '30d' => 30 * $day,
];
$period_in = isset($_GET['period']) ? (string)$_GET['period'] : '14d';
$period    = isset($period_seconds[$period_in]) ? $period_in : '14d';
$window    = $period_seconds[$period];
$since  = $now - $window;

// -----------------------------------------------------------------------------
// Headline stat cards (IBO GLASS shape)
// -----------------------------------------------------------------------------
$total_hits  = (int) db_one('SELECT COUNT(*) c FROM panel_request_log WHERE created_at >= ?', [$since])['c'];
$unique_ips  = (int) db_one('SELECT COUNT(DISTINCT ip_address) c FROM panel_request_log WHERE created_at >= ?', [$since])['c'];

$top_row = db_one(
    'SELECT path, COUNT(*) c FROM panel_request_log
     WHERE created_at >= ? GROUP BY path ORDER BY c DESC LIMIT 1',
    [$since]
);
$top_endpoint = $top_row ? (string)$top_row['path'] : '—';
$top_ep_count = $top_row ? (int)$top_row['c']      : 0;

// Database footprint — sum of every .db file in data/
$db_size_bytes = 0;
foreach (glob(__DIR__ . '/../data/*.db') as $f) {
    $db_size_bytes += @filesize($f) ?: 0;
}
$db_size = $db_size_bytes >= 1024 * 1024
    ? sprintf('%.1f MB', $db_size_bytes / (1024 * 1024))
    : sprintf('%d KB', max(1, (int)round($db_size_bytes / 1024)));

// -----------------------------------------------------------------------------
// Endpoint distribution (donut + bar)
// -----------------------------------------------------------------------------
$endpoint_dist_rows = db_all(
    'SELECT path AS name, COUNT(*) AS count FROM panel_request_log
     WHERE created_at >= ? GROUP BY path ORDER BY count DESC LIMIT 8',
    [$since]
);
$endpoint_dist = array_map(function ($r) {
    return ['name' => (string)$r['name'], 'count' => (int)$r['count']];
}, $endpoint_dist_rows);

$top_endpoints = $endpoint_dist;   // bar chart uses the same data

// Long tail = endpoints ranked 9..N
$long_tail_rows = db_all(
    'SELECT path AS name, COUNT(*) AS count FROM panel_request_log
     WHERE created_at >= ? GROUP BY path ORDER BY count DESC LIMIT 30 OFFSET 8',
    [$since]
);
$long_tail = array_map(function ($r) {
    return ['name' => (string)$r['name'], 'count' => (int)$r['count']];
}, $long_tail_rows);

// -----------------------------------------------------------------------------
// Recent client activity (table)
// -----------------------------------------------------------------------------
$recent_clients_rows = db_all(
    "SELECT path AS endpoint, headers, ip_address, created_at AS latest
     FROM panel_request_log
     WHERE created_at >= ?
     ORDER BY id DESC LIMIT 20",
    [$since]
);
$recent_clients = [];
foreach ($recent_clients_rows as $r) {
    $ua = '';
    if (!empty($r['headers'])) {
        $h = json_decode($r['headers'], true);
        if (is_array($h)) {
            foreach ($h as $hk => $hv) {
                if (strcasecmp($hk, 'User-Agent') === 0) { $ua = (string)$hv; break; }
            }
        }
    }
    $recent_clients[] = [
        'endpoint'     => (string)($r['endpoint'] ?? ''),
        'user_agent'   => $ua,
        'country_code' => 'xx',  // no geoip yet — flag placeholder
        'latest'       => date('Y-m-d H:i:s', (int)$r['latest']),
    ];
}

// -----------------------------------------------------------------------------
// Map data (country_counts + markers) — empty until we wire a geoip provider
// -----------------------------------------------------------------------------
$country_counts = new stdClass();   // {US: 12, GB: 3, ...}
$country_dist   = [];               // [{code, count}]
$markers        = [];               // [{lat, lng, name, count}]

// -----------------------------------------------------------------------------
// Concentration curve (cumulative share of top-N endpoints)
// -----------------------------------------------------------------------------
$concentration = [];
if ($total_hits > 0) {
    $running = 0;
    foreach (array_slice($endpoint_dist_rows, 0, 10) as $row) {
        $running += (int)$row['count'];
        $concentration[] = round(($running / $total_hits) * 100, 1);
    }
}

// -----------------------------------------------------------------------------
// Legacy fields (kept so old dashboard.php still works if anyone hits this)
// -----------------------------------------------------------------------------
$legacy_totals = [
    'devices'    => (int) db_one('SELECT COUNT(*) c FROM devices')['c'],
    'active_24h' => (int) db_one('SELECT COUNT(*) c FROM devices WHERE last_seen_at >= ?', [$now - $day])['c'],
    'playlists'  => (int) db_one('SELECT COUNT(*) c FROM playlists')['c'],
    'portals'    => (int) db_one('SELECT COUNT(*) c FROM portals')['c'],
    'vpns'       => (int) db_one('SELECT COUNT(*) c FROM vpn_profiles')['c'],
];
$legacy_subs = [
    'paid'    => (int) db_one('SELECT COUNT(*) c FROM subscriptions WHERE is_trial >= 2')['c'],
    'trial'   => (int) db_one('SELECT COUNT(*) c FROM subscriptions WHERE is_trial = 0')['c'],
    'expired' => (int) db_one('SELECT COUNT(*) c FROM subscriptions WHERE is_trial = 1')['c'],
];

json_response([
    // IBO GLASS shape
    'period'           => $period,
    'total_hits'       => $total_hits,
    'unique_ips'       => $unique_ips,
    'top_endpoint'     => $top_endpoint,
    'top_ep_count'     => $top_ep_count,
    'db_size'          => $db_size,
    'endpoint_dist'    => $endpoint_dist,
    'top_endpoints'    => $top_endpoints,
    'long_tail'        => $long_tail,
    'recent_clients'   => $recent_clients,
    'country_counts'   => $country_counts,
    'country_dist'     => $country_dist,
    'markers'          => $markers,
    'concentration'    => $concentration,

    // Legacy shape (for any code still on it)
    'totals'           => $legacy_totals,
    'subs'             => $legacy_subs,
    'recent_devices'   => db_all(
        'SELECT d.mac_address, d.app_type, d.app_version, d.last_seen_at,
                s.is_trial, s.expired_date
         FROM devices d LEFT JOIN subscriptions s ON s.device_id = d.id
         ORDER BY d.last_seen_at DESC LIMIT 10'
    ),
    'endpoint_counts'  => $endpoint_dist,
]);
