<?php
// ======================================================================
//      GERENCIADOR DE BOUQUETS COMPLETO v1.1
//      Adicionada funcionalidade de "Selecionar Tudo" por coluna.
// ======================================================================

// --- 1. CONFIGURAÇÃO E CONEXÃO ---
$db_host = 'localhost';
$db_name = 'u535247987_tvbox'; // Suas credenciais
$db_user = 'u535247987_tvbox'; // Suas credenciais
$db_pass = 'Jean#909110';      // Suas credenciais
$charset = 'utf8mb4';

try {
    $dsn = "mysql:host=$db_host;dbname=$db_name;charset=$charset";
    $options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC];
    $pdo = new PDO($dsn, $db_user, $db_pass, $options);
} catch (PDOException $e) {
    // Tratamento de erro robusto
    header('Content-Type: application/json; charset=utf-8');
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'Falha na conexão com o banco de dados.']);
    exit();
}

// --- 2. LÓGICA DA API INTERNA (PARA AJAX) ---
$action = $_POST['action'] ?? $_GET['action'] ?? '';

if ($action) {
    header('Content-Type: application/json; charset=utf-8');
    switch ($action) {
        case 'get_all_bouquets':
            $bouquets = $pdo->query("SELECT * FROM `bouquets` ORDER BY `bouquet_name` ASC")->fetchAll();
            echo json_encode(['status' => 'success', 'data' => $bouquets]);
            break;

        case 'get_bouquet_details':
            $bouquet_id = intval($_POST['id'] ?? 0);
            $all_categories = $pdo->query("SELECT id, nome, type FROM categoria ORDER BY type, position ASC")->fetchAll();
            $stmt = $pdo->prepare("SELECT category_id FROM bouquet_categories WHERE bouquet_id = ?");
            $stmt->execute([$bouquet_id]);
            $selected_categories_ids = $stmt->fetchAll(PDO::FETCH_COLUMN);
            
            echo json_encode(['status' => 'success', 'data' => ['all' => $all_categories, 'selected' => $selected_categories_ids]]);
            break;

        case 'save_bouquet':
            $id = intval($_POST['id'] ?? 0);
            $name = trim($_POST['name'] ?? '');
            $category_ids = $_POST['categories'] ?? [];
            if (empty($name)) { http_response_code(400); echo json_encode(['status' => 'error', 'message' => 'O nome do bouquet é obrigatório.']); exit(); }
            
            $pdo->beginTransaction();
            try {
                if ($id > 0) {
                    $stmt = $pdo->prepare("UPDATE bouquets SET bouquet_name = ? WHERE id = ?");
                    $stmt->execute([$name, $id]);
                } else {
                    $stmt = $pdo->prepare("INSERT INTO bouquets (bouquet_name) VALUES (?)");
                    $stmt->execute([$name]);
                    $id = $pdo->lastInsertId();
                }
                $stmt = $pdo->prepare("DELETE FROM bouquet_categories WHERE bouquet_id = ?");
                $stmt->execute([$id]);
                if (!empty($category_ids)) {
                    $stmt = $pdo->prepare("INSERT INTO bouquet_categories (bouquet_id, category_id) VALUES (?, ?)");
                    foreach ($category_ids as $cat_id) {
                        $stmt->execute([$id, intval($cat_id)]);
                    }
                }
                $pdo->commit();
                echo json_encode(['status' => 'success', 'message' => 'Bouquet salvo com sucesso!']);
            } catch (Exception $e) { $pdo->rollBack(); http_response_code(500); echo json_encode(['status' => 'error', 'message' => 'Erro ao salvar o bouquet: '.$e->getMessage()]); }
            break;
            
        case 'delete_bouquet':
            $id = intval($_POST['id'] ?? 0);
            $pdo->beginTransaction();
            try {
                $pdo->prepare("DELETE FROM bouquets WHERE id = ?")->execute([$id]);
                $pdo->prepare("DELETE FROM bouquet_categories WHERE bouquet_id = ?")->execute([$id]);
                $pdo->commit();
                echo json_encode(['status' => 'success', 'message' => 'Bouquet apagado com sucesso!']);
            } catch (Exception $e) { $pdo->rollBack(); http_response_code(500); echo json_encode(['status' => 'error', 'message' => 'Erro ao apagar o bouquet.']); }
            break;
    }
    exit();
}

