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

session_start();
require '../includes/conexao.php';

// SEGURANÇA
if (!isset($_SESSION['account_id'])) { header("Location: ../login.php"); exit; }

$stmt = $pdo->prepare("SELECT page_access, name FROM accounts WHERE id = ?");
$stmt->execute([$_SESSION['account_id']]);
$acc = $stmt->fetch();

if (!$acc || $acc['page_access'] < 3) {
    die("<div class='container p-5 text-center text-white bg-dark'><h1>⛔ Acesso Negado</h1><a href='../index.php' class='btn btn-light'>Voltar</a></div>");
}

$page_title = "Logs & Auditoria";

// Header
if(file_exists('../includes/admin_header.php')) include '../includes/admin_header.php';
else include '../includes/header.php';

// --- 1. BUSCAR LOGS DO SHOP (VENDAS) ---
$shopLogs = $pdo->query("
    SELECT h.*, a.name as account_name 
    FROM shop_history h 
    LEFT JOIN accounts a ON h.account_id = a.id 
    ORDER BY h.date DESC 
    LIMIT 100
")->fetchAll();

// --- 2. BUSCAR LOGS ADMINISTRATIVOS ---
$adminLogs = $pdo->query("
    SELECT l.*, 
           adm.name as admin_name, 
           target.name as target_name
    FROM site_admin_logs l
    LEFT JOIN accounts adm ON l.admin_id = adm.id
    LEFT JOIN accounts target ON l.target_id = target.id
    ORDER BY l.date DESC 
    LIMIT 100
")->fetchAll();
?>

<style>
    /* Admin Dark Theme */
    body { background-color: #0f172a; color: #f8fafc; font-family: 'Poppins', sans-serif; }
    .card { background-color: #1e293b; border: 1px solid rgba(255,255,255,0.1); color: #fff; border-radius: 12px; }
    
    /* Tabs */
    .nav-tabs .nav-link { color: #94a3b8; border: none; font-weight: 600; padding: 12px 20px; }
    .nav-tabs .nav-link.active { background-color: #1e293b; color: #3b82f6; border-bottom: 3px solid #3b82f6; }
    .nav-tabs { border-bottom: 1px solid rgba(255,255,255,0.1); }

    /* Tables */
    .table { color: #cbd5e1; }
    .table tbody tr:hover { background-color: rgba(255,255,255,0.02); color: #fff; }
    .table thead th { background-color: #0f172a; border-bottom: 2px solid #334155; color: #94a3b8; font-size: 0.8rem; text-transform: uppercase; }
    
    /* Utils */
    .text-white-50 { color: rgba(255,255,255,0.6) !important; }
</style>

<div class="container my-5">

    <div class="d-flex justify-content-between align-items-center mb-4 border-bottom border-secondary pb-3">
        <div>
            <h2 class="fw-bold text-white mb-0"><i class="fas fa-file-invoice-dollar text-warning me-2"></i>Auditoria</h2>
            <p class="text-white-50 m-0">Monitore vendas e ações da staff.</p>
        </div>
        <span class="badge bg-danger shadow-sm"><i class="fas fa-lock me-1"></i> Logs Imutáveis</span>
    </div>

    <div class="card shadow">
        <div class="card-header bg-transparent border-0 pt-3 px-3">
            <ul class="nav nav-tabs card-header-tabs" id="logsTab" role="tablist">
                <li class="nav-item">
                    <button class="nav-link active" id="shop-tab" data-bs-toggle="tab" data-bs-target="#shop-logs" type="button"><i class="fas fa-shopping-cart me-2"></i> Vendas do Shop</button>
                </li>
                <li class="nav-item">
                    <button class="nav-link" id="admin-tab" data-bs-toggle="tab" data-bs-target="#admin-logs" type="button"><i class="fas fa-user-shield me-2"></i> Ações da Staff</button>
                </li>
            </ul>
        </div>
        
        <div class="card-body p-0">
            <div class="tab-content">
                
                <div class="tab-pane fade show active" id="shop-logs">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead>
                                <tr>
                                    <th class="ps-4">Data</th>
                                    <th>Cliente</th>
                                    <th>Produto</th>
                                    <th>Valor</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(empty($shopLogs)): ?>
                                    <tr><td colspan="5" class="text-center py-5 text-muted">Nenhuma venda registrada.</td></tr>
                                <?php else: foreach($shopLogs as $log): ?>
                                <tr>
                                    <td class="ps-4 text-white-50 small"><i class="far fa-clock me-1"></i> <?php echo date('d/m/Y H:i', $log['date']); ?></td>
                                    <td class="fw-bold text-white"><?php echo htmlspecialchars($log['account_name'] ?? 'ID: '.$log['account_id']); ?></td>
                                    <td>
                                        <span class="text-info fw-bold"><?php echo htmlspecialchars($log['offer_name']); ?></span>
                                        <?php if($log['count'] > 1): ?><span class="badge bg-secondary rounded-pill ms-1">x<?php echo $log['count']; ?></span><?php endif; ?>
                                    </td>
                                    <td><span class="badge bg-success bg-opacity-10 text-success border border-success">- <?php echo $log['points_cost']; ?> Pts</span></td>
                                    <td>
                                        <?php if($log['status'] == 'delivered'): ?>
                                            <span class="badge bg-success"><i class="fas fa-check"></i> Entregue</span>
                                        <?php else: ?>
                                            <span class="badge bg-warning text-dark"><i class="fas fa-spinner fa-spin"></i> Pendente</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="tab-pane fade" id="admin-logs">
                    
                    <div class="alert alert-warning bg-opacity-10 border-warning text-warning m-3 d-flex align-items-center">
                        <i class="fas fa-exclamation-triangle fa-2x me-3"></i>
                        <div>
                            <strong>Área Sensível:</strong> Aqui ficam registrados todos os comandos administrativos críticos (adição de pontos, banimentos, trocas de cargo).
                        </div>
                    </div>

                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead>
                                <tr>
                                    <th class="ps-4">Data</th>
                                    <th>Staff (Autor)</th>
                                    <th>Alvo</th>
                                    <th>Ação / Detalhes</th>
                                    <th>IP Origem</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(empty($adminLogs)): ?>
                                    <tr><td colspan="5" class="text-center py-5 text-muted">Nenhuma ação registrada.</td></tr>
                                <?php else: foreach($adminLogs as $log): ?>
                                <tr>
                                    <td class="ps-4 text-white-50 small"><?php echo date('d/m/y H:i', $log['date']); ?></td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div class="bg-danger rounded-circle text-white d-flex align-items-center justify-content-center me-2" style="width:24px; height:24px;"><i class="fas fa-user-shield small"></i></div>
                                            <span class="fw-bold text-danger"><?php echo htmlspecialchars($log['admin_name']); ?></span>
                                        </div>
                                    </td>
                                    <td class="text-info fw-bold"><?php echo htmlspecialchars($log['target_name'] ?? 'ID: '.$log['target_id']); ?></td>
                                    <td class="text-white-50"><?php echo htmlspecialchars($log['description']); ?></td>
                                    <td><code class="text-warning bg-dark border border-secondary px-2 py-1 rounded"><?php echo $log['ip']; ?></code></td>
                                </tr>
                                <?php endforeach; endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

            </div>
        </div>
    </div>

</div>

<?php if(file_exists('../includes/admin_footer.php')) include '../includes/admin_footer.php'; else include '../includes/footer.php'; ?>