<?php
// admin/page-list.php
$pageTitle = 'Gerenciar Páginas';
$pageHeader = 'Gerenciar Páginas';
$currentPage = 'pages';

// Define BASE_PATH se não estiver definido
if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(dirname(__FILE__)));
}

// Importações de arquivos necessários
require_once '../includes/config.php';
require_once '../includes/db.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';

// Verificar autenticação do usuário
if (!$auth->isLoggedIn()) {
    redirect('admin/login.php');
    exit;
}

logInfo("=== INÍCIO DA EXECUÇÃO DE " . basename(__FILE__) . " ===");

// Iniciar sessão se não estiver iniciada
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Gerar e armazenar CSRF token na sessão
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrfToken = $_SESSION['csrf_token'];

// Array com os tipos de páginas
$pageTypes = [
    'landing' => 'Página de Aterrisagem (PA)',
    'step1' => 'Primeira Etapa',
    'registration' => 'Página de Registro'
];

/**
 * Função para deletar página com todas as dependências
 */
function deletePageSafely($db, $pageId) {
    try {
        // Iniciar transação
        $db->beginTransaction();
        
        // Buscar dados da página
        $db->query("SELECT title, featured_image, type FROM pages WHERE id = :id");
        $db->bind(':id', $pageId);
        $pageData = $db->single();
        
        if (!$pageData) {
            throw new Exception("Página não encontrada");
        }
        
        // 1. Deletar configurações de fluxo se for uma landing page
        if ($pageData['type'] === 'landing') {
            $db->query("DELETE FROM flow_settings WHERE landing_page_id = :id");
            $db->bind(':id', $pageId);
            $db->execute();
            logInfo("Configurações de fluxo deletadas para landing page ID: $pageId");
        }
        
        // 2. Atualizar outras páginas que referenciam esta como landing_page_id
        $db->query("UPDATE pages SET landing_page_id = 0 WHERE landing_page_id = :id");
        $db->bind(':id', $pageId);
        $db->execute();
        logInfo("Referências de landing_page_id atualizadas para página ID: $pageId");
        
        // 3. Deletar imagem se existir
        if (!empty($pageData['featured_image'])) {
            deleteImage($pageData['featured_image']);
            logInfo("Imagem deletada: {$pageData['featured_image']}");
        }
        
        // 4. Deletar a página
        $db->query("DELETE FROM pages WHERE id = :id");
        $db->bind(':id', $pageId);
        $db->execute();
        
        // Confirmar transação
        $db->commit();
        
        logInfo("Página deletada com sucesso: ID {$pageId} - {$pageData['title']}");
        return ['success' => true, 'title' => $pageData['title']];
        
    } catch (Exception $e) {
        // Reverter transação em caso de erro
        $db->rollback();
        logError("Erro ao deletar página ID $pageId: " . $e->getMessage());
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

// Processamento de exclusão individual
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_single']) && isset($_POST['csrf_token']) && $_POST['csrf_token'] === $csrfToken) {
    $pageId = isset($_POST['page_id']) ? intval($_POST['page_id']) : 0;
    
    if ($pageId > 0) {
        $result = deletePageSafely($db, $pageId);
        
        if ($result['success']) {
            setAlert("Página '{$result['title']}' deletada com sucesso!", ALERT_SUCCESS);
        } else {
            setAlert('Erro ao deletar a página: ' . $result['error'], ALERT_ERROR);
        }
    } else {
        setAlert('ID da página inválido.', ALERT_ERROR);
    }
    
    // Redirecionar para evitar resubmissão
    $redirectUrl = 'page-list.php?page=' . (isset($_GET['page']) ? $_GET['page'] : 1);
    if (!empty($_GET['search'])) $redirectUrl .= '&search=' . urlencode($_GET['search']);
    if (!empty($_GET['type'])) $redirectUrl .= '&type=' . urlencode($_GET['type']);
    if (!empty($_GET['status'])) $redirectUrl .= '&status=' . urlencode($_GET['status']);
    
    header('Location: ' . $redirectUrl);
    exit;
}

// Processamento de ações em lote
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && isset($_POST['csrf_token']) && $_POST['csrf_token'] === $csrfToken) {
    $selectedPages = isset($_POST['selected_pages']) ? $_POST['selected_pages'] : [];
    
    if (!empty($selectedPages)) {
        try {
            switch ($_POST['action']) {
                case 'publish':
                    $db->query("UPDATE pages SET published = 1 WHERE id IN (" . implode(',', array_map('intval', $selectedPages)) . ")");
                    $db->execute();
                    setAlert('Páginas publicadas com sucesso!', ALERT_SUCCESS);
                    break;
                    
                case 'unpublish':
                    $db->query("UPDATE pages SET published = 0 WHERE id IN (" . implode(',', array_map('intval', $selectedPages)) . ")");
                    $db->execute();
                    setAlert('Páginas despublicadas com sucesso!', ALERT_SUCCESS);
                    break;
                    
                case 'delete':
                    $deletedCount = 0;
                    $errorCount = 0;
                    
                    foreach ($selectedPages as $pageId) {
                        $pageId = intval($pageId);
                        $result = deletePageSafely($db, $pageId);
                        
                        if ($result['success']) {
                            $deletedCount++;
                        } else {
                            $errorCount++;
                        }
                    }
                    
                    if ($deletedCount > 0 && $errorCount === 0) {
                        setAlert("$deletedCount página(s) deletada(s) com sucesso!", ALERT_SUCCESS);
                    } elseif ($deletedCount > 0 && $errorCount > 0) {
                        setAlert("$deletedCount página(s) deletada(s) com sucesso, $errorCount erro(s).", ALERT_WARNING);
                    } else {
                        setAlert("Erro ao deletar as páginas selecionadas.", ALERT_ERROR);
                    }
                    break;
            }
        } catch (Exception $e) {
            logError("Erro ao executar ação em lote: " . $e->getMessage());
            setAlert('Erro ao executar a ação selecionada.', ALERT_ERROR);
        }
    } else {
        setAlert('Selecione pelo menos uma página para executar a ação.', ALERT_WARNING);
    }
    
    // Redirecionar para evitar resubmissão
    $redirectUrl = 'page-list.php?page=' . (isset($_GET['page']) ? $_GET['page'] : 1);
    if (!empty($_GET['search'])) $redirectUrl .= '&search=' . urlencode($_GET['search']);
    if (!empty($_GET['type'])) $redirectUrl .= '&type=' . urlencode($_GET['type']);
    if (!empty($_GET['status'])) $redirectUrl .= '&status=' . urlencode($_GET['status']);
    
    header('Location: ' . $redirectUrl);
    exit;
}