// --- 3. DADOS PARA CARREGAMENTO INICIAL DA PÁGINA ---
$bouquets_iniciais = $pdo->query("SELECT * FROM `bouquets` ORDER BY `bouquet_name` ASC")->fetchAll();
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Gerenciador de Bouquets</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        body { font-family: sans-serif; background-color: #f4f4f4; margin: 0; padding: 20px; }
        .container { max-width: 900px; margin: auto; background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
        h1 { text-align: center; color: #0056b3; }
        #bouquetsTable { width: 100%; border-collapse: collapse; margin-top: 20px; }
        #bouquetsTable th, #bouquetsTable td { border: 1px solid #ddd; padding: 12px; text-align: left; }
        #bouquetsTable th { background-color: #f2f2f2; }
        .actions button { background: none; border: none; cursor: pointer; font-size: 20px; margin: 0 5px; }
        .top-actions { text-align: right; margin-bottom: 20px; }
        .action-button { font-size: 16px; font-weight: bold; padding: 10px 20px; color: #fff; border: none; border-radius: 5px; cursor: pointer; }
        #createBouquetBtn { background-color: #007bff; }
        /* Estilos do Modal */
        .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.6); display: none; justify-content: center; align-items: center; z-index: 1000; }
        .modal-content { background: #fff; padding: 30px; border-radius: 8px; width: 90%; max-width: 800px; max-height: 90vh; overflow-y: auto; }
        .modal-content h2 { margin-top: 0; }
        .modal-content input[type="text"] { width: 100%; padding: 10px; font-size: 16px; margin-bottom: 20px; box-sizing: border-box; }
        .modal-actions { text-align: right; margin-top: 20px; }
        .modal-actions button { margin-left: 10px; }
        .category-columns { display: flex; gap: 20px; }
        .category-column { flex: 1; border: 1px solid #eee; padding: 10px; border-radius: 5px; }
        .category-column h3 { margin-top: 0; }
        .category-list { max-height: 300px; overflow-y: auto; }
        .category-list label { display: block; margin-bottom: 5px; cursor: pointer; padding: 2px; border-radius: 3px; }
        .category-list label:hover { background-color: #f0f0f0; }
        .select-all-label { font-weight: bold; border-bottom: 1px solid #ccc; display: block; padding-bottom: 5px; margin-bottom: 10px; cursor: pointer; }
    </style>
</head>
<body>
    <div class="container">
        <h1>Gerenciador de Bouquets (Pacotes)</h1>
        <div class="top-actions">
            <button id="createBouquetBtn" class="action-button">Criar Novo Bouquet</button>
        </div>
        <table id="bouquetsTable">
            <thead>
                <tr>
                    <th>Nome do Bouquet</th>
                    <th width="120px">Ações</th>
                </tr>
            </thead>
            <tbody>
                </tbody>
        </table>
    </div>

    <div id="bouquetModal" class="modal-overlay">
        <div class="modal-content">
            <h2 id="modalTitle">Criar Novo Bouquet</h2>
            <input type="hidden" id="bouquet_id">
            <input type="text" id="bouquet_name" placeholder="Nome do Pacote (ex: Plano Básico)">
            <div class="category-columns">
                <div class="category-column" id="streams-column">
                    <h3>Canais</h3>
                    <label class="select-all-label"><input type="checkbox" class="select-all-checkbox" data-target-column="streams-column"> Selecionar Tudo</label>
                    <div class="category-list"></div>
                </div>
                <div class="category-column" id="movie-column">
                    <h3>Filmes</h3>
                    <label class="select-all-label"><input type="checkbox" class="select-all-checkbox" data-target-column="movie-column"> Selecionar Tudo</label>
                    <div class="category-list"></div>
                </div>
                <div class="category-column" id="series-column">
                    <h3>Séries</h3>
                    <label class="select-all-label"><input type="checkbox" class="select-all-checkbox" data-target-column="series-column"> Selecionar Tudo</label>
                    <div class="category-list"></div>
                </div>
            </div>
            <div class="modal-actions">
                <button id="cancelButton" class="action-button" style="background-color: #6c757d;">Cancelar</button>
                <button id="saveButton" class="action-button" style="background-color: #28a745;">Salvar</button>
            </div>
        </div>
    </div>

<script>
$(document).ready(function() {
    const modal = $('#bouquetModal');
    const tableBody = $('#bouquetsTable tbody');

    function loadBouquets() {
        tableBody.html('<tr><td colspan="2">Carregando...</td></tr>');
        $.get(window.location.pathname, { action: 'get_all_bouquets' }, function(res) {
            tableBody.empty();
            if (res.status === 'success' && res.data.length > 0) {
                res.data.forEach(function(bouquet) {
                    tableBody.append(`
                        <tr data-id="${bouquet.id}">
                            <td>${bouquet.bouquet_name}</td>
                            <td class="actions">
                                <button class="edit-btn" data-id="${bouquet.id}" title="Editar">✏️</button>
                                <button class="delete-btn" data-id="${bouquet.id}" title="Apagar">🗑️</button>
                            </td>
                        </tr>
                    `);
                });
            } else {
                tableBody.html('<tr><td colspan="2">Nenhum bouquet encontrado. Crie um novo.</td></tr>');
            }
        });
    }
    loadBouquets();

    function openModal(bouquet_id = 0, bouquet_name = '') {
        $('#bouquet_id').val(bouquet_id);
        $('#bouquet_name').val(bouquet_name);
        $('#modalTitle').text(bouquet_id ? 'Editar Bouquet' : 'Criar Novo Bouquet');
        $('.category-list').empty().html('Carregando...');
        $('.select-all-checkbox').prop('checked', false); // Reseta os checkboxes "selecionar tudo"
        
        $.post(window.location.pathname, { action: 'get_bouquet_details', id: bouquet_id }, function(res) {
            if (res.status === 'success') {
                $('.category-list').empty();
                res.data.all.forEach(function(cat) {
                    const isChecked = res.data.selected.includes(cat.id.toString());
                    const checkbox = `
                        <label>
                            <input type="checkbox" class="category-checkbox" value="${cat.id}" ${isChecked ? 'checked' : ''}>
                            ${cat.nome}
                        </label>`;
                    // Garante que 'movie' vá para a coluna de filmes, etc.
                    let typeColumn = cat.type;
                    if (typeColumn === 'live') { typeColumn = 'streams'; } // Normaliza o tipo, se necessário
                    $(`#${typeColumn}-column .category-list`).append(checkbox);
                });
            }
        });
        modal.css('display', 'flex');
    }
    
    $('#createBouquetBtn').on('click', () => openModal());
    
    tableBody.on('click', '.edit-btn', function() {
        const id = $(this).data('id');
        const name = $(this).closest('tr').find('td:first').text();
        openModal(id, name);
    });

    $('#cancelButton').on('click', () => modal.hide());
    
    $('#saveButton').on('click', function() {
        let selectedCategories = [];
        $('.category-checkbox:checked').each(function() {
            selectedCategories.push($(this).val());
        });
        
        $.post(window.location.pathname, {
            action: 'save_bouquet',
            id: $('#bouquet_id').val(),
            name: $('#bouquet_name').val(),
            categories: selectedCategories
        }, function(res) {
            if (res.status === 'success') {
                modal.hide();
                Swal.fire('Sucesso!', res.message, 'success');
                loadBouquets();
            } else {
                Swal.fire('Erro!', res.message, 'error');
            }
        }).fail(function() { Swal.fire('Erro!', 'Não foi possível salvar o bouquet.', 'error'); });
    });

    tableBody.on('click', '.delete-btn', function() {
        const id = $(this).data('id');
        Swal.fire({
            title: 'Tem certeza?', text: "Esta ação apagará o bouquet permanentemente!", icon: 'warning',
            showCancelButton: true, confirmButtonText: 'Sim, apagar!', cancelButtonText: 'Cancelar'
        }).then((result) => {
            if (result.isConfirmed) {
                $.post(window.location.pathname, { action: 'delete_bouquet', id: id }, function(res) {
                    if (res.status === 'success') {
                        Swal.fire('Apagado!', res.message, 'success');
                        loadBouquets();
                    } else { Swal.fire('Erro!', res.message, 'error'); }
                });
            }
        });
    });

    // [NOVO] LÓGICA PARA O "SELECIONAR TUDO"
    $('.select-all-checkbox').on('click', function() {
        const isChecked = $(this).prop('checked');
        const targetColumnId = $(this).data('target-column');
        
        // Encontra todos os checkboxes de categoria dentro da coluna alvo e atualiza o estado deles
        $('#' + targetColumnId).find('.category-checkbox').prop('checked', isChecked);
    });
});
</script>
</body>
</html>