<?php
// api/monitor_api.php - Com Limpeza Automática Diferenciada
session_start();
require_once '../includes/db.php';
header('Content-Type: application/json');
error_reporting(0);

$action = $_REQUEST['action'] ?? '';

if ($action == 'get_online') {
    try {
        $now = time();

        // --- 1. LIMPEZA DE CANAIS (5 Minutos) ---
        // Se o registro for antigo (mais de 300 segundos sem atualizar), remove.
        $limit_live = $now - 300; 
        $pdo->query("DELETE FROM active_connections 
                     WHERE (stream_type = 'live' OR stream_type = 'channel') 
                     AND start_time < $limit_live");

        // --- 2. LIMPEZA DE VOD (Filmes/Séries) (70 Minutos) ---
        // Se o registro for antigo (mais de 4200 segundos), remove.
        $limit_vod = $now - 4200;
        $pdo->query("DELETE FROM active_connections 
                     WHERE (stream_type = 'movie' OR stream_type = 'series') 
                     AND start_time < $limit_vod");

        // --- 3. FAXINA GERAL DE SEGURANÇA (4 Horas) ---
        // Remove qualquer coisa (bugs) que tenha ficado a mais de 4h
        $limit_geral = $now - 14400;
        $pdo->query("DELETE FROM active_connections WHERE start_time < $limit_geral");


        // --- BUSCA DADOS ---
        $sql = "SELECT * FROM active_connections ORDER BY id DESC";
        $stmt = $pdo->query($sql);
        $conns = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $output = [];

        foreach($conns as $c) {
            // Calcula duração baseado no timestamp atual
            $duration_secs = $now - $c['start_time'];
            $duration = gmdate("H:i:s", $duration_secs);
            
            // Garante que tenha imagem
            $img = $c['content_image'];
            if(empty($img)) $img = "https://i.imgur.com/7bI1klo.png";

            $output[] = [
                'id' => $c['id'],
                'user' => $c['username'],
                'ip' => $c['user_ip'],
                'content_name' => $c['content_name'], 
                'content_logo' => $img,
                'type' => $c['stream_type'],
                'duration' => $duration,
                'flag' => "https://flagcdn.com/24x18/br.png"
            ];
        }

        echo json_encode($output);
    } catch (Exception $e) { echo json_encode([]); }
}

if ($action == 'kill') {
    $id = $_POST['id'];
    $pdo->query("DELETE FROM active_connections WHERE id = " . (int)$id);
    echo json_encode(['status'=>true]);
}
?>
