<?php
// system_logs.php - Com Sidebar e Layout Responsivo
session_start();
require_once 'includes/db.php';

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

$tab = $_GET['tab'] ?? 'actions';
?>
<!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">
    
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/style.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/dark-theme.css">

    <style>
        body { background-color: #0f172a; color: #f8fafc; font-family: 'Segoe UI', sans-serif; overflow-x: hidden; }
        
        /* Ajustes dos Cards e Tabela */
        .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; padding: 12px 15px; }
        
        /* Nav Pills (Abas) */
        .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; }
        
        /* Badges */
        .badge-cost { background: rgba(239, 68, 68, 0.15); color: #f87171; border: 1px solid rgba(239, 68, 68, 0.3); }
        .badge-add { background: rgba(34, 197, 94, 0.15); color: #4ade80; border: 1px solid rgba(34, 197, 94, 0.3); }

        /* ============================================================
           LAYOUT RESPONSIVO (SIDEBAR + CONTEÚDO)
           ============================================================ */
        
        /* PC (Telas Grandes) */
        @media (min-width: 992px) {
            #sidebar { 
                display: block !important; 
                width: 240px; 
                position: fixed; top: 0; left: 0; height: 100vh; 
                z-index: 1000; overflow-y: auto; 
            }
            .right-column { 
                margin-left: 240px; 
                width: calc(100% - 240px); 
                padding: 0;
            }
            .btn-voltar-mobile { display: none; }
        }

        /* CELULAR (Telas Pequenas) */
        @media (max-width: 991px) {
            #sidebar { display: none !important; }
            .right-column { 
                margin-left: 0 !important; 
                width: 100% !important; 
                padding: 0;
            }
            .btn-voltar-mobile {
                display: inline-block;
                margin-right: 10px;
                color: #fff;
                font-size: 1.2rem;
            }
        }
    </style>
</head>
<body>

<div class="container-fluid p-0">
    <div class="row no-gutters">
        
        <?php include 'includes/sidebar.php'; ?>

        <div class="right-column">

            <div class="page-header d-flex justify-content-between align-items-center sticky-top">
                <div class="d-flex align-items-center">
                    <a href="dashboard.php" class="btn-voltar-mobile"><i class="fa fa-arrow-left"></i></a>
                    <h4 class="mb-0 font-weight-bold"><i class="fa-solid fa-file-contract text-info mr-2"></i> Logs do Sistema</h4>
                </div>
                <a href="dashboard.php" class="btn btn-outline-secondary btn-sm d-none d-lg-inline-block">
                    <i class="fa fa-arrow-left"></i> Voltar
                </a>
            </div>

            <div class="container-fluid px-4 pb-5">
                
                <ul class="nav nav-pills mb-4">
                    <li class="nav-item"><a class="nav-link <?php echo $tab == 'actions' ? 'active' : ''; ?>" href="?tab=actions"><i class="fa-solid fa-cart-shopping mr-1"></i> Gastos & Ações</a></li>
                    <li class="nav-item"><a class="nav-link <?php echo $tab == 'credits' ? 'active' : ''; ?>" href="?tab=credits"><i class="fa-solid fa-right-left mr-1"></i> Transferências</a></li>
                    <li class="nav-item"><a class="nav-link <?php echo $tab == 'login' ? 'active' : ''; ?>" href="?tab=login"><i class="fa-solid fa-shield-halved mr-1"></i> Logins</a></li>
                </ul>

                <div class="card">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            
                            <?php if($tab == 'actions'): ?>
                            <thead>
                                <tr>
                                    <th>Revendedor</th>
                                    <th>Ação</th>
                                    <th>Custo</th>
                                    <th>Detalhes</th>
                                    <th>Data</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                try {
                                    $sql = "SELECT l.*, r.username 
                                            FROM users_logs l 
                                            LEFT JOIN revendedores r ON l.owner = r.id 
                                            ORDER BY l.id DESC LIMIT 50";
                                    $stmt = $pdo->query($sql);
                                    while($r = $stmt->fetch(PDO::FETCH_ASSOC)){
                                        $user = $r['username'] ? $r['username'] : 'Admin';
                                        
                                        $acao = $r['action'];
                                        if($acao == 'create_user') $acao = '<span class="badge badge-success">Criou Usuário</span>';
                                        elseif($acao == 'renew_user') $acao = '<span class="badge badge-info">Renovou</span>';
                                        elseif($acao == 'create_trial') $acao = '<span class="badge badge-warning">Teste</span>';
                                        else $acao = '<span class="badge badge-secondary">'.$acao.'</span>';

                                        $custo = $r['cost'] > 0 ? "<span class='badge badge-cost'>-{$r['cost']}</span>" : "<span class='text-muted'>0</span>";

                                        echo "<tr>
                                            <td class='font-weight-bold text-white'>{$user}</td>
                                            <td>{$acao}</td>
                                            <td>{$custo}</td>
                                            <td class='text-muted small'>".($r['deleted_info'] ?? '')."</td>
                                            <td>".date('d/m H:i', strtotime($r['date']))."</td>
                                        </tr>";
                                    }
                                } catch(Exception $e) {
                                    echo "<tr><td colspan='5' class='text-center text-danger'>Erro ao ler users_logs.</td></tr>";
                                }
                                ?>
                            </tbody>

                            <?php elseif($tab == 'credits'): ?>
                            <thead>
                                <tr>
                                    <th>De (Admin)</th>
                                    <th>Para (Revenda)</th>
                                    <th>Qtd</th>
                                    <th>Motivo</th>
                                    <th>Data</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                try {
                                    $sql = "SELECT l.*, r1.username as admin_name, r2.username as target_name 
                                            FROM credits_log l 
                                            LEFT JOIN revendedores r1 ON l.admin_id = r1.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)){
                                        $adm = $r['admin_name'] ? $r['admin_name'] : 'Sistema';
                                        $target = $r['target_name'] ? $r['target_name'] : 'N/A';
                                        $qtd = "<span class='badge badge-add'>+{$r['amount']}</span>";

                                        echo "<tr>
                                            <td class='text-warning'>{$adm}</td>
                                            <td class='text-white'>{$target}</td>
                                            <td>{$qtd}</td>
                                            <td>".($r['reason'] ?? '')."</td>
                                            <td>".date('d/m H:i', strtotime($r['date']))."</td>
                                        </tr>";
                                    }
                                } catch(Exception $e) {}
                                ?>
                            </tbody>

                            <?php elseif($tab == 'login'): ?>
                            <thead><tr><th>Usuário</th><th>IP</th><th>Status</th><th>Data</th></tr></thead>
                            <tbody>
                                <?php
                                try {
                                    $check = $pdo->query("SHOW TABLES LIKE 'login_logs'");
                                    if($check->rowCount() > 0) {
                                        $sql = "SELECT l.*, r.username FROM login_logs l LEFT JOIN revendedores r ON l.user_id = r.id ORDER BY l.id DESC LIMIT 50";
                                        $stmt = $pdo->query($sql);
                                        while($r = $stmt->fetch(PDO::FETCH_ASSOC)){
                                            $st = ($r['status'] == 'Success') ? 'text-success' : 'text-danger';
                                            echo "<tr><td><b>".($r['username']??'Desc.')."</b></td><td>{$r['login_ip']}</td><td class='{$st}'>{$r['status']}</td><td>".date('d/m H:i', strtotime($r['date']))."</td></tr>";
                                        }
                                    }
                                } catch(Exception $e) {}
                                ?>
                            </tbody>
                            <?php endif; ?>

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.bundle.min.js"></script>
</body>
</html>