// Parâmetros de filtro e paginação
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$type = isset($_GET['type']) ? trim($_GET['type']) : '';
$status = isset($_GET['status']) ? trim($_GET['status']) : '';

$whereConditions = [];
$params = [];

if (!empty($search)) {
    $whereConditions[] = "(title LIKE :search OR content LIKE :search)";
    $params[':search'] = "%{$search}%";
}

if (!empty($type)) {
    $whereConditions[] = "type = :type";
    $params[':type'] = $type;
}

if ($status !== '') {
    $whereConditions[] = "published = :status";
    $params[':status'] = $status === 'published' ? 1 : 0;
}

$whereClause = !empty($whereConditions) ? "WHERE " . implode(" AND ", $whereConditions) : "";

// Contar total de registros
$db->query("SELECT COUNT(*) as total FROM pages {$whereClause}");
foreach ($params as $key => $value) {
    $db->bind($key, $value);
}
$totalRecords = $db->single()['total'];
$totalPages = ceil($totalRecords / $limit);

// Buscar páginas
$db->query("SELECT * FROM pages {$whereClause} 
            ORDER BY created_at DESC 
            LIMIT :limit OFFSET :offset");

foreach ($params as $key => $value) {
    $db->bind($key, $value);
}
$db->bind(':limit', $limit, PDO::PARAM_INT);
$db->bind(':offset', $offset, PDO::PARAM_INT);

$pages = $db->resultSet();
logInfo("Páginas carregadas: " . count($pages));

// Estatísticas
$db->query("SELECT COUNT(*) as total FROM pages");
$totalPagesCount = $db->single()['total'];

$db->query("SELECT COUNT(*) as total FROM pages WHERE published = 1");
$publishedPages = $db->single()['total'];

$db->query("SELECT COUNT(*) as total FROM pages WHERE published = 0");
$draftPages = $db->single()['total'];

// Carregar o header depois de todas as verificações
require_once 'inc/header.php';
?>

<div class="container-fluid px-4">
    <div class="page-header mb-4">
        <div class="row align-items-center">
            <div class="col-md-6">
                <h1 class="page-title"><?php echo $pageTitle; ?></h1>
                <p class="text-muted">Gerencie todas as páginas do seu funil de vendas</p>
            </div>
            <div class="col-md-6 text-md-end">
                <a href="page-create.php" class="btn btn-primary">
                    <i class="fas fa-plus me-2"></i>Nova Página
                </a>
            </div>
        </div>
    </div>

    <!-- Estatísticas -->
    <div class="row mb-4">
        <div class="col-md-4">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body d-flex align-items-center">
                    <div class="icon-box bg-primary-light me-3">
                        <i class="fas fa-file-alt text-primary"></i>
                    </div>
                    <div>
                        <h3 class="h2 mb-0 fw-bold"><?php echo $totalPagesCount; ?></h3>
                        <p class="text-muted mb-0">Total de Páginas</p>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-4">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body d-flex align-items-center">
                    <div class="icon-box bg-success-light me-3">
                        <i class="fas fa-check-circle text-success"></i>
                    </div>
                    <div>
                        <h3 class="h2 mb-0 fw-bold"><?php echo $publishedPages; ?></h3>
                        <p class="text-muted mb-0">Páginas Publicadas</p>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-4">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body d-flex align-items-center">
                    <div class="icon-box bg-warning-light me-3">
                        <i class="fas fa-pencil-alt text-warning"></i>
                    </div>
                    <div>
                        <h3 class="h2 mb-0 fw-bold"><?php echo $draftPages; ?></h3>
                        <p class="text-muted mb-0">Páginas em Rascunho</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filtros -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body p-4">
            <form method="get" action="" class="row g-3">
                <div class="col-md-5">
                    <div class="input-group">
                        <span class="input-group-text bg-light border-end-0">
                            <i class="fas fa-search text-muted"></i>
                        </span>
                        <input type="text" class="form-control border-start-0 ps-0" name="search" placeholder="Buscar pelo título ou conteúdo..." 
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                </div>
                
                <div class="col-md-3">
                    <select class="form-select" name="type">
                        <option value="">Todos os Tipos</option>
                        <?php foreach ($pageTypes as $value => $label): ?>
                        <option value="<?php echo $value; ?>" <?php echo $type === $value ? 'selected' : ''; ?>>
                            <?php echo $label; ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <select class="form-select" name="status">
                        <option value="">Todos os Status</option>
                        <option value="published" <?php echo $status === 'published' ? 'selected' : ''; ?>>Publicado</option>
                        <option value="draft" <?php echo $status === 'draft' ? 'selected' : ''; ?>>Rascunho</option>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-filter me-2"></i>Filtrar
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Tabela -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body p-0">
            <form method="post" action="" id="bulkForm">
                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrfToken); ?>">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="bg-light">
                            <tr>
                                <th width="40" class="ps-3">
                                    <div class="form-check">
                                        <input type="checkbox" class="form-check-input" id="selectAll">
                                        <label class="form-check-label" for="selectAll"></label>
                                    </div>
                                </th>
                                <th width="60">ID</th>
                                <th width="80">Imagem</th>
                                <th>Título</th>
                                <th>Tipo</th>
                                <th>Sequência</th>
                                <th>Status</th>
                                <th>Criado em</th>
                                <th class="text-end pe-3">Ações</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($pages)): ?>
                            <tr>
                                <td colspan="9" class="text-center py-5">
                                    <div class="empty-state">
                                        <i class="fas fa-folder-open text-muted opacity-25" style="font-size: 3rem;"></i>
                                        <p class="text-muted mt-3 mb-0">Nenhuma página encontrada com os filtros selecionados.</p>
                                        <a href="page-list.php" class="btn btn-sm btn-outline-primary mt-3">Limpar filtros</a>
                                    </div>
                                </td>
                            </tr>
                            <?php else: ?>
                                <?php foreach ($pages as $pageItem): ?>
                                <tr>
                                    <td class="ps-3">
                                        <div class="form-check">
                                            <input type="checkbox" class="form-check-input" name="selected_pages[]" 
                                                   value="<?php echo $pageItem['id']; ?>" id="page-<?php echo $pageItem['id']; ?>">
                                            <label class="form-check-label" for="page-<?php echo $pageItem['id']; ?>"></label>
                                        </div>
                                    </td>
                                    <td><?php echo $pageItem['id']; ?></td>
                                    <td>
                                        <?php if (!empty($pageItem['featured_image'])): ?>
                                        <img src="<?php echo htmlspecialchars($pageItem['featured_image']); ?>" 
                                             alt="Thumbnail" class="img-thumbnail" style="width: 50px; height: 50px; object-fit: cover;">
                                        <?php else: ?>
                                        <div class="img-thumbnail d-flex align-items-center justify-content-center bg-light" style="width: 50px; height: 50px;">
                                            <i class="fas fa-image text-muted"></i>
                                        </div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <a href="page-edit.php?id=<?php echo $pageItem['id']; ?>" class="fw-medium text-decoration-none text-dark">
                                            <?php echo htmlspecialchars($pageItem['title']); ?>
                                        </a>
                                        <?php if ($pageItem['type'] === 'landing'): ?>
                                        <br><small class="text-primary"><i class="fas fa-link me-1"></i>Landing Principal</small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="badge bg-light text-dark border">
                                            <?php echo isset($pageTypes[$pageItem['type']]) ? substr($pageTypes[$pageItem['type']], 0, strpos($pageTypes[$pageItem['type']], ' ')) : $pageItem['type']; ?>
                                        </span>
                                    </td>
                                    <td><?php echo $pageItem['sequence']; ?></td>
                                    <td>
                                        <span class="badge <?php echo $pageItem['published'] ? 'bg-success-light text-success' : 'bg-warning-light text-warning'; ?>">
                                            <?php echo $pageItem['published'] ? 'Publicado' : 'Rascunho'; ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="text-muted" title="<?php echo date('d/m/Y H:i', strtotime($pageItem['created_at'])); ?>">
                                            <?php echo function_exists('formatTimeAgo') ? formatTimeAgo($pageItem['created_at']) : date('d/m/Y H:i', strtotime($pageItem['created_at'])); ?>
                                        </span>
                                    </td>
                                    <td class="text-end pe-3">
                                        <div class="btn-group btn-group-sm">
                                            <a href="page-edit.php?id=<?php echo $pageItem['id']; ?>" 
                                               class="btn btn-outline-primary" title="Editar">
                                                <i class="fas fa-pen"></i>
                                            </a>
                                            <button type="button" class="btn btn-outline-danger" title="Excluir"
                                                    onclick="confirmDelete(<?php echo $pageItem['id']; ?>, '<?php echo htmlspecialchars(addslashes($pageItem['title'])); ?>')">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                            <?php if ($pageItem['published']): ?>
                                            <a href="../pages/<?php echo $pageItem['slug']; ?>" 
                                               class="btn btn-outline-secondary" title="Visualizar" target="_blank">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <?php else: ?>
                                            <a href="../pages/preview.php?id=<?php echo $pageItem['id']; ?>" 
                                               class="btn btn-outline-secondary" title="Prévia" target="_blank">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <?php if (!empty($pages)): ?>
                <div class="bulk-actions p-3 border-top d-flex align-items-center">
                    <div class="d-flex align-items-center">
                        <select name="action" class="form-select form-select-sm me-2" style="width: 180px;">
                            <option value="">Ações em lote</option>
                            <option value="publish">Publicar selecionados</option>
                            <option value="unpublish">Despublicar selecionados</option>
                            <option value="delete">Excluir selecionados</option>
                        </select>
                        <button type="submit" class="btn btn-sm btn-secondary" id="apply-action">
                            <i class="fas fa-play me-1"></i>Aplicar
                        </button>
                    </div>
                    
                    <div class="ms-auto">
                        <span class="text-muted small">
                            Mostrando <?php echo count($pages); ?> de <?php echo $totalRecords; ?> páginas
                        </span>
                    </div>
                </div>
                <?php endif; ?>
            </form>
        </div>
    </div>

    <!-- Paginação -->
    <?php if ($totalPages > 1): ?>
    <nav aria-label="Navegação das páginas">
        <ul class="pagination justify-content-center">
            <?php if ($page > 1): ?>
            <li class="page-item">
                <a class="page-link" href="page-list.php?page=1<?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo !empty($type) ? '&type=' . urlencode($type) : ''; ?><?php echo $status !== '' ? '&status=' . urlencode($status) : ''; ?>" aria-label="Primeira">
                    <i class="fas fa-angle-double-left"></i>
                </a>
            </li>
            <li class="page-item">
                <a class="page-link" href="page-list.php?page=<?php echo $page - 1; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo !empty($type) ? '&type=' . urlencode($type) : ''; ?><?php echo $status !== '' ? '&status=' . urlencode($status) : ''; ?>" aria-label="Anterior">
                    <i class="fas fa-angle-left"></i>
                </a>
            </li>
            <?php endif; ?>

            <?php
            $start = max(1, $page - 2);
            $end = min($totalPages, $page + 2);

            for ($i = $start; $i <= $end; $i++):
            ?>
            <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                <a class="page-link" href="page-list.php?page=<?php echo $i; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo !empty($type) ? '&type=' . urlencode($type) : ''; ?><?php echo $status !== '' ? '&status=' . urlencode($status) : ''; ?>">
                    <?php echo $i; ?>
                </a>
            </li>
            <?php endfor; ?>

            <?php if ($page < $totalPages): ?>
            <li class="page-item">
                <a class="page-link" href="page-list.php?page=<?php echo $page + 1; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo !empty($type) ? '&type=' . urlencode($type) : ''; ?><?php echo $status !== '' ? '&status=' . urlencode($status) : ''; ?>" aria-label="Próxima">
                    <i class="fas fa-angle-right"></i>
                </a>
            </li>
            <li class="page-item">
                <a class="page-link" href="page-list.php?page=<?php echo $totalPages; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo !empty($type) ? '&type=' . urlencode($type) : ''; ?><?php echo $status !== '' ? '&status=' . urlencode($status) : ''; ?>" aria-label="Última">
                    <i class="fas fa-angle-double-right"></i>
                </a>
            </li>
            <?php endif; ?>
        </ul>
    </nav>
    <?php endif; ?>
