<?php
// movies.php - Gerenciador de Filmes (Com Filtro de Categoria)
session_start();
require_once 'includes/db.php';

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

// Busca Categorias para o Filtro
try {
    $cats = $pdo->query("SELECT * FROM categories WHERE type='movie' ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $cats = []; }

// Filtro Atual (da URL)
$cat_filter = isset($_GET['cat']) ? (int)$_GET['cat'] : 0;
$search_query = isset($_GET['q']) ? $_GET['q'] : '';

// Query de Filmes
$sql = "SELECT m.*, c.name as cat_name FROM movies m LEFT JOIN categories c ON m.category_id = c.id WHERE 1=1";
$params = [];

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

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

$sql .= " ORDER BY m.id DESC LIMIT 100"; // Limite de 100 para não travar, use paginação real se tiver milhares
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$movies = $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 Filmes</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; }
        .movie-cover { width: 40px; height: 60px; object-fit: cover; border-radius: 4px; background: #000; }
        
        /* Menu Responsivo */
        @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; }
        }

        /* 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">Filmes</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-film text-danger"></i> Filmes</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 Filme</button>
        </div>
    </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-4 col-6 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-6 col-6 mb-2 mb-md-0">
                    <div class="input-group">
                        <input type="text" name="q" class="form-control" placeholder="Buscar filme..." 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-2">
                    <a href="movies.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="60">Capa</th>
                        <th>Nome</th>
                        <th class="d-none d-sm-table-cell">Categoria</th>
                        <th class="text-right pr-4">Ações</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(count($movies) > 0): ?>
                        <?php foreach($movies as $m): ?>
                        <tr>
                            <td class="text-center p-1">
                                <img src="<?php echo $m['cover_url'] ?: 'https://via.placeholder.com/40x60?text=?'; ?>" class="movie-cover" onerror="this.src='https://via.placeholder.com/40x60?text=Erro'">
                            </td>
                            <td>
                                <div class="font-weight-bold text-white"><?php echo htmlspecialchars($m['name']); ?></div>
                                <div class="d-sm-none text-muted small"><?php echo $m['cat_name'] ?: 'Sem Categoria'; ?></div>
                            </td>
                            <td class="d-none d-sm-table-cell">
                                <span class="badge badge-dark border border-secondary"><?php echo $m['cat_name'] ?: 'Sem Categoria'; ?></span>
                            </td>
                            <td class="text-right pr-4">
                                <button class="btn btn-sm btn-info" onclick="edit(<?php echo $m['id']; ?>)"><i class="fa fa-pen"></i></button>
                                <button class="btn btn-sm btn-danger" onclick="del(<?php echo $m['id']; ?>)"><i class="fa fa-trash"></i></button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="4" class="text-center py-5 text-muted">Nenhum filme encontrado com estes filtros.</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-film"></i> Dados do Filme</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="Digite o nome e tecle 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_movie">
                    <input type="hidden" name="id" id="editId">
                    
                    <div class="row">
                        <div class="col-md-8">
                            <div class="form-group">
                                <label>Nome do Filme</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>URL do Vídeo (M3U8 / MP4 / MKV)</label>
                        <input type="text" class="form-control" name="stream_url" id="editUrl" required placeholder="http://...">
                    </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="3"></textarea>
                    </div>

                    <button type="submit" class="btn btn-success btn-block font-weight-bold py-2">SALVAR DADOS</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="movie">
                    <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'; // Chave TMDB Pública

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

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

    // Busca TMDB (Front-end)
    function searchTMDB() {
        let q = $('#tmdbSearch').val();
        if(q.length < 2) return toastr.warning('Digite o nome do filme');
        
        $('#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/movie?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(m => {
                let img = m.poster_path ? `https://image.tmdb.org/t/p/w92${m.poster_path}` : 'https://via.placeholder.com/35x50';
                let year = m.release_date ? m.release_date.substr(0,4) : '';
                let safeName = m.title.replace(/"/g, '&quot;');
                let safeDesc = m.overview ? m.overview.replace(/"/g, '&quot;') : '';
                let safeImg = m.poster_path ? `https://image.tmdb.org/t/p/w500${m.poster_path}` : '';

                let html = `
                <div class="tmdb-item" onclick='fillData("${safeName}", "${safeImg}", "${safeDesc}")'>
                    <img src="${img}">
                    <div>
                        <div class="font-weight-bold text-white">${m.title} <small class="text-warning">(${year})</small></div>
                        <small class="text-muted">⭐ ${m.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_movie&id='+id, function(r){
            if(r.status) {
                let d = r.data;
                $('#editId').val(d.id);
                $('#editName').val(d.name);
                $('#editUrl').val(d.stream_url);
                $('#editCover').val(d.cover_url);
                $('#editDesc').val(d.description);
                $('#editCat').val(d.category_id);
                $('#modalContent').modal('show');
            }
        }, 'json');
    }

    function del(id) {
        if(confirm('Apagar filme?')) {
            $.post('api/content.php', {action:'delete_movie', 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>
