<?php
// system_logs.php - Corrigido para exibir nomes
session_start();
require_once 'includes/db.php';
require_once 'includes/logger.php';

// Apenas Admin
if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'admin' && $_SESSION['user_id'] != 1) { 
    header('Location: dashboard.php'); exit; 
}

// Filtro de abas
$tab = $_GET['tab'] ?? 'credits';
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Logs do Sistema</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { background-color: #0f172a; color: #f8fafc; font-family: sans-serif; }
        .page-header { background: #1e293b; padding: 20px; border-bottom: 1px solid #334155; margin-bottom: 30px; }
        .card { background: #1e293b; border: 1px solid #334155; border-radius: 10px; }
        .table { color: #cbd5e1; margin-bottom: 0; }
        .table td, .table th { border-top: 1px solid #334155; vertical-align: middle; }
        .nav-pills .nav-link { color: #94a3b8; background: #0f172a; border: 1px solid #334155; margin-right: 10px; border-radius: 8px; }
        .nav-pills .nav-link.active { background: #3b82f6; color: #fff; border-color: #3b82f6; }
        .badge-plus { background: rgba(34, 197, 94, 0.2); color: #22c55e; }
        .badge-minus { background: rgba(239, 68, 68, 0.2); color: #ef4444; }
    </style>
</head>
<body>

<div class="page-header d-flex justify-content-between align-items-center">
    <h4 class="mb-0"><i class="fa-solid fa-file-contract text-warning mr-2"></i> Logs do Sistema</h4>
    <a href="dashboard.php" class="btn btn-outline-light btn-sm">Voltar</a>
</div>

<div class="container-fluid px-4">
    
    <ul class="nav nav-pills mb-4">
        <li class="nav-item">
            <a class="nav-link <?php echo $tab == 'credits' ? 'active' : ''; ?>" href="?tab=credits">
                <i class="fa-solid fa-coins mr-1"></i> Créditos
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link <?php echo $tab == 'login' ? 'active' : ''; ?>" href="?tab=login">
                <i class="fa-solid fa-right-to-bracket mr-1"></i> Acessos
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link <?php echo $tab == 'actions' ? 'active' : ''; ?>" href="?tab=actions">
                <i class="fa-solid fa-user-gear mr-1"></i> Ações Adm
            </a>
        </li>
    </ul>

    <div class="card">
        <div class="table-responsive">
            <table class="table table-hover">
                
                <?php if($tab == 'credits'): ?>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Quem Enviou</th>
                        <th>Recebeu</th>
                        <th>Qtd</th>
                        <th>Motivo</th>
                        <th>Data</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    // CORREÇÃO: Busca nomes em 'revendedores' e 'adm'
                    $sql = "SELECT l.*, 
                                COALESCE(r1.username, a1.username, 'Sistema') as admin_name,
                                r2.username as target_name 
                            FROM credits_log l 
                            LEFT JOIN revendedores r1 ON l.admin_id = r1.id 
                            LEFT JOIN adm a1 ON l.admin_id = a1.id 
                            LEFT JOIN revendedores r2 ON l.target_id = r2.id 
                            ORDER BY l.id DESC LIMIT 50";
                    $stmt = $pdo->query($sql);
                    while($r = $stmt->fetch(PDO::FETCH_ASSOC)){
                        $badge = ($r['amount'] >= 0) ? 'badge-plus' : 'badge-minus';
                        echo "<tr>
                            <td>#{$r['id']}</td>
                            <td class='text-warning'>{$r['admin_name']}</td>
                            <td class='text-info'>{$r['target_name']}</td>
                            <td><span class='badge {$badge}'>{$r['amount']}</span></td>
                            <td>{$r['reason']}</td>
                            <td>".date('d/m H:i', $r['date'])."</td>
                        </tr>";
                    }
                    ?>
                </tbody>

                <?php elseif($tab == 'login'): ?>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Usuário</th>
                        <th>IP</th>
                        <th>Status</th>
                        <th>Data</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    // CORREÇÃO: Busca em 'revendedores' E 'adm' para garantir que o nome apareça
                    $sql = "SELECT l.*, 
                                r.username as res_name, 
                                a.username as adm_name 
                            FROM login_logs l 
                            LEFT JOIN revendedores r ON l.user_id = r.id 
                            LEFT JOIN adm a ON l.user_id = a.id 
                            ORDER BY l.id DESC LIMIT 50";
                            
                    $stmt = $pdo->query($sql);
                    while($r = $stmt->fetch(PDO::FETCH_ASSOC)){
                        $statusColor = ($r['status'] == 'Success') ? 'text-success' : 'text-danger';
                        
                        // Prioriza Revenda, se não achar tenta Admin
                        $username = $r['res_name'];
                        if(empty($username)) $username = $r['adm_name'];
                        if(empty($username)) $username = 'Desconhecido';

                        echo "<tr>
                            <td>#{$r['id']}</td>
                            <td><b>{$username}</b></td>
                            <td>{$r['login_ip']}</td>
                            <td class='{$statusColor}'>{$r['status']}</td>
                            <td>".date('d/m H:i', $r['date'])."</td>
                        </tr>";
                    }
                    ?>
                </tbody>

                <?php elseif($tab == 'actions'): ?>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Admin/Revenda</th>
                        <th>Ação</th>
                        <th>Detalhes</th>
                        <th>Data</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    // CORREÇÃO: Busca nome de quem fez a ação
                    $sql = "SELECT l.*, 
                                COALESCE(r.username, a.username) as username 
                            FROM users_logs l 
                            LEFT JOIN revendedores r ON l.owner = r.id 
                            LEFT JOIN adm a ON l.owner = a.id 
                            ORDER BY l.id DESC LIMIT 50";
                    $stmt = $pdo->query($sql);
                    while($r = $stmt->fetch(PDO::FETCH_ASSOC)){
                        echo "<tr>
                            <td>#{$r['id']}</td>
                            <td class='text-info'>{$r['username']}</td>
                            <td><b>{$r['action']}</b></td>
                            <td class='small text-muted'>{$r['deleted_info']}</td>
                            <td>".date('d/m H:i', $r['date'])."</td>
                        </tr>";
                    }
                    ?>
                </tbody>
                <?php endif; ?>

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

</body>
</html>
