<?php
require_once __DIR__ . '/../includes/bootstrap.php';
require_once __DIR__ . '/../session_check.php';

header('Content-Type: application/json; charset=utf-8');

$cacheDir = dirname(__DIR__) . '/cache/iptv_monitor';
$ttl = 120;
$now = time();

if (!is_dir($cacheDir)) {
    @mkdir($cacheDir, 0755, true);
}

function monitor_device_bucket($device) {
    $device = trim((string)$device);
    $lower = strtolower($device);

    if ($device === '') {
        return 'Desconhecido';
    }
    if (strpos($lower, 'fire') !== false || strpos($lower, 'amazon') !== false) {
        return 'Fire TV';
    }
    if (strpos($lower, 'google tv') !== false || strpos($lower, 'android tv') !== false) {
        return 'Android TV';
    }
    if (strpos($lower, 'android') !== false) {
        return 'Android';
    }
    return $device;
}

$files = glob($cacheDir . '/*.json');
$online = [];
$summary = [
    'online' => 0,
    'live' => 0,
    'movie' => 0,
    'series' => 0,
];
$devices = [];

if ($files !== false) {
    foreach ($files as $file) {
        $updatedAt = @filemtime($file);
        if ($updatedAt === false) {
            $updatedAt = 0;
        }

        if (($now - $updatedAt) > $ttl) {
            @unlink($file);
            continue;
        }

        $raw = @file_get_contents($file);
        $item = json_decode((string)$raw, true);
        if (!is_array($item)) {
            @unlink($file);
            continue;
        }

        $item['updated_at'] = (int)($item['updated_at'] ?? $updatedAt);
        $item['first_seen'] = (int)($item['first_seen'] ?? $item['updated_at'] ?? $now);
        if ($item['first_seen'] <= 0) {
            $item['first_seen'] = $item['updated_at'];
        }
        $item['seconds_ago'] = max(0, $now - $item['updated_at']);
        $item['online_seconds'] = max(0, $now - $item['first_seen']);
        $item['type_label'] = ($item['content_type'] === 'live') ? '📺 Live' : (($item['content_type'] === 'movie') ? '🎬 Filme' : '📼 Série');
        $item['device_bucket'] = monitor_device_bucket($item['device'] ?? '');
        $online[] = $item;

        $summary['online']++;
        if (isset($summary[$item['content_type']])) {
            $summary[$item['content_type']]++;
        }
        if (!isset($devices[$item['device_bucket']])) {
            $devices[$item['device_bucket']] = 0;
        }
        $devices[$item['device_bucket']]++;
    }
}

usort($online, function ($a, $b) {
    return ($b['updated_at'] ?? 0) <=> ($a['updated_at'] ?? 0);
});

arsort($devices);
$deviceRows = [];
foreach ($devices as $deviceName => $count) {
    $deviceRows[] = [
        'name' => $deviceName,
        'count' => (int)$count,
    ];
}

echo json_encode([
    'success' => 1,
    'summary' => $summary,
    'devices' => $deviceRows,
    'ttl_seconds' => $ttl,
    'generated_at' => $now,
    'data' => $online,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
