<?php
session_start();
require_once 'includes/db.php';
if (!isset($_SESSION['logged_in_fxtream'])) { header('Location: index.php'); exit; }
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Gerenciar Bouquets</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">
    <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; }
        .modal-content { background-color: #1f1f1f; border: 1px solid #333; color: #fff; }
        .form-control { background-color: #2c2c2c; border: 1px solid #444; color: #fff; }
        .cat-box { max-height: 300px; overflow-y: auto; background: #111; padding: 10px; border: 1px solid #333; border-radius: 5px; }
        .custom-control-label { cursor: pointer; }
        .nav-tabs .nav-link { background: #2c2c2c; color: #aaa; border: 1px solid #333; margin-right: 5px; }
        .nav-tabs .nav-link.active { background: #007bff; color: #fff; border-color: #007bff; }
    </style>
</head>
<body>

    <nav class="navbar navbar-expand-lg navbar-dark bg-dark border-bottom border-secondary mb-4">
        <div class="container-fluid">
            <a href="dashboard.php" class="btn btn-secondary btn-sm mr-3"><i class="fa fa-arrow-left"></i> Voltar</a>
            <span class="navbar-brand h1 mb-0">Pacotes (Bouquets)</span>
        </div>
    </nav>

    <div class="container">
        <div class="d-flex justify-content-between mb-3">
            <h4>Seus Pacotes</h4>
            <button class="btn btn-success font-weight-bold" onclick="openModal()"><i class="fa fa-plus"></i> Novo Pacote</button>
        </div>

        <div class="card shadow">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="bg-secondary text-white">
                        <tr>
                            <th>Nome do Pacote</th>
                            <th class="text-center">Conteúdo</th>
                            <th class="text-right">Ações</th>
                        </tr>
                    </thead>
                    <tbody id="tableBody">
                        <tr><td colspan="3" class="text-center py-4"><i class="fa fa-spinner fa-spin"></i> Carregando...</td></tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="modal fade" id="modalBouquet" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header border-secondary">
                    <h5 class="modal-title">Gerenciar Pacote</h5>
                    <button type="button" class="close text-white" data-dismiss="modal">×</button>
                </div>
                <div class="modal-body">
                    <form id="formBouquet">
                        <input type="hidden" name="action" value="save">
                        <input type="hidden" name="id" id="editId">
                        
                        <div class="form-group">
                            <label>Nome do Pacote</label>
                            <input type="text" name="name" id="bouqName" class="form-control" required placeholder="Ex: Pacote Básico, Pacote Premium...">
                        </div>

                        <ul class="nav nav-tabs mb-3" id="myTab" role="tablist">
                            <li class="nav-item"><a class="nav-link active" data-toggle="tab" href="#tab-live">📺 Canais</a></li>
                            <li class="nav-item"><a class="nav-link" data-toggle="tab" href="#tab-movie">🎬 Filmes</a></li>
                            <li class="nav-item"><a class="nav-link" data-toggle="tab" href="#tab-series">🍿 Séries</a></li>
                        </ul>

                        <div class="tab-content">
                            <div class="tab-pane fade show active" id="tab-live">
                                <div class="form-group"><input type="text" class="form-control mb-2" placeholder="Filtrar categorias..." onkeyup="filterList(this, '#listLive')"></div>
                                <div class="text-right mb-1"><button type="button" class="btn btn-xs btn-outline-info" onclick="checkAll('#listLive')">Marcar Tudo</button></div>
                                <div class="cat-box" id="listLive">Carregando...</div>
                            </div>
                            <div class="tab-pane fade" id="tab-movie">
                                <div class="form-group"><input type="text" class="form-control mb-2" placeholder="Filtrar categorias..." onkeyup="filterList(this, '#listMovie')"></div>
                                <div class="text-right mb-1"><button type="button" class="btn btn-xs btn-outline-info" onclick="checkAll('#listMovie')">Marcar Tudo</button></div>
                                <div class="cat-box" id="listMovie">Carregando...</div>
                            </div>
                            <div class="tab-pane fade" id="tab-series">
                                <div class="form-group"><input type="text" class="form-control mb-2" placeholder="Filtrar categorias..." onkeyup="filterList(this, '#listSeries')"></div>
                                <div class="text-right mb-1"><button type="button" class="btn btn-xs btn-outline-info" onclick="checkAll('#listSeries')">Marcar Tudo</button></div>
                                <div class="cat-box" id="listSeries">Carregando...</div>
                            </div>
                        </div>

                        <button type="submit" class="btn btn-primary btn-block mt-4 font-weight-bold">SALVAR PACOTE</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>
        $(document).ready(function(){ loadList(); });

        function loadList() {
            $.post('api/bouquets_api.php', {action: 'list'}, function(data){
                let html = '';
                if(data.length == 0) html = '<tr><td colspan="3" class="text-center text-muted py-4">Nenhum pacote criado.</td></tr>';
                else {
                    data.forEach(b => {
                        let cCount = JSON.parse(b.bouq_channels || '[]').length;
                        let mCount = JSON.parse(b.bouq_movies || '[]').length;
                        let sCount = JSON.parse(b.bouq_series || '[]').length;
                        html += `<tr>
                            <td class="font-weight-bold text-warning">${b.name}</td>
                            <td class="text-center small">
                                <span class="badge badge-primary">📺 ${cCount} Cats</span>
                                <span class="badge badge-success">🎬 ${mCount} Cats</span>
                                <span class="badge badge-danger">🍿 ${sCount} Cats</span>
                            </td>
                            <td class="text-right">
                                <button class="btn btn-sm btn-info" onclick="openModal(${b.id})"><i class="fa fa-edit"></i></button>
                                <button class="btn btn-sm btn-danger" onclick="del(${b.id})"><i class="fa fa-trash"></i></button>
                            </td>
                        </tr>`;
                    });
                }
                $('#tableBody').html(html);
            }, 'json');
        }

        function openModal(id = null) {
            $('#editId').val(id ? id : '');
            $('#bouqName').val('');
            $('#listLive, #listMovie, #listSeries').html('<i class="fa fa-spinner fa-spin"></i> Carregando...');
            $('#modalBouquet').modal('show');

            $.get('api/bouquets_api.php?action=get_data' + (id ? '&id='+id : ''), function(res){
                if(id && res.bouquet) $('#bouqName').val(res.bouquet.name);
                
                // Arrays selecionados
                let selLive = id ? JSON.parse(res.bouquet.bouq_channels) : [];
                let selMov  = id ? JSON.parse(res.bouquet.bouq_movies) : [];
                let selSer  = id ? JSON.parse(res.bouquet.bouq_series) : [];

                renderCheckboxes(res.categories.live, '#listLive', 'ch_cats[]', selLive);
                renderCheckboxes(res.categories.movie, '#listMovie', 'mov_cats[]', selMov);
                renderCheckboxes(res.categories.series, '#listSeries', 'ser_cats[]', selSer);
            }, 'json');
        }

        function renderCheckboxes(list, target, name, selected) {
            let html = '';
            if(list.length === 0) html = '<div class="text-muted text-center">Nenhuma categoria encontrada.</div>';
            else {
                list.forEach(c => {
                    let checked = selected.includes(c.id.toString()) || selected.includes(c.id) ? 'checked' : '';
                    html += `<div class="custom-control custom-checkbox mb-1">
                        <input type="checkbox" class="custom-control-input" id="cat_${name}_${c.id}" name="${name}" value="${c.id}" ${checked}>
                        <label class="custom-control-label" for="cat_${name}_${c.id}">${c.name}</label>
                    </div>`;
                });
            }
            $(target).html(html);
        }

        $('#formBouquet').submit(function(e){
            e.preventDefault();
            $.post('api/bouquets_api.php', $(this).serialize(), function(r){
                if(r.status) { toastr.success(r.msg); $('#modalBouquet').modal('hide'); loadList(); }
                else toastr.error(r.msg);
            }, 'json');
        });

        function del(id) {
            if(confirm('Apagar pacote?')) {
                $.post('api/bouquets_api.php', {action:'delete', id:id}, function(){ loadList(); }, 'json');
            }
        }

        function filterList(input, target) {
            let term = $(input).val().toLowerCase();
            $(target + ' .custom-control').each(function(){
                let txt = $(this).text().toLowerCase();
                $(this).toggle(txt.indexOf(term) > -1);
            });
        }

        function checkAll(target) {
            $(target + ' input[type="checkbox"]').prop('checked', true);
        }
    </script>
</body>
</html>