</div>

<!-- Modal de confirmação de exclusão -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteModalLabel">Confirmar Exclusão</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fechar"></button>
            </div>
            <div class="modal-body">
                <p>Tem certeza que deseja excluir a página <strong id="pageTitleToDelete"></strong>?</p>
                <p class="text-danger mb-0">Esta ação não pode ser desfeita e removerá todas as dependências relacionadas.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                <form id="deleteForm" method="post" action="">
                    <input type="hidden" name="delete_single" value="1">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrfToken); ?>">
                    <input type="hidden" id="pageIdToDelete" name="page_id" value="">
                    <button type="submit" class="btn btn-danger">Excluir Página</button>
                </form>
            </div>
        </div>
    </div>
</div>

<style>
    :root {
        --primary-color: #4F46E5;
        --secondary-color: #7C3AED;
        --accent-color: #EC4899;
        --dark-color: #1F2937;
        --light-color: #F8FAFC;
        --text-color: #1F2937;
        --border-color: #E5E7EB;
        --gradient: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
        --success-light: rgba(16, 185, 129, 0.1);
        --warning-light: rgba(245, 158, 11, 0.1);
        --primary-light: rgba(79, 70, 229, 0.1);
        --info-light: rgba(59, 130, 246, 0.1);
    }

    .page-header {
        margin-bottom: 2rem;
    }
    
    .page-title {
        font-size: 1.75rem;
        font-weight: 700;
        margin-bottom: 0.5rem;
        color: var(--dark-color);
    }
    
    .card {
        border-radius: 0.75rem;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
        transition: all 0.3s ease;
    }
    
    .card:hover {
        box-shadow: 0 10px 15px rgba(0, 0, 0, 0.07);
    }
    
    .icon-box {
        width: 48px;
        height: 48px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;
    }
    
    .bg-primary-light {
        background-color: var(--primary-light);
    }
    
    .bg-success-light {
        background-color: var(--success-light);
    }
    
    .bg-warning-light {
        background-color: var(--warning-light);
    }
    
    .bg-info-light {
        background-color: var(--info-light);
    }
    
    .text-primary {
        color: var(--primary-color) !important;
    }
    
    .text-success {
        color: #10B981 !important;
    }
    
    .text-warning {
        color: #F59E0B !important;
    }
    
    .table th {
        font-weight: 600;
        padding-top: 0.75rem;
        padding-bottom: 0.75rem;
    }
    
    .table td {
        padding: 0.75rem;
        vertical-align: middle;
    }
    
    .form-check-input:checked {
        background-color: var(--primary-color);
        border-color: var(--primary-color);
    }
    
    .page-link {
        color: var(--primary-color);
        border: none;
        margin: 0 3px;
        border-radius: 6px;
    }
    
    .page-item.active .page-link {
        background: var(--gradient);
    }
    
    .empty-state {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 2rem 0;
    }
    
    .badge.bg-success-light {
        background-color: var(--success-light);
        color: #10B981;
        font-weight: 500;
        padding: 0.35rem 0.65rem;
    }
    
    .badge.bg-warning-light {
        background-color: var(--warning-light);
        color: #F59E0B;
        font-weight: 500;
        padding: 0.35rem 0.65rem;
    }
    
    .btn-group .btn {
        padding: 0.35rem 0.5rem;
        border-radius: 0.375rem;
    }
    
    .btn-group .btn:not(:first-child) {
        margin-left: 1px;
    }
    
    .table tbody tr {
        transition: all 0.2s ease;
    }
    
    .table tbody tr:hover {
        background-color: rgba(79, 70, 229, 0.03);
    }
