<?php
// landing_pages_lista.php
// Ativar exibição de erros para debug
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', 'logs/php_errors.log');

// Criar pasta de logs se não existir
if (!file_exists('logs')) {
    mkdir('logs', 0755, true);
}

session_start();

// Verificar login e tenant
if (!isset($_SESSION['logado'], $_SESSION['usuario_id'], $_SESSION['tenant_id']) || $_SESSION['logado'] !== true) {
    header('Location: login.php');
    exit;
}

require_once 'conexao.php';

// Verificar permissões do usuário atual
$permissao = $_SESSION['permissao'] ?? 'usuario';
$is_admin = ($permissao === 'admin' || $permissao === 'super_admin');

if (!$is_admin) {
    header('Location: acesso_negado.php');
    exit;
}

$tenantId = (int)$_SESSION['tenant_id'];

// Processar exclusão
if (isset($_GET['excluir']) && is_numeric($_GET['excluir'])) {
    $id = (int)$_GET['excluir'];
    
    // Verificar se a landing page pertence ao tenant
    $checkStmt = $conn->prepare("SELECT id, nome FROM landing_pages WHERE id = ? AND tenant_id = ?");
    $checkStmt->bind_param("ii", $id, $tenantId);
    $checkStmt->execute();
    $checkResult = $checkStmt->get_result();
    
    if ($checkResult->num_rows > 0) {
        $lp = $checkResult->fetch_assoc();
        
        // Excluir submissoes primeiro (foreign key)
        $delSubm = $conn->prepare("DELETE FROM landing_page_submissoes WHERE landing_page_id = ?");
        $delSubm->bind_param("i", $id);
        $delSubm->execute();
        $delSubm->close();
        
        // Excluir a landing page
        $delStmt = $conn->prepare("DELETE FROM landing_pages WHERE id = ? AND tenant_id = ?");
        $delStmt->bind_param("ii", $id, $tenantId);
        
        if ($delStmt->execute()) {
            $_SESSION['mensagem'] = "Landing Page '{$lp['nome']}' excluída com sucesso!";
            $_SESSION['mensagem_tipo'] = 'sucesso';
            
            // Registrar log
            $logFile = 'logs/landing_pages_acoes.log';
            $dataHora = date('Y-m-d H:i:s');
            $usuario = $_SESSION['usuario_id'];
            $logMsg = "[$dataHora] [Usuário: $usuario] [Ação: Exclusão] Landing Page ID: $id, Nome: {$lp['nome']}\n";
            file_put_contents($logFile, $logMsg, FILE_APPEND);
        } else {
            $_SESSION['mensagem'] = "Erro ao excluir landing page: " . $delStmt->error;
            $_SESSION['mensagem_tipo'] = 'erro';
        }
        $delStmt->close();
    } else {
        $_SESSION['mensagem'] = "Landing Page não encontrada ou não pertence ao seu tenant!";
        $_SESSION['mensagem_tipo'] = 'erro';
    }
    $checkStmt->close();
    
    header("Location: landing_pages_lista.php");
    exit;
}

