<?php
// landing_page_estatisticas.php
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();

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

require_once 'conexao.php';

$id = (int)($_GET['id'] ?? 0);
$tenantId = (int)$_SESSION['tenant_id'];

// Buscar informações da landing page
$stmt = $conn->prepare("
    SELECT lp.*, f.nome as funil_nome, ef.nome as etapa_nome, o.nome as origem_nome
    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.id = ? AND lp.tenant_id = ?
");
$stmt->bind_param("ii", $id, $tenantId);
$stmt->execute();
$landingPage = $stmt->get_result()->fetch_assoc();

if (!$landingPage) {
    header('Location: landing_pages_lista.php');
    exit;
}

// Processar filtros
$periodo = $_GET['periodo'] ?? '30d';
$dataInicio = null;
$dataFim = date('Y-m-d');

switch ($periodo) {
    case '7d':
        $dataInicio = date('Y-m-d', strtotime('-7 days'));
        break;
    case '30d':
        $dataInicio = date('Y-m-d', strtotime('-30 days'));
        break;
    case '90d':
        $dataInicio = date('Y-m-d', strtotime('-90 days'));
        break;
    case '12m':
        $dataInicio = date('Y-m-d', strtotime('-12 months'));
        break;
    default:
        $dataInicio = date('Y-m-d', strtotime('-30 days'));
}

// Buscar estatísticas da tabela landing_page_estatisticas
$stmt = $conn->prepare("
    SELECT 
        data,
        visualizacoes,
        submissoes,
        taxa_conversao
    FROM landing_page_estatisticas 
    WHERE landing_page_id = ? 
      AND data BETWEEN ? AND ?
    ORDER BY data DESC
");
$stmt->bind_param("iss", $id, $dataInicio, $dataFim);
$stmt->execute();
$estatisticasDiarias = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Totais do período
$stmt = $conn->prepare("
    SELECT 
        COALESCE(SUM(visualizacoes), 0) as total_visualizacoes,
        COALESCE(SUM(submissoes), 0) as total_submissoes,
        CASE 
            WHEN COALESCE(SUM(visualizacoes), 0) > 0 
            THEN (COALESCE(SUM(submissoes), 0) / COALESCE(SUM(visualizacoes), 0)) * 100
            ELSE 0 
        END as taxa_conversao_periodo,
        MIN(data) as primeira_data,
        MAX(data) as ultima_data
    FROM landing_page_estatisticas 
    WHERE landing_page_id = ? 
      AND data BETWEEN ? AND ?
");
$stmt->bind_param("iss", $id, $dataInicio, $dataFim);
$stmt->execute();
$totaisPeriodo = $stmt->get_result()->fetch_assoc();

// Estatísticas por hora (da tabela de submissões)
$stmt = $conn->prepare("
    SELECT HOUR(created_at) as hora,
           COUNT(*) as total
    FROM landing_page_submissoes 
    WHERE landing_page_id = ? 
      AND DATE(created_at) BETWEEN ? AND ?
    GROUP BY HOUR(created_at)
    ORDER BY hora
");
$stmt->bind_param("iss", $id, $dataInicio, $dataFim);
$stmt->execute();
$statsHorario = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Estatísticas por dia da semana
$stmt = $conn->prepare("
    SELECT DAYNAME(created_at) as dia_semana,
           DAYOFWEEK(created_at) as num_dia,
           COUNT(*) as total
    FROM landing_page_submissoes 
    WHERE landing_page_id = ? 
      AND DATE(created_at) BETWEEN ? AND ?
    GROUP BY DAYNAME(created_at), DAYOFWEEK(created_at)
    ORDER BY num_dia
");
$stmt->bind_param("iss", $id, $dataInicio, $dataFim);
$stmt->execute();
$statsDiaSemana = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Últimas submissões
$stmt = $conn->prepare("
    SELECT *
    FROM landing_page_submissoes 
    WHERE landing_page_id = ?
    ORDER BY created_at DESC
    LIMIT 20
");
$stmt->bind_param("i", $id);
$stmt->execute();
$ultimasSubmissoes = $stmt->get_result();

// Preparar dados para os gráficos
$diasLabels = [];
$visualizacoesData = [];
$submissoesData = [];
$taxasData = [];

foreach ($estatisticasDiarias as $dia) {
    $diasLabels[] = date('d/m', strtotime($dia['data']));
    $visualizacoesData[] = $dia['visualizacoes'];
    $submissoesData[] = $dia['submissoes'];
    $taxasData[] = round($dia['taxa_conversao'] ?? 0, 1);
}

// Inverter para ordem cronológica
$diasLabels = array_reverse($diasLabels);
$visualizacoesData = array_reverse($visualizacoesData);
$submissoesData = array_reverse($submissoesData);
$taxasData = array_reverse($taxasData);

// Dados para gráfico de horas
$horasData = array_fill(0, 24, 0);
foreach ($statsHorario as $hora) {
    $horasData[$hora['hora']] = $hora['total'];
}

// Dados para gráfico de dias da semana
$diasSemana = ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'];
$semanaData = array_fill(0, 7, 0);
foreach ($statsDiaSemana as $dia) {
    $semanaData[$dia['num_dia'] - 1] = $dia['total'];
}

// Calcular médias
$diasComDados = count($estatisticasDiarias);
$mediaVisualizacoes = $diasComDados > 0 ? round(array_sum($visualizacoesData) / $diasComDados, 1) : 0;
$mediaSubmissoes = $diasComDados > 0 ? round(array_sum($submissoesData) / $diasComDados, 1) : 0;

// URL da landing page
$protocolo = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
$baseUrl = $protocolo . $_SERVER['HTTP_HOST'] . '/';
$lpUrl = $baseUrl . 'lp.php?token=' . $landingPage['token'];
?>
<!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>Estatísticas - <?php echo htmlspecialchars($landingPage['nome']); ?> - SON</title>
    
    <!-- CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f5f5f5;
        }

        .header-fixed {
            position: fixed;
            top: 0;
            left: 60px;
            right: 0;
            background: #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;
        }

        .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: hidden;
        }

        .sidebar:hover {
            width: 250px;
        }

        .sidebar ul {
            list-style: none;
            padding: 70px 0 20px;
        }

        .sidebar a {
            display: flex;
            align-items: center;
            padding: 15px 20px;
            color: #333;
            text-decoration: none;
            white-space: nowrap;
        }

        .sidebar a:hover {
            background: #f0f0f0;
        }

        .sidebar i {
            margin-right: 15px;
            min-width: 20px;
            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;
        }

        .page-header {
            background: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
        }

        .page-header h1 {
            color: #333;
            font-size: 24px;
        }

        .page-header h1 i {
            color: #4CAF50;
            margin-right: 10px;
        }

        .filtros {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .btn-filtro {
            padding: 8px 16px;
            border: 1px solid #ddd;
            background: white;
            border-radius: 5px;
            cursor: pointer;
            text-decoration: none;
            color: #666;
            font-size: 14px;
        }

        .btn-filtro.active {
            background: #4CAF50;
            color: white;
            border-color: #4CAF50;
        }

        .btn-filtro:hover {
            background: #f0f0f0;
        }

        .btn-filtro.active:hover {
            background: #45a049;
        }

        .lp-info {
            background: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            border-left: 4px solid #4CAF50;
        }

        .lp-info h3 {
            color: #333;
            margin-bottom: 10px;
        }

        .lp-info p {
            color: #666;
            margin-bottom: 5px;
        }

        .lp-link {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            font-family: monospace;
            word-break: break-all;
            margin-top: 10px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            text-align: center;
        }

        .stat-icon {
            font-size: 32px;
            color: #4CAF50;
            margin-bottom: 10px;
        }

        .stat-value {
            font-size: 36px;
            font-weight: bold;
            color: #333;
            margin-bottom: 5px;
        }

        .stat-label {
            color: #666;
            font-size: 14px;
        }

        .stat-small {
            font-size: 12px;
            color: #999;
            margin-top: 10px;
        }

        .charts-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .chart-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .chart-card h3 {
            color: #333;
            margin-bottom: 15px;
            font-size: 16px;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }

        .chart-container {
            height: 300px;
            position: relative;
        }

        .table-container {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-top: 30px;
        }

        .table-container h3 {
            color: #333;
            margin-bottom: 15px;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th {
            background: #f8f9fa;
            padding: 12px;
            text-align: left;
            font-weight: 600;
            color: #333;
        }

        td {
            padding: 12px;
            border-bottom: 1px solid #eee;
            color: #666;
        }

        tr:hover {
            background: #f5f5f5;
        }

        .btn {
            display: inline-flex;
            align-items: center;
            gap: 5px;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            text-decoration: none;
            font-size: 14px;
        }

        .btn-primary {
            background: #4CAF50;
            color: white;
        }

        .btn-primary:hover {
            background: #45a049;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #5a6268;
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-success:hover {
            background: #218838;
        }

        .no-data {
            text-align: center;
            padding: 40px;
            color: #999;
        }

        .no-data i {
            font-size: 48px;
            color: #ddd;
            margin-bottom: 15px;
        }

        @media (max-width: 768px) {
            .charts-row {
                grid-template-columns: 1fr;
            }
            
            .stats-grid {
                grid-template-columns: 1fr 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="header-fixed">
        <img src="tvitec.png" alt="Logo" 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: #4CAF50; 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">
            <div class="page-header">
                <div>
                    <h1>
                        <i class="fas fa-chart-bar"></i>
                        Estatísticas da Landing Page
                    </h1>
                </div>
                <div class="filtros">
                    <a href="?id=<?php echo $id; ?>&periodo=7d" class="btn-filtro <?php echo $periodo == '7d' ? 'active' : ''; ?>">7 dias</a>
                    <a href="?id=<?php echo $id; ?>&periodo=30d" class="btn-filtro <?php echo $periodo == '30d' ? 'active' : ''; ?>">30 dias</a>
                    <a href="?id=<?php echo $id; ?>&periodo=90d" class="btn-filtro <?php echo $periodo == '90d' ? 'active' : ''; ?>">90 dias</a>
                    <a href="?id=<?php echo $id; ?>&periodo=12m" class="btn-filtro <?php echo $periodo == '12m' ? 'active' : ''; ?>">12 meses</a>
                </div>
            </div>

            <div class="lp-info">
                <h3><i class="fas fa-rocket"></i> <?php echo htmlspecialchars($landingPage['nome']); ?></h3>
                <p>
                    <i class="fas fa-tag"></i> Funil: <?php echo htmlspecialchars($landingPage['funil_nome'] ?? 'N/A'); ?> |
                    Etapa: <?php echo htmlspecialchars($landingPage['etapa_nome'] ?? 'N/A'); ?> |
                    Origem: <?php echo htmlspecialchars($landingPage['origem_nome'] ?? 'Landing Page'); ?>
                </p>
                <div class="lp-link">
                    <i class="fas fa-link"></i> <?php echo $lpUrl; ?>
                    <button onclick="copiarLink('<?php echo $lpUrl; ?>')" style="margin-left: 10px; background: none; border: none; color: #4CAF50; cursor: pointer;">
                        <i class="fas fa-copy"></i>
                    </button>
                </div>
            </div>

            <!-- Cards de estatísticas -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-eye"></i></div>
                    <div class="stat-value"><?php echo number_format($totaisPeriodo['total_visualizacoes'] ?? 0); ?></div>
                    <div class="stat-label">Visualizações</div>
                    <div class="stat-small">média <?php echo $mediaVisualizacoes; ?>/dia</div>
                </div>

                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-paper-plane"></i></div>
                    <div class="stat-value"><?php echo number_format($totaisPeriodo['total_submissoes'] ?? 0); ?></div>
                    <div class="stat-label">Submissões</div>
                    <div class="stat-small">média <?php echo $mediaSubmissoes; ?>/dia</div>
                </div>

                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-percent"></i></div>
                    <div class="stat-value"><?php echo number_format($totaisPeriodo['taxa_conversao_periodo'] ?? 0, 1); ?>%</div>
                    <div class="stat-label">Taxa de Conversão</div>
                    <div class="stat-small">submissões/visualizações</div>
                </div>

                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-calendar-alt"></i></div>
                    <div class="stat-value"><?php echo $diasComDados; ?></div>
                    <div class="stat-label">Dias com dados</div>
                    <div class="stat-small">
                        <?php 
                        if ($totaisPeriodo['primeira_data']) {
                            echo 'desde ' . date('d/m/Y', strtotime($totaisPeriodo['primeira_data']));
                        }
                        ?>
                    </div>
                </div>
            </div>

            <!-- Gráficos -->
            <div class="charts-row">
                <?php if (!empty($estatisticasDiarias)): ?>
                <div class="chart-card">
                    <h3><i class="fas fa-chart-line"></i> Visualizações vs Submissões</h3>
                    <div class="chart-container">
                        <canvas id="graficoComparativo"></canvas>
                    </div>
                </div>

                <div class="chart-card">
                    <h3><i class="fas fa-percent"></i> Taxa de Conversão Diária</h3>
                    <div class="chart-container">
                        <canvas id="graficoTaxa"></canvas>
                    </div>
                </div>
                <?php endif; ?>

                <?php if (!empty($statsHorario)): ?>
                <div class="chart-card">
                    <h3><i class="fas fa-clock"></i> Submissões por Hora</h3>
                    <div class="chart-container">
                        <canvas id="graficoHorario"></canvas>
                    </div>
                </div>
                <?php endif; ?>

                <?php if (!empty($statsDiaSemana)): ?>
                <div class="chart-card">
                    <h3><i class="fas fa-calendar-week"></i> Submissões por Dia da Semana</h3>
                    <div class="chart-container">
                        <canvas id="graficoDiasSemana"></canvas>
                    </div>
                </div>
                <?php endif; ?>
            </div>

            <!-- Últimas submissões -->
            <div class="table-container">
                <h3><i class="fas fa-history"></i> Últimas 20 Submissões</h3>
                
                <?php if ($ultimasSubmissoes && $ultimasSubmissoes->num_rows > 0): ?>
                <div style="overflow-x: auto;">
                    <table>
                        <thead>
                            <tr>
                                <th>Data/Hora</th>
                                <th>Dados Enviados</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($submissao = $ultimasSubmissoes->fetch_assoc()): ?>
                            <tr>
                                <td><?php echo date('d/m/Y H:i:s', strtotime($submissao['created_at'])); ?></td>
                                <td>
                                    <?php 
                                    $dados = json_decode($submissao['dados_submissao'], true);
                                    if ($dados && is_array($dados)) {
                                        echo '<pre style="margin: 0; font-size: 12px;">';
                                        foreach ($dados as $campo => $valor) {
                                            if (!is_array($valor)) {
                                                echo htmlspecialchars("$campo: $valor") . '<br>';
                                            }
                                        }
                                        echo '</pre>';
                                    } else {
                                        echo htmlspecialchars(substr($submissao['dados_submetidos'], 0, 100)) . '...';
                                    }
                                    ?>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
                <?php else: ?>
                <div class="no-data">
                    <i class="fas fa-inbox"></i>
                    <h3>Nenhuma submissão encontrada</h3>
                    <p>Esta landing page ainda não recebeu nenhum lead no período selecionado.</p>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script>
    function copiarLink(link) {
        navigator.clipboard.writeText(link).then(() => {
            alert('Link copiado para a área de transferência!');
        });
    }

    document.addEventListener('DOMContentLoaded', function() {
        // Gráfico Comparativo (Visualizações vs Submissões)
        <?php if (!empty($estatisticasDiarias)): ?>
        new Chart(document.getElementById('graficoComparativo'), {
            type: 'line',
            data: {
                labels: <?php echo json_encode($diasLabels); ?>,
                datasets: [
                    {
                        label: 'Visualizações',
                        data: <?php echo json_encode($visualizacoesData); ?>,
                        borderColor: '#2196F3',
                        backgroundColor: 'rgba(33, 150, 243, 0.1)',
                        tension: 0.1,
                        fill: true
                    },
                    {
                        label: 'Submissões',
                        data: <?php echo json_encode($submissoesData); ?>,
                        borderColor: '#4CAF50',
                        backgroundColor: 'rgba(76, 175, 80, 0.1)',
                        tension: 0.1,
                        fill: true
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top',
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    }
                }
            }
        });

        // Gráfico de Taxa de Conversão
        new Chart(document.getElementById('graficoTaxa'), {
            type: 'bar',
            data: {
                labels: <?php echo json_encode($diasLabels); ?>,
                datasets: [{
                    label: 'Taxa de Conversão (%)',
                    data: <?php echo json_encode($taxasData); ?>,
                    backgroundColor: '#4CAF50',
                    borderRadius: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return value + '%';
                            }
                        }
                    }
                }
            }
        });
        <?php endif; ?>

        // Gráfico por Hora
        <?php if (!empty($statsHorario)): ?>
        new Chart(document.getElementById('graficoHorario'), {
            type: 'bar',
            data: {
                labels: Array.from({length: 24}, (_, i) => i + 'h'),
                datasets: [{
                    label: 'Submissões',
                    data: <?php echo json_encode($horasData); ?>,
                    backgroundColor: '#4CAF50'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    }
                }
            }
        });
        <?php endif; ?>

        // Gráfico por Dia da Semana
        <?php if (!empty($statsDiaSemana)): ?>
        new Chart(document.getElementById('graficoDiasSemana'), {
            type: 'bar',
            data: {
                labels: <?php echo json_encode($diasSemana); ?>,
                datasets: [{
                    label: 'Submissões',
                    data: <?php echo json_encode($semanaData); ?>,
                    backgroundColor: [
                        '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', 
                        '#9966FF', '#FF9F40', '#FF6384'
                    ]
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    }
                }
            }
        });
        <?php endif; ?>
    });
    </script>

    <?php include 'sino_notificacoes.php'; ?>
</body>
</html>
<?php $conn->close(); ?>