<?php
// admin/revenue.php
$pageTitle = 'Relatórios de Receita';
$pageHeader = 'Relatórios de Receita';
$currentPage = 'revenue';

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

require_once '../includes/config.php';
require_once '../includes/db.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';

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

// Inclui a classe IntegraOn se existir
$integraOnAvailable = false;
if (file_exists('../includes/integraon-revenue.php')) {
    require_once '../includes/integraon-revenue.php';
    $integraOnAvailable = class_exists('IntegraOnRevenueAPI');
}

// Inicializar variáveis
$startDate = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-01');
$endDate = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');
$period = isset($_GET['period']) ? $_GET['period'] : '30';

// Ajustar datas baseado no período selecionado
if ($period && $period !== 'custom') {
    $endDate = date('Y-m-d');
    $startDate = date('Y-m-d', strtotime("-{$period} days"));
}

// Dados de receita local (fallback)
$localRevenueData = [];
$topProducts = [];
$revenueStats = [
    'total_visits' => 0,
    'total_conversions' => 0,
    'conversion_rate' => 0,
    'total_revenue' => 0,
    'avg_order_value' => 0
];

try {
    // Buscar estatísticas de visitas das páginas
    $db->query("SELECT COUNT(*) as total_visits FROM page_views 
               WHERE viewed_at BETWEEN :start_date AND :end_date");
    $db->bind(':start_date', $startDate . ' 00:00:00');
    $db->bind(':end_date', $endDate . ' 23:59:59');
    $visitsResult = $db->single();
    $revenueStats['total_visits'] = $visitsResult['total_visits'] ?? 0;

    // Se IntegraOn estiver disponível e configurado, usar seus dados
    if ($integraOnAvailable && isset($integraOnRevenue) && $integraOnRevenue->isConfigured()) {
        try {
            // Sincronizar dados recentes
            $integraOnRevenue->syncData($startDate, $endDate);
            
            // Buscar dados locais do IntegraOn
            $localRevenueData = $integraOnRevenue->getLocalRevenueData($startDate, $endDate);
            $topProducts = $integraOnRevenue->getTopProducts($startDate, $endDate, 10);
            $roiData = $integraOnRevenue->calculateROI($startDate, $endDate);
            
            $revenueStats['total_conversions'] = $roiData['total_conversoes'] ?? 0;
            $revenueStats['total_revenue'] = $roiData['receita_total'] ?? 0;
            
        } catch (Exception $e) {
            logError("Erro ao buscar dados IntegraOn: " . $e->getMessage());
        }
    }
    
    // Calcular estatísticas finais
    if ($revenueStats['total_visits'] > 0) {
        $revenueStats['conversion_rate'] = round(($revenueStats['total_conversions'] / $revenueStats['total_visits']) * 100, 2);
    }
    
    if ($revenueStats['total_conversions'] > 0) {
        $revenueStats['avg_order_value'] = round($revenueStats['total_revenue'] / $revenueStats['total_conversions'], 2);
    }

} catch (Exception $e) {
    logError("Erro ao buscar dados de receita: " . $e->getMessage());
    setAlert('Erro ao carregar dados de receita: ' . $e->getMessage(), ALERT_ERROR);
}

// Incluir header
require_once 'inc/header.php';
?>

<div class="container-fluid px-4">
    <!-- Cabeçalho -->
    <div class="row mt-4 mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h1 class="h3 mb-2"><?php echo $pageHeader; ?></h1>
                    <p class="text-muted mb-0">Análise de receita e conversões</p>
                </div>
                <div>
                    <button class="btn btn-primary" onclick="exportData()">
                        <i class="fas fa-download me-2"></i>Exportar
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Filtros de Período -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body">
            <form method="GET" action="" class="row g-3">
                <div class="col-md-3">
                    <label for="period" class="form-label">Período</label>
                    <select class="form-select" id="period" name="period" onchange="toggleCustomDates()">
                        <option value="7" <?php echo $period == '7' ? 'selected' : ''; ?>>Últimos 7 dias</option>
                        <option value="30" <?php echo $period == '30' ? 'selected' : ''; ?>>Últimos 30 dias</option>
                        <option value="90" <?php echo $period == '90' ? 'selected' : ''; ?>>Últimos 90 dias</option>
                        <option value="custom" <?php echo $period == 'custom' ? 'selected' : ''; ?>>Personalizado</option>
                    </select>
                </div>
                <div class="col-md-3" id="start-date-field" style="<?php echo $period !== 'custom' ? 'display:none;' : ''; ?>">
                    <label for="start_date" class="form-label">Data Inicial</label>
                    <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo $startDate; ?>">
                </div>
                <div class="col-md-3" id="end-date-field" style="<?php echo $period !== 'custom' ? 'display:none;' : ''; ?>">
                    <label for="end_date" class="form-label">Data Final</label>
                    <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo $endDate; ?>">
                </div>
                <div class="col-md-3 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-search me-2"></i>Filtrar
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Alertas -->
    <?php if ($alert = getAlert()): ?>
    <div class="alert alert-<?php echo $alert['type']; ?> alert-dismissible fade show" role="alert">
        <?php echo $alert['message']; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>

    <!-- Cards de Estatísticas -->
    <div class="row mb-4">
        <div class="col-md-3 mb-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="card-subtitle mb-2 text-muted">Total de Visitas</h6>
                            <h3 class="card-title mb-0"><?php echo number_format($revenueStats['total_visits']); ?></h3>
                        </div>
                        <div class="text-primary">
                            <i class="fas fa-eye fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3 mb-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="card-subtitle mb-2 text-muted">Conversões</h6>
                            <h3 class="card-title mb-0"><?php echo number_format($revenueStats['total_conversions']); ?></h3>
                        </div>
                        <div class="text-success">
                            <i class="fas fa-shopping-cart fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3 mb-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="card-subtitle mb-2 text-muted">Taxa de Conversão</h6>
                            <h3 class="card-title mb-0"><?php echo $revenueStats['conversion_rate']; ?>%</h3>
                        </div>
                        <div class="text-info">
                            <i class="fas fa-percentage fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3 mb-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="card-subtitle mb-2 text-muted">Receita Total</h6>
                            <h3 class="card-title mb-0">R$ <?php echo number_format($revenueStats['total_revenue'], 2, ',', '.'); ?></h3>
                        </div>
                        <div class="text-warning">
                            <i class="fas fa-dollar-sign fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Gráfico de Receita ao Longo do Tempo -->
    <div class="row mb-4">
        <div class="col-md-8">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white">
                    <h5 class="card-title mb-0">Receita ao Longo do Tempo</h5>
                </div>
                <div class="card-body">
                    <canvas id="revenueChart" height="100"></canvas>
                </div>
            </div>
        </div>
        
        <div class="col-md-4">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white">
                    <h5 class="card-title mb-0">Resumo do Período</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <small class="text-muted">Ticket Médio</small>
                        <div class="h5">R$ <?php echo number_format($revenueStats['avg_order_value'], 2, ',', '.'); ?></div>
                    </div>
                    <div class="mb-3">
                        <small class="text-muted">Período Analisado</small>
                        <div class="h6"><?php echo date('d/m/Y', strtotime($startDate)); ?> - <?php echo date('d/m/Y', strtotime($endDate)); ?></div>
                    </div>
                    <div class="mb-3">
                        <small class="text-muted">Status IntegraOn</small>
                        <div class="h6">
                            <?php if ($integraOnAvailable): ?>
                                <span class="badge bg-success">Conectado</span>
                            <?php else: ?>
                                <span class="badge bg-warning">Não configurado</span>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Top Produtos -->
    <?php if (!empty($topProducts)): ?>
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white">
                    <h5 class="card-title mb-0">Top Produtos por Receita</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Produto</th>
                                    <th>Vendas</th>
                                    <th>Receita Total</th>
                                    <th>Receita Aprovada</th>
                                    <th>Comissão Média</th>
                                    <th>Taxa Aprovação</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($topProducts as $product): ?>
                                <tr>
                                    <td>
                                        <strong><?php echo htmlspecialchars($product['product_name']); ?></strong>
                                        <br><small class="text-muted">ID: <?php echo $product['product_id']; ?></small>
                                    </td>
                                    <td><?php echo number_format($product['total_vendas']); ?></td>
                                    <td>R$ <?php echo number_format($product['receita_total'], 2, ',', '.'); ?></td>
                                    <td>R$ <?php echo number_format($product['receita_aprovada'], 2, ',', '.'); ?></td>
                                    <td>R$ <?php echo number_format($product['comissao_media'], 2, ',', '.'); ?></td>
                                    <td>
                                        <span class="badge bg-<?php echo $product['taxa_aprovacao'] >= 80 ? 'success' : ($product['taxa_aprovacao'] >= 60 ? 'warning' : 'danger'); ?>">
                                            <?php echo $product['taxa_aprovacao']; ?>%
                                        </span>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Receita Diária -->
    <?php if (!empty($localRevenueData)): ?>
    <div class="row">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white">
                    <h5 class="card-title mb-0">Receita por Dia</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Data</th>
                                    <th>Conversões</th>
                                    <th>Receita Total</th>
                                    <th>Aprovada</th>
                                    <th>Pendente</th>
                                    <th>Rejeitada</th>
                                    <th>Ticket Médio</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($localRevenueData as $day): ?>
                                <tr>
                                    <td><?php echo date('d/m/Y', strtotime($day['data'])); ?></td>
                                    <td><?php echo number_format($day['total_conversoes']); ?></td>
                                    <td>R$ <?php echo number_format($day['receita_total'], 2, ',', '.'); ?></td>
                                    <td>R$ <?php echo number_format($day['receita_aprovada'], 2, ',', '.'); ?></td>
                                    <td>R$ <?php echo number_format($day['receita_pendente'], 2, ',', '.'); ?></td>
                                    <td>R$ <?php echo number_format($day['receita_rejeitada'], 2, ',', '.'); ?></td>
                                    <td>R$ <?php echo number_format($day['ticket_medio'], 2, ',', '.'); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php else: ?>
    <div class="row">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-body text-center py-5">
                    <i class="fas fa-chart-line fa-3x text-muted mb-3"></i>
                    <h4 class="text-muted">Nenhum dado de receita encontrado</h4>
                    <p class="text-muted">Configure a integração com IntegraOn para visualizar dados de receita detalhados.</p>
                    <?php if (isset($_SESSION['admin_role']) && $_SESSION['admin_role'] === 'admin'): ?>
                    <a href="settings.php" class="btn btn-primary">Configurar Integração</a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- Scripts -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Função para alternar campos de data customizada
function toggleCustomDates() {
    const period = document.getElementById('period').value;
    const startField = document.getElementById('start-date-field');
    const endField = document.getElementById('end-date-field');
    
    if (period === 'custom') {
        startField.style.display = 'block';
        endField.style.display = 'block';
    } else {
        startField.style.display = 'none';
        endField.style.display = 'none';
    }
}

// Função para exportar dados
function exportData() {
    const startDate = '<?php echo $startDate; ?>';
    const endDate = '<?php echo $endDate; ?>';
    window.open(`revenue-export.php?start_date=${startDate}&end_date=${endDate}`, '_blank');
}

// Configuração do gráfico de receita
document.addEventListener('DOMContentLoaded', function() {
    const ctx = document.getElementById('revenueChart').getContext('2d');
    
    // Dados do gráfico (convertidos do PHP)
    const chartData = {
        labels: [<?php 
            if (!empty($localRevenueData)) {
                foreach ($localRevenueData as $day) {
                    echo "'" . date('d/m', strtotime($day['data'])) . "', ";
                }
            } else {
                echo "'Sem dados'";
            }
        ?>],
        datasets: [{
            label: 'Receita Total',
            data: [<?php 
                if (!empty($localRevenueData)) {
                    foreach ($localRevenueData as $day) {
                        echo $day['receita_total'] . ", ";
                    }
                } else {
                    echo "0";
                }
            ?>],
            backgroundColor: 'rgba(54, 162, 235, 0.2)',
            borderColor: 'rgba(54, 162, 235, 1)',
            borderWidth: 2,
            tension: 0.3,
            fill: true
        }, {
            label: 'Receita Aprovada',
            data: [<?php 
                if (!empty($localRevenueData)) {
                    foreach ($localRevenueData as $day) {
                        echo $day['receita_aprovada'] . ", ";
                    }
                } else {
                    echo "0";
                }
            ?>],
            backgroundColor: 'rgba(75, 192, 192, 0.2)',
            borderColor: 'rgba(75, 192, 192, 1)',
            borderWidth: 2,
            tension: 0.3,
            fill: false
        }]
    };

    const chart = new Chart(ctx, {
        type: 'line',
        data: chartData,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                },
                title: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return 'R$ ' + value.toLocaleString('pt-BR');
                        }
                    }
                }
            },
            tooltips: {
                callbacks: {
                    label: function(context) {
                        return context.dataset.label + ': R$ ' + context.parsed.y.toLocaleString('pt-BR');
                    }
                }
            }
        }
    });
});
</script>

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