// Buscar landing pages existentes
$stmt = $conn->prepare("
    SELECT lp.*, f.nome as funil_nome, ef.nome as etapa_nome, o.nome as origem_nome,
           (SELECT COUNT(*) FROM landing_page_submissoes WHERE landing_page_id = lp.id) as total_submissoes
    FROM landing_pages lp
    LEFT JOIN funis f ON lp.funil_id = f.id
    LEFT JOIN etapas_funis ef ON lp.etapa_funil_id = ef.id
    LEFT JOIN origens o ON lp.origem_id = o.id
    WHERE lp.tenant_id = ?
    ORDER BY lp.created_at DESC
");
$stmt->bind_param("i", $tenantId);
$stmt->execute();
$landingPages = $stmt->get_result();

// URL base do sistema
$protocolo = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
$baseUrl = $protocolo . $_SERVER['HTTP_HOST'] . '/';
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <link rel="icon" type="image/png" sizes="16x16" href="/favicon_io/favicon-16x16.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/favicon_io/favicon-32x32.png">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Landing Pages - SON</title>
    
    <!-- CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: 'Segoe UI', Arial, sans-serif;
            background-color: #f5f5f5;
            min-height: 100vh;
        }
        
        .header-fixed {
            position: fixed;
            top: 0;
            left: 60px;
            right: 0;
            background-color: #f5f5f5;
            padding: 15px 20px;
            z-index: 900;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            height: 70px;
        }
        
        .header-fixed img {
            height: 40px;
        }
        
        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            height: 100vh;
            width: 60px;
            background: white;
            box-shadow: 2px 0 5px rgba(0,0,0,0.1);
            z-index: 1000;
            transition: width 0.3s ease;
            overflow-x: hidden;
        }
        
        .sidebar:hover {
            width: 250px;
        }
        
        .sidebar ul {
            list-style: none;
            padding: 70px 0 20px 0;
            margin: 0;
        }
        
        .sidebar a {
            display: flex;
            align-items: center;
            padding: 15px 20px;
            text-decoration: none;
            color: #333;
            white-space: nowrap;
        }
        
        .sidebar a:hover {
            background-color: #f0f0f0;
        }
        
        .sidebar i {
            margin-right: 15px;
            min-width: 20px;
            text-align: center;
            font-size: 18px;
        }
        
        .sidebar span {
            display: none;
        }
        
        .sidebar:hover span {
            display: inline;
        }
        
        .main-content {
            margin-left: 60px;
            margin-top: 70px;
            padding: 20px;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            padding: 25px;
            border-radius: 8px;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.05);
        }
        
        h1 {
            color: #333;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }
        
        .header-actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .btn-novo {
            background-color: #4cafaf;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
        
        .btn-novo:hover {
            background-color: #3d9b9b;
        }
        
        .btn-voltar {
            background-color: #6c757d;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
        
        .btn-voltar:hover {
            background-color: #5a6268;
        }
        
        .mensagem-flutuante {
            position: fixed;
            top: 90px;
            right: 20px;
            padding: 15px 25px;
            border-radius: 4px;
            color: white;
            z-index: 2000;
            animation: slideIn 0.3s ease;
        }
        
        @keyframes slideIn {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }
        
        .mensagem-sucesso {
            background-color: #2ecc71;
        }
        
        .mensagem-erro {
            background-color: #e74c3c;
        }
        
        .landing-pages-list {
            margin-top: 20px;
        }
        
        .landing-item {
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 15px;
            margin-bottom: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
        }
        
        .landing-item:hover {
            background: #f9f9f9;
        }
        
        .landing-info {
            flex: 1;
            min-width: 300px;
        }
        
        .landing-info h3 {
            margin-bottom: 5px;
            color: #333;
            display: flex;
            align-items: center;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        .landing-info p {
            color: #666;
            font-size: 13px;
            margin-bottom: 3px;
        }
        
        .landing-stats {
            display: flex;
            gap: 15px;
            margin-top: 5px;
            flex-wrap: wrap;
        }
        
        .stat-badge {
            background: #e9ecef;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 12px;
        }
        
        .landing-link {
            background: #f8f9fa;
            padding: 5px 10px;
            border-radius: 4px;
            font-family: monospace;
            font-size: 12px;
            margin-top: 5px;
            word-break: break-all;
        }
        
        .landing-actions {
            display: flex;
            gap: 5px;
            flex-wrap: wrap;
        }
        
        .btn-editar, 
        .btn-excluir,
        .btn-visualizar,
        .btn-copiar,
        .btn-estatisticas {
            padding: 5px 10px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            text-decoration: none;
            color: white;
            font-size: 12px;
            display: inline-flex;
            align-items: center;
            gap: 3px;
        }
        
        .btn-editar {
            background-color: #3498db;
        }
        
        .btn-editar:hover {
            background-color: #2980b9;
        }
        
        .btn-excluir {
            background-color: #e74c3c;
        }
        
        .btn-excluir:hover {
            background-color: #c0392b;
        }
        
        .btn-visualizar {
            background-color: #2ecc71;
        }
        
        .btn-visualizar:hover {
            background-color: #27ae60;
        }
        
        .btn-copiar {
            background-color: #f39c12;
        }
        
        .btn-copiar:hover {
            background-color: #e67e22;
        }
        
        .btn-estatisticas {
            background-color: #9b59b6;
        }
        
        .btn-estatisticas:hover {
            background-color: #8e44ad;
        }
        
        .badge {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: bold;
        }
        
        .badge-success {
            background: #d4edda;
            color: #155724;
        }
        
        .badge-danger {
            background: #f8d7da;
            color: #721c24;
        }
        
        .empty-state {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        
        .empty-state i {
            font-size: 48px;
            color: #ddd;
            margin-bottom: 15px;
        }
        
        .empty-state h3 {
            margin-bottom: 10px;
            color: #333;
        }
        
        .empty-state p {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="header-fixed">
        <img src="tvitec.png" alt="Logo TVITEC" style="height:40px;">
        <div class="user-info" style="display:flex; align-items:center; gap:10px;">
            <div class="user-initial" style="width:40px; height:40px; border-radius:50%; background:#4cafaf; display:flex; align-items:center; justify-content:center; color:white; font-weight:bold;">
                <?php echo strtoupper(substr($_SESSION['nome_usuario'] ?? 'U', 0, 1)); ?>
            </div>
            <div>
                <div style="font-weight: bold;"><?php echo htmlspecialchars($_SESSION['nome_usuario'] ?? 'Usuário'); ?></div>
                <div style="font-size: 0.9em;"><?php echo htmlspecialchars($_SESSION['email_usuario'] ?? ''); ?></div>
            </div>
        </div>
    </div>

    <?php include 'menu_lateral.php'; ?>

    <div class="main-content">
        <div class="container">
            <?php if (isset($_SESSION['mensagem'])): ?>
                <div class="mensagem-flutuante <?php echo $_SESSION['mensagem_tipo'] === 'erro' ? 'mensagem-erro' : 'mensagem-sucesso'; ?>">
                    <?php echo htmlspecialchars($_SESSION['mensagem']); ?>
                </div>
                <?php 
                unset($_SESSION['mensagem']);
                unset($_SESSION['mensagem_tipo']);
                ?>
            <?php endif; ?>

            <div class="header-actions">
                <h1>
                    <i class="fas fa-rocket"></i> 
                    Landing Pages
                </h1>
                <div>
                    <a href="landing_pages.php" class="btn-novo">
                        <i class="fas fa-plus"></i> Nova Landing Page
                    </a>
                   
                </div>
            </div>
            
            <div class="landing-pages-list">
                <?php if ($landingPages && $landingPages->num_rows > 0): ?>
                    <?php while ($lp = $landingPages->fetch_assoc()): ?>
                        <div class="landing-item">
                            <div class="landing-info">
                                <h3>
                                    <?php echo htmlspecialchars($lp['nome']); ?>
                                    <?php if ($lp['ativo']): ?>
                                        <span class="badge badge-success">Ativo</span>
                                    <?php else: ?>
                                        <span class="badge badge-danger">Inativo</span>
                                    <?php endif; ?>
                                </h3>
                                <p>
                                    <i class="fas fa-tag"></i> Funil: <?php echo htmlspecialchars($lp['funil_nome'] ?? 'N/A'); ?> | 
                                    Etapa: <?php echo htmlspecialchars($lp['etapa_nome'] ?? 'N/A'); ?> |
                                    Origem: <?php echo htmlspecialchars($lp['origem_nome'] ?? 'Landing Page'); ?>
                                </p>
                                <div class="landing-stats">
                                    <span class="stat-badge">
                                        <i class="fas fa-users"></i> <?php echo $lp['total_submissoes']; ?> leads
                                    </span>
                                    <span class="stat-badge">
                                        <i class="far fa-calendar-alt"></i> Criado: <?php echo date('d/m/Y H:i', strtotime($lp['created_at'])); ?>
                                    </span>
                                    <?php if (!empty($lp['updated_at']) && $lp['updated_at'] != $lp['created_at']): ?>
                                    <span class="stat-badge">
                                        <i class="far fa-edit"></i> Atualizado: <?php echo date('d/m/Y H:i', strtotime($lp['updated_at'])); ?>
                                    </span>
                                    <?php endif; ?>
                                </div>
                                <div class="landing-link">
                                    <small><i class="fas fa-link"></i> <?php echo $baseUrl; ?>lp.php?token=<?php echo $lp['token']; ?></small>
                                </div>
                            </div>
                            <div class="landing-actions">
                                <a href="landing_pages.php?editar=<?php echo $lp['id']; ?>" class="btn-editar" title="Editar">
                                    <i class="fas fa-edit"></i> Editar
                                </a>
                                <a href="<?php echo $baseUrl; ?>lp.php?token=<?php echo $lp['token']; ?>" target="_blank" class="btn-visualizar" title="Visualizar">
                                    <i class="fas fa-eye"></i> Visualizar
                                </a>
                                <button class="btn-copiar" onclick="copiarLink('<?php echo $baseUrl; ?>lp.php?token=<?php echo $lp['token']; ?>')" title="Copiar link">
                                    <i class="fas fa-copy"></i> Copiar
                                </button>
                                <a href="landing_page_estatisticas.php?id=<?php echo $lp['id']; ?>" class="btn-estatisticas" title="Estatísticas">
                                    <i class="fas fa-chart-bar"></i> Estatísticas
                                </a>
                                <button class="btn-excluir" onclick="confirmarExclusao(<?php echo $lp['id']; ?>, '<?php echo htmlspecialchars($lp['nome']); ?>')" title="Excluir">
                                    <i class="fas fa-trash"></i> Excluir
                                </button>
                            </div>
                        </div>
                    <?php endwhile; ?>
                <?php else: ?>
                    <div class="empty-state">
                        <i class="fas fa-rocket"></i>
                        <h3>Nenhuma landing page cadastrada</h3>
                        <p>Crie sua primeira landing page para começar a capturar leads automaticamente!</p>
                        <a href="landing_pages.php" class="btn-novo">
                            <i class="fas fa-plus"></i> Criar Landing Page
                        </a>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script>
    // Copiar link
    function copiarLink(link) {
        navigator.clipboard.writeText(link).then(() => {
            Swal.fire({
                icon: 'success',
                title: 'Link copiado!',
                text: 'O link da landing page foi copiado para a área de transferência.',
                timer: 2000,
                showConfirmButton: false
            });
        }).catch(() => {
            Swal.fire('Erro', 'Não foi possível copiar o link', 'error');
        });
    }
    
    // Confirmar exclusão
function confirmarExclusao(id, nome) {
    Swal.fire({
        title: 'Confirmar exclusão',
        html: `Deseja realmente excluir a landing page "<strong>${nome}</strong>"?<br>
               <small style="color: #e74c3c;">Todos os dados de submissão também serão excluídos!</small>`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#e74c3c',
        confirmButtonText: 'Sim, excluir',
        cancelButtonText: 'Cancelar'
    }).then((result) => {
        if (result.isConfirmed) {
            // Verifique se está usando o arquivo correto
            window.location.href = 'excluir_landing_page.php?id=' + id;
            // OU
            // window.location.href = 'landing_pages_lista.php?excluir=' + id;
        }
    });
}
    
    // Fechar mensagem após 5 segundos
    setTimeout(function() {
        var msg = document.querySelector('.mensagem-flutuante');
        if (msg) msg.style.display = 'none';
    }, 5000);
    </script>
    
    <?php include 'sino_notificacoes.php'; ?>
</body>
</html>
<?php
if (isset($conn)) $conn->close();
?>