<?php
// series.php - Gerenciador de Séries (IDÊNTICO AOS CANAIS E FILMES COM TEMPO ATIVO)
session_start();
require_once 'includes/db.php';

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

// ==============================================================================
// 🛠️ AUTO-CORREÇÃO DO BANCO DE DADOS (Cria Proxy e Uptime automaticamente)
// ==============================================================================
try { $pdo->query("SELECT is_proxy FROM series LIMIT 1"); } 
catch (Exception $e) { $pdo->query("ALTER TABLE series ADD is_proxy INT(1) DEFAULT 0"); }

try { $pdo->query("SELECT uptime FROM series LIMIT 1"); } 
catch (Exception $e) { $pdo->query("ALTER TABLE series ADD uptime DATETIME NULL"); }

// ==============================================================================
// 🚀 FUNÇÃO DE TEMPO (Uptime)
// ==============================================================================
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 ''; }
}

// ==============================================================================
// 🚀 MINI-API INTERNA (Ações de Ligar/Desligar sem sair da página)
// ==============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['internal_action'])) {
    if(ob_get_length()) ob_clean(); 
    header('Content-Type: application/json');
    $action = $_POST['internal_action'];
    
    if ($action === 'toggle_proxy') {
        $id = (int)$_POST['id'];
        $status = (int)$_POST['status'];
        
        if ($status == 1) {
            $pdo->query("UPDATE series SET is_proxy = 1, uptime = NOW() WHERE id = $id");
        } else {
            $pdo->query("UPDATE series SET is_proxy = 0, uptime = NULL WHERE id = $id");
        }
        echo json_encode(['status' => true, 'msg' => 'Modo alterado com sucesso!']);
        exit;
    }
    
    if ($action === 'restart_proxy') {
        $id = (int)$_POST['id'];
        $pdo->query("DELETE FROM active_connections WHERE content_id = $id AND stream_type = 'series'");
        echo json_encode(['status' => true, 'msg' => 'Conexões da série reiniciadas!']);
        exit;
    }

    if ($action === 'mass_action') {
        $ids = isset($_POST['ids']) ? $_POST['ids'] : [];
        $cmd = $_POST['cmd'];
        if (!empty($ids)) {
            $in_clause = implode(',', array_map('intval', $ids));
            if ($cmd === 'proxy') {
                $pdo->query("UPDATE series SET is_proxy = 1, uptime = NOW() WHERE id IN ($in_clause)");
            } elseif ($cmd === 'direct') {
                $pdo->query("UPDATE series SET is_proxy = 0, uptime = NULL WHERE id IN ($in_clause)");
            } elseif ($cmd === 'restart') {
                $pdo->query("DELETE FROM active_connections WHERE content_id IN ($in_clause) AND stream_type = 'series'");
            }
        }
        echo json_encode(['status' => true, 'msg' => 'Ação em massa concluída!']);
        exit;
    }
}
// ==============================================================================

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

// --- 2. FILTROS DA URL ---
$cat_filter = isset($_GET['cat']) ? (int)$_GET['cat'] : 0;
$status_filter = isset($_GET['status']) ? $_GET['status'] : 'all';
$search_query = isset($_GET['q']) ? $_GET['q'] : '';

// --- 3. BUSCAR SÉRIES (Com Contagem Online) ---
$sql = "SELECT s.*, c.name as cat_name,
        (SELECT COUNT(*) FROM active_connections WHERE content_id = s.id AND stream_type = 'series') as online_users
        FROM series s 
        LEFT JOIN categories c ON s.category_id = c.id 
        WHERE 1=1";
$params = [];

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

if ($status_filter === '1') {
    $sql .= " AND s.is_proxy = 1"; 
} elseif ($status_filter === '0') {
    $sql .= " AND (s.is_proxy = 0 OR s.is_proxy IS NULL)"; 
}

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

