<?php
// adm/log-acesso-empresa.php

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Caminho ajustado para subir um nível, assumindo que conexao.php está na raiz
require_once '../conexao.php';

// 1. Verificação de Segurança (Apenas Admins)
if (($_SESSION['role'] ?? '') !== 'Administradores' && ($_SESSION['role'] ?? '') !== 'Administrador') {
    header("Location: ../login.php");
    exit();
}

try {
    // 2. Consulta SQL Cruzando Histórico com Empresas e contando anúncios
    // Identifica se a empresa é Paga (tem anúncio_pago) ou Gratuita (anuncio_gratuito)
    $sql = "SELECT 
                h.id AS acesso_id,
                h.data_acesso,
                h.pagina_acessada,
                e.nome_empresa,
                e.email AS empresa_email,
                (SELECT COUNT(*) FROM anuncio_pago WHERE empresa_id = e.id) as total_pagos,
                (SELECT COUNT(*) FROM anuncio_gratuito WHERE empresa_id = e.id) as total_gratuitos
            FROM historico_acessos h
            INNER JOIN Empresas e ON h.usuario_id = e.id
            WHERE h.tipo_usuario = 'empresa'
            ORDER BY h.data_acesso DESC 
            LIMIT 200"; 

    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $acessos = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    error_log("Erro no log de empresas: " . $e->getMessage());
    $erro_critico = "Erro ao carregar o relatório de acessos.";
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Log de Acessos Empresas - Adm</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        body { background-color: #f8f9fa; padding: 30px; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        .container-log { background: #fff; padding: 25px; border-radius: 12px; box-shadow: 0 5px 15px rgba(0,0,0,0.08); }
        .titulo-pg { color: #12929e; font-weight: bold; border-bottom: 2px solid #f1f1f1; padding-bottom: 15px; margin-bottom: 25px; }
        .table thead { background-color: #12929e; color: white; }
        .badge-pago { background-color: #28a745; color: white; padding: 5px 10px; }
        .badge-gratuito { background-color: #ffc107; color: #212529; padding: 5px 10px; }
        .badge-nenhum { background-color: #e9ecef; color: #6c757d; border: 1px solid #dee2e6; }
        .text-url { font-family: monospace; font-size: 0.85rem; color: #d63384; background: #f8f9fa; padding: 2px 5px; border-radius: 4px; }
    </style>
</head>
<body>

<div class="container-fluid">
    <div class="container-log">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2 class="titulo-pg"><i class="fas fa-history"></i> Log de Acessos: Empresas</h2>
            <a href="/painel-adm.php" class="btn btn-secondary btn-sm">
                <i class="fas fa-arrow-left"></i> Voltar ao Painel
            </a>
        </div>

        <?php if (isset($erro_critico)): ?>
            <div class="alert alert-danger"><?= $erro_critico ?></div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Data/Hora</th>
                            <th>Empresa</th>
                            <th>E-mail</th>
                            <th>Status/Perfil</th>
                            <th>Página Visitada</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($acessos) > 0): ?>
                            <?php foreach ($acessos as $row): ?>
                                <tr>
                                    <td><small><?= date('d/m/Y H:i:s', strtotime($row['data_acesso'])) ?></small></td>
                                    <td><strong><?= htmlspecialchars($row['nome_empresa']) ?></strong></td>
                                    <td><?= htmlspecialchars($row['empresa_email']) ?></td>
                                    <td>
                                        <?php 
                                        if ($row['total_pagos'] > 0) {
                                            echo '<span class="badge badge-pago"><i class="fas fa-check-circle"></i> Paga</span> ';
                                        }
                                        if ($row['total_gratuitos'] > 0) {
                                            echo '<span class="badge badge-gratuito">Gratuita</span>';
                                        }
                                        if ($row['total_pagos'] == 0 && $row['total_gratuitos'] == 0) {
                                            echo '<span class="badge badge-nenhum">Sem Anúncios</span>';
                                        }
                                        ?>
                                    </td>
                                    <td><span class="text-url"><?= htmlspecialchars($row['pagina_acessada']) ?></span></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="5" class="text-center py-4 text-muted">Nenhum histórico de acesso encontrado para empresas.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
</body>
</html>