</style>

<script>
document.getElementById('selectAll').addEventListener('change', function() {
    document.querySelectorAll('input[name="selected_pages[]"]').forEach(checkbox => checkbox.checked = this.checked);
    updateSelectedCount();
});

function confirmDelete(id, title) {
    const modal = new bootstrap.Modal(document.getElementById('deleteModal'));
    document.getElementById('pageIdToDelete').value = id;
    document.getElementById('pageTitleToDelete').textContent = title;
    modal.show();
}

document.getElementById('apply-action').addEventListener('click', function(e) {
    const actionSelect = document.querySelector('select[name="action"]');
    const selectedAction = actionSelect.value;
    const selectedPages = document.querySelectorAll('input[name="selected_pages[]"]:checked');
    
    if (!selectedAction) {
        e.preventDefault();
        alert('Por favor, selecione uma ação para aplicar.');
        return;
    }
    
    if (selectedPages.length === 0) {
        e.preventDefault();
        alert('Por favor, selecione pelo menos uma página.');
        return;
    }
    
    if (selectedAction === 'delete') {
        if (!confirm(`Tem certeza que deseja excluir ${selectedPages.length} página(s) selecionada(s)?\nEsta ação não pode ser desfeita e removerá todas as dependências relacionadas.`)) {
            e.preventDefault();
        }
    }
});

document.querySelectorAll('input[name="selected_pages[]"]').forEach(checkbox => {
    checkbox.addEventListener('change', function() {
        const row = this.closest('tr');
        if (this.checked) {
            row.classList.add('bg-light');
        } else {
            row.classList.remove('bg-light');
        }
        updateSelectedCount();
    });
});

function updateSelectedCount() {
    const count = document.querySelectorAll('input[name="selected_pages[]"]:checked').length;
    const applyButton = document.getElementById('apply-action');
    
    if (count > 0) {
        applyButton.innerHTML = `<i class="fas fa-play me-1"></i>Aplicar (${count})`;
    } else {
        applyButton.innerHTML = `<i class="fas fa-play me-1"></i>Aplicar`;
    }
}

document.addEventListener('DOMContentLoaded', function() {
    const cards = document.querySelectorAll('.card');
    cards.forEach((card, index) => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(20px)';
        card.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
        
        setTimeout(() => {
            card.style.opacity = '1';
            card.style.transform = 'translateY(0)';
        }, 100 + (index * 50));
    });
    updateSelectedCount();
});
</script>

<?php require_once 'inc/footer.php'; ?>