<?php
session_start();
require_once 'includes/db.php';

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

// Buscar Dados
try {
    $series = $pdo->query("SELECT * FROM series ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
    $cats = $pdo->query("SELECT * FROM categories WHERE type='series'")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $series = []; $cats = []; }
?>

<!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://vendedorp2p.com/views/_css/bootstrap/bootstrap.min.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_fonts/font-awesome/css/all.min.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_plugins/toastr/toastr.min.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/hamburgers/hamburgers.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-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: 45px; height: 65px; object-fit: cover; border-radius: 4px; border: 1px solid #444; }
        
        /* TMDB Search */
        #tmdbResults { max-height: 250px; overflow-y: auto; margin-bottom: 15px; border: 1px solid #444; display: none; }
        .tmdb-item { cursor: pointer; padding: 10px; border-bottom: 1px solid #333; display: flex; align-items: center; transition: 0.2s; }
        .tmdb-item:hover { background-color: #333; }
        .tmdb-item img { width: 40px; height: 60px; object-fit: cover; margin-right: 10px; border-radius: 3px; }
        .tmdb-info h6 { margin: 0; font-size: 14px; color: #fff; }
        
        /* Sidebar Responsivo */
        @media (min-width: 992px) {
            #sidebar { width: 240px; position: fixed; top: 0; left: 0; height: 100vh; z-index: 1000; overflow-y: auto; }
            .container-fluid { margin-left: 240px; width: calc(100% - 240px); }
            .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-fluid { margin-left: 0; width: 100%; padding-top: 10px; }
            .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; }
        }
    </style>
</head>
<body>

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

<div class="container-fluid mt-4 mb-5" style="max-width: 1400px;">
    
    <div class="d-lg-none d-flex justify-content-between align-items-center mb-3 bg-dark p-2 rounded">
        <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">Séries</span>
        <div></div>
    </div>

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="d-none d-lg-block">🍿 Gerenciar Séries</h3>
        <div>
            <a href="dashboard.php" class="btn btn-secondary mr-2"><i class="fa fa-arrow-left"></i> Voltar</a>
            <button class="btn btn-info mr-2" onclick="$('#modalCat').modal('show')"><i class="fa fa-tags"></i> Categoria</button>
            <button class="btn btn-success" onclick="openModal()"><i class="fa fa-plus"></i> Nova Série</button>
        </div>
    </div>

    <div class="card shadow-sm">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0 align-middle">
                    <thead class="thead-light">
                        <tr>
                            <th width="80" class="text-center">Capa</th>
                            <th>Nome</th>
                            <th>Sinopse</th>
                            <th class="text-right">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(count($series) > 0): ?>
                            <?php foreach($series as $s): ?>
                            <tr>
                                <td class="text-center">
                                    <img src="<?php echo !empty($s['cover_url']) ? $s['cover_url'] : 'https://via.placeholder.com/45x65?text=Capa'; ?>" class="series-cover">
                                </td>
                                <td class="font-weight-bold"><?php echo htmlspecialchars($s['name']); ?></td>
                                <td>
                                    <small class="text-muted">
                                        <?php echo substr(htmlspecialchars($s['description']), 0, 60) . '...'; ?>
                                    </small>
                                </td>
                                <td class="text-right">
                                    <a href="series_details.php?id=<?php echo $s['id']; ?>" class="btn btn-sm btn-warning" title="Gerenciar Episódios">
                                        <i class="fa fa-list-ol"></i>
                                    </a>
                                    
                                    <button class="btn btn-sm btn-primary" onclick="edit(<?php echo $s['id']; ?>)" title="Editar"><i class="fa fa-edit"></i></button>
                                    <button class="btn btn-sm btn-danger" onclick="del(<?php echo $s['id']; ?>)" title="Excluir"><i class="fa fa-trash"></i></button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="4" class="text-center p-5 text-muted">Nenhuma série cadastrada.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </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 bg-dark">
                <h5 class="modal-title"><i class="fa fa-tv"></i> Dados da Série</h5>
                <button type="button" class="close" 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 Série (TMDB)</label>
                    <div class="input-group">
                        <input type="text" id="tmdbSearch" class="form-control" placeholder="Digite o nome e aperte 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" class="bg-dark mt-2 rounded"></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">Sem Categoria</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>URL da Capa (Poster)</label>
                        <div class="input-group">
                            <input type="text" class="form-control" name="cover_url" id="editCover" placeholder="http://...">
                            <div class="input-group-append">
                                <button class="btn btn-outline-secondary" type="button" onclick="window.open($('#editCover').val(), '_blank')">Ver</button>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Sinopse / Descrição</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" 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 da Categoria</label>
                    <input type="text" class="form-control mb-3" name="name" placeholder="Ex: Animes..." required>
                    <button class="btn btn-info btn-block font-weight-bold">CRIAR</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="https://vendedorp2p.com/views/_js/jquery/jquery-3.1.1.min.js"></script>
<script src="https://vendedorp2p.com/views/_js/bootstrap/bootstrap.min.js"></script>
<script src="https://vendedorp2p.com/views/_plugins/toastr/toastr.min.js"></script>

<script>
const TMDB_API_KEY = 'f99aa9ae1fe7619969cc7db0938c1ae5'; 
const TMDB_IMG_URL = 'https://image.tmdb.org/t/p/w500';

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

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

function searchTMDB() {
    var query = $('#tmdbSearch').val();
    if(query.length < 2) { toastr.warning('Digite pelo menos 2 letras'); return; }
    $('#tmdbResults').show().html('<div class="p-3 text-center"><i class="fa fa-spinner fa-spin"></i> Buscando...</div>');

    $.ajax({
        url: `https://api.themoviedb.org/3/search/tv?api_key=${TMDB_API_KEY}&query=${encodeURIComponent(query)}&language=pt-BR`,
        method: 'GET',
        success: function(res) {
            $('#tmdbResults').empty();
            if(!res.results || res.results.length === 0) {
                $('#tmdbResults').html('<div class="p-2 text-center text-muted">Nenhuma série encontrada.</div>');
                return;
            }
            res.results.forEach(function(show) {
                let poster = show.poster_path ? (TMDB_IMG_URL + show.poster_path) : 'https://via.placeholder.com/45x60?text=S/IMG';
                let year = show.first_air_date ? show.first_air_date.split('-')[0] : '???';
                let safeName = show.name.replace(/'/g, "&apos;").replace(/"/g, "&quot;");
                let safeDesc = show.overview ? show.overview.replace(/'/g, "&apos;").replace(/"/g, "&quot;") : '';

                let html = `<div class="tmdb-item" onclick='selectTMDB("${safeName}", "${poster}", "${safeDesc}")'><img src="${poster}"><div class="tmdb-info"><h6>${show.name} (${year})</h6><small class="text-warning">⭐ ${show.vote_average}</small></div></div>`;
                $('#tmdbResults').append(html);
            });
        },
        error: function() { $('#tmdbResults').html('<div class="p-2 text-danger">Erro na API.</div>'); }
    });
}

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

function edit(id) {
    $.get('api/content.php?action=get_series&id='+id, function(res){
        if(res.status) {
            var d = res.data;
            $('#editId').val(d.id);
            $('#editName').val(d.name);
            $('#editCover').val(d.cover_url);
            $('#editDesc').val(d.description);
            $('#editCat').val(d.category_id);
            $('#tmdbResults').hide();
            $('#modalContent').modal('show');
        }
    }, 'json');
}

function del(id) {
    if(confirm('Tem certeza? Isso pode apagar temporadas vinculadas.')) {
        $.post('api/content.php', {action:'delete_series', id:id}, function(res){
            if(res.status){ toastr.success(res.msg); 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); $('#modalContent').modal('hide'); 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');
});

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