<?php
// channels.php - COM TOLERÂNCIA DE BUFFER + AÇÕES EM MASSA
session_start();
require_once 'includes/db.php';

if (!isset($_SESSION['logged_in_fxtream'])) { header('Location: index.php'); exit; }

// ==========================================================
// FAXINA INTELIGENTE (HÍBRIDO)
// ==========================================================
$timeout_proxy = time() - 120;
$pdo->query("DELETE ac FROM active_connections ac JOIN channels c ON ac.content_id = c.id WHERE ac.stream_type = 'live' AND c.running = 1 AND ac.start_time < $timeout_proxy");

$timeout_direct = time() - 3600; 
$pdo->query("DELETE ac FROM active_connections ac LEFT JOIN channels c ON ac.content_id = c.id WHERE (ac.stream_type != 'live' OR c.running = 0 OR c.running IS NULL) AND ac.start_time < $timeout_direct");
// ==========================================================

// --- BUSCA CATEGORIAS ---
try {
    $cats = $pdo->query("SELECT * FROM categories WHERE type='channel' ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $cats = []; }

// --- FILTROS ---
$cat_filter = isset($_GET['cat']) ? (int)$_GET['cat'] : 0;
$status_filter = isset($_GET['status']) ? $_GET['status'] : 'all';
$limit_filter = isset($_GET['limit']) ? (int)$_GET['limit'] : 100;
$search_query = isset($_GET['q']) ? $_GET['q'] : '';

// --- SQL QUERY ---
$sql = "SELECT c.*, cat.name as cat_name,
        (SELECT COUNT(*) FROM active_connections WHERE content_id = c.id AND stream_type = 'live') as online_users
        FROM channels c 
        LEFT JOIN categories cat ON c.category_id = cat.id 
        WHERE 1=1";
$params = [];

if ($cat_filter > 0) { $sql .= " AND c.category_id = ?"; $params[] = $cat_filter; }

if ($status_filter === '1') {
    $sql .= " AND c.running = 1"; 
} elseif ($status_filter === '0') {
    $sql .= " AND c.running = 0"; 
}

if (!empty($search_query)) { $sql .= " AND c.name LIKE ?"; $params[] = "%$search_query%"; }

$sql .= " ORDER BY online_users DESC, c.running DESC, c.id DESC LIMIT $limit_filter";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$channels = $stmt->fetchAll(PDO::FETCH_ASSOC);

function formatUptime($datetime) {
    if (!$datetime) return '';
    try {
        $start = new DateTime($datetime);
        $now = new DateTime();
        $diff = $start->diff($now);
        $parts = [];
        if ($diff->d > 0) $parts[] = $diff->d . "d";
        if ($diff->h > 0) $parts[] = $diff->h . "h";
        $parts[] = $diff->i . "m"; 
        return implode(' ', $parts);
    } catch (Exception $e) { return ''; }
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Gerenciar Canais</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/hamburgers/1.1.3/hamburgers.min.css">
    <style>
        body { background-color: #121212; color: #e0e0e0; font-family: 'Segoe UI', sans-serif; }
        .card { background-color: #1e1e1e; border: 1px solid #333; }
        .table { color: #bfbfbf; }
        .table td, .table th { vertical-align: middle; border-top: 1px solid #333; }
        .table-hover tbody tr:hover { background-color: #2c2c2c; }
        .form-control, .custom-select { background-color: #2c2c2c; border: 1px solid #444; color: #fff; }
        .modal-content { background-color: #1f1f1f; border: 1px solid #333; color: #fff; }
        .channel-logo { width: 40px; height: 40px; object-fit: contain; background: #000; border-radius: 4px; border: 1px solid #444; }
        
        @media (min-width: 992px) {
            #sidebar { width: 240px; position: fixed; top: 0; left: 0; height: 100vh; z-index: 1000; overflow-y: auto; }
            .container-main { margin-left: 240px; width: calc(100% - 240px); padding: 20px; }
            .hamburger { display: none !important; }
        }
        @media (max-width: 991px) {
            #sidebar { position: fixed; top: 0; left: -260px; width: 250px; height: 100vh; z-index: 9999; transition: all 0.3s ease; box-shadow: 2px 0 10px rgba(0,0,0,0.5); }
            #sidebar.active { left: 0; }
            .container-main { margin-left: 0; width: 100%; padding: 15px; }
            .overlay-menu { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9998; }
            .overlay-menu.active { display: block; }
        }
        .pulse-live { animation: pulse-green 2s infinite; }
        @keyframes pulse-green {
            0% { box-shadow: 0 0 0 0 rgba(40, 167, 69, 0.7); }
            70% { box-shadow: 0 0 0 5px rgba(40, 167, 69, 0); }
            100% { box-shadow: 0 0 0 0 rgba(40, 167, 69, 0); }
        }
        /* Botões Flutuantes em Massa */
        .mass-actions { display: none; margin-bottom: 15px; background: #2a2a2a; padding: 10px; border-radius: 5px; border: 1px solid #444; }
    </style>
</head>
<body>

<?php include 'includes/sidebar.php'; ?>
<div class="overlay-menu" id="overlayMenu"></div>

<div class="container-main">
    
    <div class="d-lg-none d-flex justify-content-between align-items-center mb-3 bg-dark p-2 rounded shadow-sm">
        <button class="hamburger hamburger--slider" type="button" id="btnToggleMenu">
            <span class="hamburger-box"><span class="hamburger-inner"></span></span>
        </button>
        <span class="font-weight-bold text-white">Canais</span>
        <div></div>
    </div>

    <div class="row mb-4 align-items-center">
        <div class="col-md-4"><h3 class="mb-0 d-none d-md-block"><i class="fa fa-tv text-primary"></i> Canais</h3></div>
        <div class="col-md-8 text-md-right mt-3 mt-md-0">
            <button class="btn btn-secondary mr-1" onclick="window.history.back()"><i class="fa fa-arrow-left"></i></button>
            <button class="btn btn-info mr-1" onclick="$('#modalCat').modal('show')"><i class="fa fa-tags"></i> Categoria</button>
            <button class="btn btn-success font-weight-bold" onclick="openModal()"><i class="fa fa-plus"></i> Novo Canal</button>
        </div>
    </div>

    <div class="mass-actions" id="massPanel">
        <span class="text-white mr-3 font-weight-bold"><i class="fa fa-check-square"></i> Selecionados: <span id="selCount">0</span></span>
        <button class="btn btn-sm btn-success mr-1" onclick="massAction('start')"><i class="fa fa-play"></i> Iniciar (Proxy)</button>
        <button class="btn btn-sm btn-secondary mr-1" onclick="massAction('stop')"><i class="fa fa-stop"></i> Parar (Direct)</button>
        <button class="btn btn-sm btn-warning mr-1" onclick="massAction('restart')"><i class="fa fa-sync-alt"></i> Reiniciar</button>
        <button class="btn btn-sm btn-danger" onclick="massAction('delete')"><i class="fa fa-trash"></i> Excluir</button>
    </div>

    <div class="card bg-dark border-0 mb-3 shadow-sm">
        <div class="card-body p-3">
            <form method="GET" class="row">
                
                <div class="col-md-3 col-12 mb-2 mb-md-0">
                    <select name="cat" class="form-control" onchange="this.form.submit()">
                        <option value="0">? Todas as Categorias</option>
                        <?php foreach($cats as $c): ?>
                            <option value="<?php echo $c['id']; ?>" <?php echo $cat_filter==$c['id']?'selected':''; ?>><?php echo htmlspecialchars($c['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-3 col-12 mb-2 mb-md-0">
                    <select name="status" class="form-control" onchange="this.form.submit()">
                        <option value="all" <?php echo $status_filter=='all'?'selected':''; ?>>?? Todos os Modos</option>
                        <option value="1" <?php echo $status_filter=='1'?'selected':''; ?>>?? Apenas Proxy (Live)</option>
                        <option value="0" <?php echo $status_filter=='0'?'selected':''; ?>>?? Apenas Direct</option>
                    </select>
                </div>

                <div class="col-md-2 col-12 mb-2 mb-md-0">
                    <select name="limit" class="form-control" onchange="this.form.submit()">
                        <option value="10" <?php echo $limit_filter==10?'selected':''; ?>>10 Linhas</option>
                        <option value="50" <?php echo $limit_filter==50?'selected':''; ?>>50 Linhas</option>
                        <option value="100" <?php echo $limit_filter==100?'selected':''; ?>>100 Linhas</option>
                        <option value="500" <?php echo $limit_filter==500?'selected':''; ?>>500 Linhas</option>
                        <option value="1000" <?php echo $limit_filter==1000?'selected':''; ?>>1000 Linhas</option>
                    </select>
                </div>

                <div class="col-md-3 col-10 mb-2 mb-md-0">
                    <div class="input-group">
                        <input type="text" name="q" class="form-control" placeholder="Buscar canal..." value="<?php echo htmlspecialchars($search_query); ?>">
                        <div class="input-group-append"><button class="btn btn-primary"><i class="fa fa-search"></i></button></div>
                    </div>
                </div>
                <div class="col-md-1 col-2">
                    <a href="channels.php" class="btn btn-outline-light btn-block"><i class="fa fa-sync-alt"></i></a>
                </div>
            </form>
        </div>
    </div>

    <div class="card shadow-sm">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="bg-secondary text-white">
                    <tr>
                        <th class="text-center" width="40"><input type="checkbox" id="checkAll" onclick="toggleAll(this)"></th>
                        <th class="text-center" width="80">Status</th>
                        <th class="text-center" width="60">Logo</th>
                        <th>Nome</th>
                        <th class="d-none d-md-table-cell">Categoria</th>
                        <th class="text-center">Online</th>
                        <th class="text-center">Modo</th>
                        <th class="text-right pr-4">Ações</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(count($channels) > 0): ?>
                        <?php foreach($channels as $c): ?>
                        <tr>
                            <td class="text-center"><input type="checkbox" class="chk-item" value="<?php echo $c['id']; ?>" onclick="updateMassPanel()"></td>
                            
                            <td class="text-center">
                                <?php if($c['running'] == 1): ?>
                                    <span class="badge badge-success shadow-sm pulse-live mb-1" title="Restream Ativo">ON</span>
                                    <br>
                                    <small class="text-success font-weight-bold" style="font-size: 0.75rem;">
                                        <i class="fa fa-clock"></i> <?php echo formatUptime($c['uptime']); ?>
                                    </small>
                                <?php else: ?>
                                    <span class="badge badge-secondary">OFF</span>
                                <?php endif; ?>
                            </td>

                            <td class="text-center p-1"><img src="<?php echo $c['logo_url'] ?: 'https://via.placeholder.com/40x40?text=?'; ?>" class="channel-logo"></td>
                            
                            <td>
                                <div class="font-weight-bold text-white"><?php echo htmlspecialchars($c['name']); ?></div>
                                <div class="d-md-none text-muted small mt-1"><?php echo $c['cat_name'] ?: 'Sem Categoria'; ?></div>
                            </td>
                            
                            <td class="d-none d-md-table-cell"><span class="badge badge-dark border border-secondary"><?php echo $c['cat_name'] ?: 'Sem Categoria'; ?></span></td>
                            
                            <td class="text-center">
                                <?php if($c['online_users'] > 0): ?>
                                    <span class="badge badge-info shadow-sm" style="font-size: 0.9rem;">
                                        <i class="fa fa-users"></i> <?php echo $c['online_users']; ?>
                                    </span>
                                <?php else: ?>
                                    <span class="text-muted small">-</span>
                                <?php endif; ?>
                            </td>

                            <td class="text-center">
                                <?php if($c['running'] == 1): ?>
                                    <button class="btn btn-sm btn-danger font-weight-bold mb-1" onclick="controlStream(<?php echo $c['id']; ?>, 'stop')" title="Virar Direct">
                                        <i class="fa fa-stop"></i> Proxy
                                    </button>
                                <?php else: ?>
                                    <button class="btn btn-sm btn-success font-weight-bold mb-1" onclick="controlStream(<?php echo $c['id']; ?>, 'start')" title="Virar Proxy">
                                        <i class="fa fa-play"></i> Direct
                                    </button>
                                <?php endif; ?>
                                
                                <?php if($c['running'] == 1): ?>
                                    <button class="btn btn-sm btn-warning font-weight-bold mb-1" onclick="controlStream(<?php echo $c['id']; ?>, 'restart')" title="Reiniciar Stream">
                                        <i class="fa fa-sync-alt"></i>
                                    </button>
                                <?php endif; ?>
                            </td>

                            <td class="text-right pr-4">
                                <button class="btn btn-sm btn-info" onclick="edit(<?php echo $c['id']; ?>)"><i class="fa fa-pen"></i></button>
                                <button class="btn btn-sm btn-danger" onclick="del(<?php echo $c['id']; ?>)"><i class="fa fa-trash"></i></button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="8" class="text-center py-5 text-muted">Nenhum canal encontrado.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="modalContent" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-dark border-secondary">
                <h5 class="modal-title"><i class="fa fa-tv"></i> Dados do Canal</h5>
                <button type="button" class="close text-white" data-dismiss="modal">×</button>
            </div>
            <div class="modal-body">
                <form id="formContent">
                    <input type="hidden" name="action" value="save_channel">
                    <input type="hidden" name="id" id="editId">
                    <div class="form-group"><label>Nome</label><input type="text" class="form-control" name="name" id="editName" required></div>
                    <div class="form-group"><label>Categoria</label><select class="form-control" name="category_id" id="editCat"><option value="0">Sem Categoria</option><?php foreach($cats as $ct): ?><option value="<?php echo $ct['id']; ?>"><?php echo $ct['name']; ?></option><?php endforeach; ?></select></div>
                    <div class="form-group"><label>URL Stream</label><input type="text" class="form-control" name="stream_url" id="editUrl" required></div>
                    <div class="form-group"><label>Logo</label><input type="text" class="form-control" name="logo_url" id="editLogo"></div>
                    <button type="submit" class="btn btn-success btn-block font-weight-bold py-2">SALVAR</button>
                </form>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="modalCat" tabindex="-1">
    <div class="modal-dialog modal-sm modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-info border-0"><h5 class="modal-title">Nova Categoria</h5><button class="close" data-dismiss="modal">×</button></div>
            <div class="modal-body">
                <form id="formCat">
                    <input type="hidden" name="action" value="save_category">
                    <input type="hidden" name="type" value="channel">
                    <input type="text" class="form-control mb-3" name="name" placeholder="Ex: Esportes" required>
                    <button class="btn btn-info btn-block">CRIAR</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script>
    $('#btnToggleMenu, #overlayMenu').click(function() { $('#sidebar').toggleClass('active'); $('#overlayMenu').toggleClass('active'); $('#btnToggleMenu').toggleClass('is-active'); });
    function openModal() { $('#formContent')[0].reset(); $('#editId').val(''); $('#modalContent').modal('show'); }
    function edit(id) { $.get('api/content.php?action=get_channel&id='+id, function(res){ if(res.status) { var d = res.data; $('#editId').val(d.id); $('#editName').val(d.name); $('#editUrl').val(d.stream_url); $('#editLogo').val(d.logo_url); $('#editCat').val(d.category_id); $('#editTranscode').val(d.transcode_quality || 'original'); $('#modalContent').modal('show'); } }, 'json'); }
    
    function controlStream(id, action) { 
        let txt = action=='start' ? 'Ativando...' : (action=='restart' ? 'Reiniciando...' : 'Desativando...');
        toastr.info(txt); 
        $.post('api/stream_control.php', {id: id, action: action}, function(res){ 
            if(res.status) { toastr.success(res.msg); setTimeout(() => location.reload(), 1000); } 
            else { toastr.error('Erro'); } 
        }, 'json'); 
    }
    
    // === AÇÕES EM MASSA ===
    function toggleAll(source) {
        $('.chk-item').prop('checked', source.checked);
        updateMassPanel();
    }

    function updateMassPanel() {
        let count = $('.chk-item:checked').length;
        $('#selCount').text(count);
        if(count > 0) $('#massPanel').slideDown(); else $('#massPanel').slideUp();
    }

    function massAction(action) {
        let ids = [];
        $('.chk-item:checked').each(function() { ids.push($(this).val()); });
        if(ids.length === 0) return;

        if(!confirm('Confirmar ação em massa para ' + ids.length + ' canais?')) return;

        toastr.info('Processando em massa...');
        
        // Loop simples para enviar comandos (pode ser otimizado no backend depois)
        let total = ids.length;
        let processed = 0;

        // Se for delete, usa API de conteúdo. Se for stream, usa stream_control
        let url = (action === 'delete') ? 'api/content.php' : 'api/stream_control.php';
        let act = (action === 'delete') ? 'delete_channel' : action;

        // Para evitar timeout, vamos mandar um request com todos os IDs (precisa adaptar a API se quiser 1 request)
        // Por enquanto, faremos loop para garantir compatibilidade
        ids.forEach(id => {
            $.post(url, {id: id, action: act}, function() {
                processed++;
                if(processed === total) {
                    toastr.success('Concluído!');
                    setTimeout(() => location.reload(), 1000);
                }
            });
        });
    }
    
    function del(id) { if(confirm('Excluir?')) { $.post('api/content.php', {action:'delete_channel', id:id}, function(res){ if(res.status){ toastr.success('Excluído!'); setTimeout(()=>location.reload(), 1000); } }, 'json'); } }
    $('#formContent').submit(function(e){ e.preventDefault(); $.post('api/content.php', $(this).serialize(), function(res){ if(res.status){ toastr.success(res.msg); setTimeout(()=>location.reload(), 1000); } else { toastr.error(res.msg); } }, 'json'); });
    $('#formCat').submit(function(e){ e.preventDefault(); $.post('api/content.php', $(this).serialize(), function(res){ if(res.status){ toastr.success(res.msg); setTimeout(()=>location.reload(), 1000); } }, 'json'); });
</script>
</body>
</html>