$sql .= " ORDER BY online_users DESC, s.id DESC LIMIT 100";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$series = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Gerenciar Séries</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; margin-bottom: 0; }
        .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; }
        .form-control:focus { background-color: #333; border-color: #007bff; color: #fff; }
        .modal-content { background-color: #1f1f1f; border: 1px solid #333; color: #fff; }
        .close { color: #fff; }
        .series-cover { width: 40px; height: 60px; object-fit: cover; border-radius: 4px; background: #000; 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; }
        }

        /* Animação e Estilos de Massa */
        .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); }
        }
        .mass-actions { display: none; margin-bottom: 15px; background: #2a2a2a; padding: 10px; border-radius: 5px; border: 1px solid #444; }

        /* TMDB Resultados */
        #tmdbResults { max-height: 250px; overflow-y: auto; margin-top: 5px; border: 1px solid #444; display: none; background: #222; border-radius: 5px; }
        .tmdb-item { cursor: pointer; padding: 10px; border-bottom: 1px solid #333; display: flex; align-items: center; }
        .tmdb-item:hover { background-color: #333; }
        .tmdb-item img { width: 35px; height: 50px; object-fit: cover; margin-right: 10px; }
    </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">Gerenciar Séries</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-warning"></i> Séries</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> Nova Série</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="massControl('proxy')"><i class="fa fa-play"></i> Iniciar (Proxy)</button>
        <button class="btn btn-sm btn-secondary mr-1" onclick="massControl('direct')"><i class="fa fa-stop"></i> Parar (Direct)</button>
        <button class="btn btn-sm btn-warning mr-1" onclick="massControl('restart')"><i class="fa fa-sync-alt"></i> Reiniciar</button>
        <button class="btn btn-sm btn-danger" onclick="massDelete()"><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 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</option>
                        <option value="0" <?php echo $status_filter=='0'?'selected':''; ?>>🟢 Apenas Direct</option>
                    </select>
                </div>

                <div class="col-md-5 col-10 mb-2 mb-md-0">
                    <div class="input-group">
                        <input type="text" name="q" class="form-control" placeholder="Buscar série..." 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="series.php" class="btn btn-outline-light btn-block" title="Limpar Filtros"><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">Capa</th>
                        <th>Nome</th>
                        <th class="d-none d-sm-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($series) > 0): ?>
                        <?php foreach($series as $s): 
                            $is_proxy = isset($s['is_proxy']) && $s['is_proxy'] == 1;
                        ?>
                        <tr>
                            <td class="text-center"><input type="checkbox" class="chk-item" value="<?php echo $s['id']; ?>" onclick="updateMassPanel()"></td>
                            
                            <td class="text-center">
                                <?php if($is_proxy): ?>
                                    <span class="badge badge-success shadow-sm pulse-live mb-1" title="Rodando na sua VPS">ON</span>
                                    <br>
                                    <small class="text-success font-weight-bold" style="font-size: 0.75rem;">
                                        <i class="fa fa-clock"></i> <?php echo formatUptime($s['uptime']); ?>
                                    </small>
                                <?php else: ?>
                                    <span class="badge badge-secondary" title="Link Direto">OFF</span>
                                <?php endif; ?>
                            </td>

                            <td class="text-center p-1">
                                <img src="<?php echo $s['cover_url'] ?: 'https://via.placeholder.com/40x60?text=?'; ?>" class="series-cover" onerror="this.src='https://via.placeholder.com/40x60?text=Erro'">
                            </td>
                            
                            <td>
                                <div class="font-weight-bold text-white"><?php echo htmlspecialchars($s['name']); ?></div>
                                <div class="d-sm-none text-muted small"><?php echo $s['cat_name'] ?: 'Sem Categoria'; ?></div>
                            </td>
                            
                            <td class="d-none d-sm-table-cell">
                                <span class="badge badge-dark border border-secondary"><?php echo $s['cat_name'] ?: 'Sem Categoria'; ?></span>
                            </td>

                            <td class="text-center">
                                <?php if($is_proxy && $s['online_users'] > 0): ?>
                                    <span class="badge badge-info shadow-sm" style="font-size: 0.9rem;">
                                        <i class="fa fa-users"></i> <?php echo $s['online_users']; ?>
                                    </span>
                                <?php else: ?>
                                    <span class="text-muted small">-</span>
                                <?php endif; ?>
                            </td>

                            <td class="text-center">
                                <?php if($is_proxy): ?>
                                    <button class="btn btn-sm btn-danger font-weight-bold mb-1" onclick="toggleProxy(<?php echo $s['id']; ?>, 0)" title="Virar Direct">
                                        <i class="fa fa-stop"></i> Proxy
                                    </button>
                                    <button class="btn btn-sm btn-warning font-weight-bold mb-1" onclick="restartProxy(<?php echo $s['id']; ?>)" title="Derrubar usuários">
                                        <i class="fa fa-sync-alt"></i>
                                    </button>
                                <?php else: ?>
                                    <button class="btn btn-sm btn-success font-weight-bold mb-1" onclick="toggleProxy(<?php echo $s['id']; ?>, 1)" title="Virar Proxy">
                                        <i class="fa fa-play"></i> Direct
                                    </button>
                                <?php endif; ?>
                            </td>

                            <td class="text-right pr-4">
                                <a href="series_details.php?id=<?php echo $s['id']; ?>" class="btn btn-sm btn-warning mr-1" title="Gerenciar Episódios">
                                    <i class="fa fa-list-ol"></i>
                                </a>
                                <button class="btn btn-sm btn-info mr-1" onclick="edit(<?php echo $s['id']; ?>)"><i class="fa fa-pen"></i></button>
                                <button class="btn btn-sm btn-danger" onclick="del(<?php echo $s['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">Nenhuma série encontrada.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="modalContent" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header border-secondary bg-dark">
                <h5 class="modal-title"><i class="fa fa-tv"></i> Dados da Série</h5>
                <button type="button" class="close text-white" data-dismiss="modal">×</button>
            </div>
            <div class="modal-body">
                
                <div class="card bg-secondary mb-3 p-2 border-0">
                    <label class="text-white mb-1 font-weight-bold"><i class="fab fa-searchengin"></i> Buscar no TMDB (Auto-Preencher)</label>
                    <div class="input-group">
                        <input type="text" id="tmdbSearch" class="form-control border-0" placeholder="Nome da série e Enter...">
                        <div class="input-group-append">
                            <button class="btn btn-warning font-weight-bold" type="button" onclick="searchTMDB()">BUSCAR</button>
                        </div>
                    </div>
                    <div id="tmdbResults"></div>
                </div>

                <form id="formContent">
                    <input type="hidden" name="action" value="save_series">
                    <input type="hidden" name="id" id="editId">
                    
                    <div class="row">
                        <div class="col-md-8">
                            <div class="form-group">
                                <label>Nome da Série</label>
                                <input type="text" class="form-control" name="name" id="editName" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>Categoria</label>
                                <select class="form-control" name="category_id" id="editCat">
                                    <option value="0">-- Selecione --</option>
                                    <?php foreach($cats as $ct): ?>
                                        <option value="<?php echo $ct['id']; ?>"><?php echo $ct['name']; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="font-weight-bold"><i class="fa fa-random"></i> Modo de Transmissão (Para todos os episódios)</label>
                        <select class="form-control font-weight-bold" name="is_proxy" id="editProxy">
                            <option value="0" class="text-success">🟢 Direct (Link Direto - Não consome a VPS)</option>
                            <option value="1" class="text-danger">🔴 Proxy (Esconde a Fonte - Consome banda da VPS)</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>URL da Capa</label>
                        <input type="text" class="form-control" name="cover_url" id="editCover" placeholder="http://...">
                    </div>

                    <div class="form-group">
                        <label>Sinopse</label>
                        <textarea class="form-control" name="description" id="editDesc" rows="4"></textarea>
                    </div>

                    <button type="submit" class="btn btn-success btn-block font-weight-bold py-2">SALVAR SÉRIE</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 text-white" 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="series">
                    <label>Nome</label>
                    <input type="text" class="form-control mb-3" name="name" 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>
    const TMDB_KEY = 'f99aa9ae1fe7619969cc7db0938c1ae5';

    // Menu Mobile
    $('#btnToggleMenu, #overlayMenu').click(function() {
        $('#sidebar').toggleClass('active');
        $('#overlayMenu').toggleClass('active');
        $('#btnToggleMenu').toggleClass('is-active');
    });

    function openModal() {
        $('#formContent')[0].reset();
        $('#editId').val('');
        $('#editProxy').val('0');
        $('#tmdbResults').hide();
        $('#modalContent').modal('show');
    }

    // === AÇÕES DE PROXY / DIRECT (INDIVIDUAL) ===
    function toggleProxy(id, status) {
        toastr.info('Alterando modo...');
        $.post('series.php', { internal_action: 'toggle_proxy', id: id, status: status }, function(res) {
            if(res && res.status) { 
                toastr.success(res.msg); 
                setTimeout(() => location.reload(), 600); 
            } else {
                toastr.error('Erro ao atualizar.');
            }
        }, 'json').fail(function() {
            toastr.error('Erro no servidor.');
        });
    }

    function restartProxy(id) {
        toastr.info('Derrubando conexões...');
        $.post('series.php', { internal_action: 'restart_proxy', id: id }, function(res) {
            if(res && res.status) { toastr.success(res.msg); setTimeout(() => location.reload(), 600); }
        }, '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 massControl(cmd) {
        let ids = [];
        $('.chk-item:checked').each(function() { ids.push($(this).val()); });
        if(ids.length === 0) return;

        if(!confirm('Aplicar ação em ' + ids.length + ' séries?')) return;
        toastr.info('Processando...');

        $.post('series.php', { internal_action: 'mass_action', cmd: cmd, ids: ids }, function(res) {
            if(res && res.status) { toastr.success(res.msg); setTimeout(() => location.reload(), 800); }
        }, 'json');
    }

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

        if(!confirm('TEM CERTEZA que deseja excluir ' + ids.length + ' séries? Os episódios também serão apagados!')) return;
        
        let total = ids.length;
        let processed = 0;
        toastr.info('Excluindo...');
        
        ids.forEach(id => {
            $.post('api/content.php', { action: 'delete_series', id: id }, function() {
                processed++;
                if(processed === total) { toastr.success('Excluídas!'); setTimeout(() => location.reload(), 800); }
            });
        });
    }

    // Busca TMDB (Séries - endpoint /tv)
    function searchTMDB() {
        let q = $('#tmdbSearch').val();
        if(q.length < 2) return toastr.warning('Digite o nome da série');
        
        $('#tmdbResults').show().html('<div class="p-2 text-center"><i class="fa fa-spinner fa-spin"></i></div>');
        
        $.get(`https://api.themoviedb.org/3/search/tv?api_key=${TMDB_KEY}&language=pt-BR&query=${encodeURIComponent(q)}`, function(res){
            $('#tmdbResults').empty();
            if(!res.results.length) return $('#tmdbResults').html('<div class="p-2 text-muted text-center">Nada encontrado.</div>');
            
            res.results.forEach(s => {
                let img = s.poster_path ? `https://image.tmdb.org/t/p/w92${s.poster_path}` : 'https://via.placeholder.com/35x50';
                let year = s.first_air_date ? s.first_air_date.substr(0,4) : '';
                let safeName = s.name.replace(/"/g, '&quot;');
                let safeDesc = s.overview ? s.overview.replace(/"/g, '&quot;') : '';
                let safeImg = s.poster_path ? `https://image.tmdb.org/t/p/w500${s.poster_path}` : '';

                let html = `
                <div class="tmdb-item" onclick='fillData("${safeName}", "${safeImg}", "${safeDesc}")'>
                    <img src="${img}">
                    <div>
                        <div class="font-weight-bold text-white">${s.name} <small class="text-warning">(${year})</small></div>
                        <small class="text-muted">⭐ ${s.vote_average}</small>
                    </div>
                </div>`;
                $('#tmdbResults').append(html);
            });
        });
    }

    function fillData(name, img, desc) {
        $('#editName').val(name);
        $('#editCover').val(img);
        $('#editDesc').val(desc);
        $('#tmdbResults').hide();
        toastr.success('Dados preenchidos!');
    }

    function edit(id) {
        $.get('api/content.php?action=get_series&id='+id, function(r){
            if(r.status) {
                let d = r.data;
                $('#editId').val(d.id);
                $('#editName').val(d.name);
                $('#editCover').val(d.cover_url);
                $('#editDesc').val(d.description);
                $('#editCat').val(d.category_id);
                $('#editProxy').val(d.is_proxy !== undefined ? d.is_proxy : 0);
                $('#modalContent').modal('show');
            }
        }, 'json');
    }

    function del(id) {
        if(confirm('Tem certeza? Isso apagará todas as temporadas e episódios vinculados!')) {
            $.post('api/content.php', {action:'delete_series', id:id}, function(){ location.reload(); });
        }
    }

    $('#formContent').submit(function(e){
        e.preventDefault();
        $.post('api/content.php', $(this).serialize(), function(r){
            if(r.status) { toastr.success(r.msg); setTimeout(()=>location.reload(), 1000); }
            else toastr.error(r.msg);
        }, 'json');
    });

    $('#formCat').submit(function(e){
        e.preventDefault();
        $.post('api/content.php', $(this).serialize(), function(r){
            if(r.status) { toastr.success(r.msg); setTimeout(()=>location.reload(), 1000); }
        }, 'json');
    });

    $('#tmdbSearch').keypress(function(e){ if(e.which==13) searchTMDB(); });
</script>
</body>
</html>