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

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

// Validação
$id_serie = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id_serie <= 0) { header('Location: series.php'); exit; }

// Busca Série
try {
    $stmt = $pdo->prepare("SELECT * FROM series WHERE id = ?");
    $stmt->execute([$id_serie]);
    $serie = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$serie) { die("<script>alert('Série não encontrada');window.location='series.php';</script>"); }
} catch (Exception $e) { die("Erro de banco de dados."); }
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Gerenciar: <?php echo htmlspecialchars($serie['name']); ?></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://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; }
        .list-group-item { background-color: #252525; border-color: #333; color: #fff; cursor: pointer; transition: 0.2s; }
        .list-group-item:hover, .list-group-item.active { background-color: #007bff; border-color: #007bff; color: #fff; }
        .form-control { 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; }
        .table { color: #bbb; }
        .table-hover tbody tr:hover { background-color: #2c2c2c; }
        
        /* Ajuste menu */
        @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">Detalhes da Série</span>
        <div></div>
    </div>

    <div class="card bg-dark border-secondary mb-4">
        <div class="card-body d-flex align-items-center p-3">
            <img src="<?php echo !empty($serie['cover_url']) ? $serie['cover_url'] : 'https://via.placeholder.com/50x70'; ?>" width="60" class="mr-3 rounded shadow-sm">
            <div>
                <h4 class="mb-0 font-weight-bold text-white"><?php echo htmlspecialchars($serie['name']); ?></h4>
                <small class="text-muted">Gerenciador de Temporadas e Episódios</small>
            </div>
            <div class="ml-auto">
                <a href="series.php" class="btn btn-secondary"><i class="fa fa-arrow-left"></i> Voltar</a>
            </div>
        </div>
    </div>

    <div class="row">
        
        <div class="col-md-4 mb-4">
            <div class="card h-100 shadow-sm">
                <div class="card-header bg-secondary text-white d-flex justify-content-between align-items-center">
                    <h6 class="mb-0 font-weight-bold"><i class="fa fa-folder"></i> TEMPORADAS</h6>
                    <button class="btn btn-sm btn-success" onclick="$('#modalSeason').modal('show')"><i class="fa fa-plus"></i> Nova</button>
                </div>
                <div class="card-body p-0" style="max-height: 600px; overflow-y: auto;">
                    <div class="list-group list-group-flush" id="seasonList">
                        <div class="text-center p-4 text-muted"><i class="fa fa-spinner fa-spin"></i> Carregando...</div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-8">
            <div class="card h-100 shadow-sm">
                <div class="card-header bg-dark d-flex justify-content-between align-items-center">
                    <h6 class="mb-0 font-weight-bold text-warning"><i class="fa fa-video"></i> EPISÓDIOS</h6>
                    <button class="btn btn-sm btn-primary" id="btnAddEp" onclick="openEpModal()">
                        <i class="fa fa-plus"></i> Adicionar Episódio
                    </button>
                </div>
                <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>Nome do Episódio</th>
                                    <th>Link / URL</th>
                                    <th class="text-right" width="120">Ações</th>
                                </tr>
                            </thead>
                            <tbody id="episodeList">
                                <tr><td colspan="3" class="text-center p-5 text-muted"><h5>👈 Selecione uma temporada ao lado</h5></td></tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

    </div>
</div>

<div class="modal fade" id="modalSeason" tabindex="-1">
    <div class="modal-dialog modal-sm modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-success border-0"><h5 class="modal-title text-white">Nova Temporada</h5><button class="close text-white" data-dismiss="modal">×</button></div>
            <div class="modal-body">
                <form id="formSeason">
                    <input type="hidden" name="action" value="save_season">
                    <input type="hidden" name="series_id" value="<?php echo $id_serie; ?>">
                    <label>Nome (Ex: Temporada 1)</label>
                    <input type="text" class="form-control mb-3" name="name" placeholder="Temporada X" required>
                    <button class="btn btn-success btn-block font-weight-bold">SALVAR</button>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalEpisode" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary border-0"><h5 class="modal-title text-white">Dados do Episódio</h5><button class="close text-white" data-dismiss="modal">×</button></div>
            <div class="modal-body">
                <form id="formEpisode">
                    <input type="hidden" name="action" value="save_episode">
                    <input type="hidden" name="id" id="epId">
                    <input type="hidden" name="season_id" id="epSeasonId">
                    
                    <div class="form-group">
                        <label>Nome do Episódio</label>
                        <input type="text" class="form-control" name="name" id="epName" placeholder="Ex: Ep 01 - Piloto" required>
                    </div>
                    <div class="form-group">
                        <label>URL do Arquivo (MKV/MP4/M3U8)</label>
                        <input type="text" class="form-control" name="stream_url" id="epUrl" required placeholder="http://...">
                    </div>
                    <div class="form-group">
                        <label>Capa Específica (Opcional)</label>
                        <input type="text" class="form-control" name="cover_url" id="epCover" placeholder="http://...">
                    </div>
                    
                    <button class="btn btn-primary btn-block font-weight-bold">SALVAR EPISÓDIO</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>
    var currentSeriesId = <?php echo $id_serie; ?>;
    var currentSeasonId = 0; // Começa zerado

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

    // --- CARREGAR TEMPORADAS ---
    function loadSeasons() {
        $.get('api/content.php?action=get_seasons&series_id=' + currentSeriesId, function(res){
            $('#seasonList').empty();
            if(res.status && res.data.length > 0) {
                res.data.forEach(function(s){
                    // Adiciona na lista
                    $('#seasonList').append(`
                        <div class="list-group-item list-group-item-action d-flex justify-content-between align-items-center" onclick="loadEpisodes(${s.id}, this)">
                            <span><i class="fa fa-folder-open mr-2"></i> ${s.name}</span>
                            <button class="btn btn-sm btn-outline-danger py-0 px-2 border-0" title="Excluir Temporada" onclick="delSeason(${s.id}, event)"><i class="fa fa-times"></i></button>
                        </div>
                    `);
                });
            } else {
                $('#seasonList').html('<div class="p-4 text-center text-muted">Nenhuma temporada criada.<br>Crie uma acima.</div>');
            }
        }, 'json').fail(function() { toastr.error('Erro ao conectar com a API'); });
    }

    // --- CARREGAR EPISÓDIOS ---
    function loadEpisodes(seasonId, element) {
        // Marca visualmente a temporada selecionada
        $('.list-group-item').removeClass('active');
        $(element).addClass('active');
        
        currentSeasonId = seasonId;
        
        $('#episodeList').html('<tr><td colspan="3" class="text-center p-5"><i class="fa fa-spinner fa-spin fa-2x"></i><br>Carregando episódios...</td></tr>');

        $.get('api/content.php?action=get_episodes&season_id=' + seasonId, function(res){
            $('#episodeList').empty();
            
            if(res.status && res.data.length > 0) {
                res.data.forEach(function(ep){
                    $('#episodeList').append(`
                        <tr>
                            <td class="font-weight-bold"><i class="fa fa-play-circle text-primary mr-2"></i> ${ep.name}</td>
                            <td><small class="text-muted text-monospace">${ep.stream_url.substring(0, 40)}...</small></td>
                            <td class="text-right">
                                <button class="btn btn-sm btn-info" onclick="editEp(${ep.id})"><i class="fa fa-edit"></i></button>
                                <button class="btn btn-sm btn-danger" onclick="delEp(${ep.id})"><i class="fa fa-trash"></i></button>
                            </td>
                        </tr>
                    `);
                });
            } else {
                $('#episodeList').html('<tr><td colspan="3" class="text-center p-5 text-muted"><h5><i class="fa fa-film"></i> Nenhum episódio nesta temporada.</h5><p>Clique em "Adicionar Episódio" acima.</p></td></tr>');
            }
        }, 'json');
    }

    // --- ABRIR MODAL DE EPISÓDIO ---
    function openEpModal() {
        if(currentSeasonId == 0) {
            toastr.warning('Por favor, selecione (clique) em uma temporada na lista da esquerda primeiro!');
            return;
        }
        $('#formEpisode')[0].reset();
        $('#epId').val('');
        $('#epSeasonId').val(currentSeasonId);
        $('#modalEpisode').modal('show');
    }

    // --- SALVAR TEMPORADA ---
    $('#formSeason').submit(function(e){
        e.preventDefault();
        $.post('api/content.php', $(this).serialize(), function(res){
            if(res.status){ 
                toastr.success(res.msg); 
                $('#modalSeason').modal('hide'); 
                loadSeasons(); 
                $('#formSeason')[0].reset();
            } else { toastr.error(res.msg); }
        }, 'json');
    });

    // --- DELETAR TEMPORADA ---
    function delSeason(id, e) {
        e.stopPropagation(); 
        if(confirm('⚠️ ATENÇÃO: Isso apagará a temporada e TODOS os episódios dentro dela.\n\nDeseja continuar?')) {
            $.post('api/content.php', {action: 'delete_season', id: id}, function(res){
                if(res.status){ 
                    toastr.success(res.msg); 
                    loadSeasons(); 
                    $('#episodeList').html('<tr><td colspan="3" class="text-center p-5 text-muted"><h5>👈 Selecione uma temporada ao lado</h5></td></tr>');
                    currentSeasonId = 0; 
                }
            }, 'json');
        }
    }

    // --- EDITAR EPISÓDIO ---
    function editEp(id) {
        $.get('api/content.php?action=get_single_episode&id='+id, function(res){
            if(res.status) {
                var d = res.data;
                $('#epId').val(d.id);
                $('#epSeasonId').val(d.season_id);
                $('#epName').val(d.name);
                $('#epUrl').val(d.stream_url);
                $('#epCover').val(d.cover_url);
                $('#modalEpisode').modal('show');
            }
        }, 'json');
    }

    // --- DELETAR EPISÓDIO ---
    function delEp(id) {
        if(confirm('Excluir este episódio?')) {
            $.post('api/content.php', {action: 'delete_episode', id: id}, function(res){
                if(res.status){ 
                    toastr.success(res.msg); 
                    loadEpisodes(currentSeasonId, $('.list-group-item.active')); 
                }
            }, 'json');
        }
    }

    // --- SALVAR EPISÓDIO ---
    $('#formEpisode').submit(function(e){
        e.preventDefault();
        $.post('api/content.php', $(this).serialize(), function(res){
            if(res.status){ 
                toastr.success(res.msg); 
                $('#modalEpisode').modal('hide'); 
                loadEpisodes(currentSeasonId, $('.list-group-item.active')); 
            } else { toastr.error(res.msg); }
        }, 'json');
    });

    // INICIAR
    $(document).ready(function(){ loadSeasons(); });
</script>
</body>
</html>
