<?php
// admin/users.php
require '../config/db.php';
if (session_status() === PHP_SESSION_NONE) { session_start(); }

// 1. SEGURIDAD & RUTAS
$current_role = $_SESSION['role'] ?? 'user';
if ($current_role !== 'admin') { header("Location: ../index.php"); exit; }

$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
$full_admin_url = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];

// 2. FUNCIÓN PARA REGISTRAR LOGS Y NOTIFICAR
function recordAction($pdo, $admin_id, $type, $target_id, $details, $notif_msg = null) {
    // Insertar Log
    $stmt = $pdo->prepare("INSERT INTO admin_logs (admin_id, action_type, target_user_id, details) VALUES (?, ?, ?, ?)");
    $stmt->execute([$admin_id, $type, $target_id, $details]);

    // Insertar Notificación para el usuario (si hay mensaje)
    if ($notif_msg) {
        $st = $pdo->prepare("INSERT INTO system_notifications (user_id, title, message) VALUES (?, ?, ?)");
        $st->execute([$target_id, "System Update", $notif_msg]);
    }
}

// 3. PROCESAMIENTO DE ACCIONES CON LOGS
if (isset($_GET['action']) && isset($_GET['id'])) {
    $tid = intval($_GET['id']);
    $action = $_GET['action'];
    $admin_id = $_SESSION['user_id'];

    try {
        if ($action === 'adjust_balance' && isset($_POST['amount'])) {
            $amt = floatval($_POST['amount']);
            $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?")->execute([$amt, $tid]);
            recordAction($pdo, $admin_id, 'BALANCE', $tid, "Adjusted balance by $amt", "Your balance has been updated by $amt.");
        }
        elseif ($action === 'toggle_ban') {
            $pdo->prepare("UPDATE users SET is_banned = 1 - is_banned WHERE id = ?")->execute([$tid]);
            recordAction($pdo, $admin_id, 'BAN', $tid, "Toggled ban status", "Security alert: Your account status has changed.");
        }
        // ... (Seguir con las demás acciones llamando a recordAction)
        
        header("Location: $full_admin_url?success=1"); exit;
    } catch (PDOException $e) { die($e->getMessage()); }
}

// 4. DATOS PARA LA GRÁFICA (Usuarios por día - últimos 7 días)
$graph_data = $pdo->query("SELECT DATE(created_at) as day, COUNT(*) as qty FROM users GROUP BY day ORDER BY day DESC LIMIT 7")->fetchAll(PDO::FETCH_ASSOC);

$users = $pdo->query("SELECT * FROM users ORDER BY created_at DESC")->fetchAll();
include '../includes/header.php';
?>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<style>
    :root { --adm-accent: #00ff88; --adm-card: #161b22; --adm-border: #30363d; }
    .admin-wrapper { max-width: 1250px; margin: 40px auto; padding: 0 20px; color: white; font-family: 'Inter', sans-serif; }
    .chart-container { background: var(--adm-card); border: 1px solid var(--adm-border); border-radius: 15px; padding: 20px; margin-bottom: 30px; height: 250px; }
    /* Reutilizamos los estilos anteriores de la tabla... */
</style>

<div class="admin-wrapper">
    <h1 style="font-family: 'Syncopate';">NETWORK<span>.INTELLIGENCE</span></h1>
    
    <div class="chart-container">
        <canvas id="growthChart"></canvas>
    </div>

    <div style="background: var(--adm-card); border: 1px solid var(--adm-border); border-radius: 12px; overflow: hidden;">
        <table style="width: 100%; border-collapse: collapse;">
            <thead style="background: rgba(0,0,0,0.3);">
                <tr>
                    <th style="padding:15px; text-align:left; font-size:10px;">ID / USER</th>
                    <th style="padding:15px; text-align:left; font-size:10px;">WALLET</th>
                    <th style="padding:15px; text-align:right; font-size:10px;">QUICK CONTROL</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($users as $u): ?>
                <tr style="border-top: 1px solid var(--adm-border);">
                    <td style="padding:15px;">
                        <b>@<?php echo $u['username']; ?></b>
                        <div style="font-size:10px; color:#8b949e;">ID: <?php echo $u['id']; ?></div>
                    </td>
                    <td style="padding:15px;">
                        <form method="POST" action="?id=<?php echo $u['id']; ?>&action=adjust_balance" style="display:flex; gap:5px;">
                            <input type="number" name="amount" placeholder="+/-" style="width:60px; background:#0d1117; border:1px solid #30363d; color:var(--adm-accent); border-radius:4px; padding:3px;">
                            <button style="background:var(--adm-accent); border:none; border-radius:4px; font-size:9px; cursor:pointer; font-weight:900;">GO</button>
                            <span style="margin-left:10px;">$<?php echo number_format($u['balance'], 2); ?></span>
                        </form>
                    </td>
                    <td style="padding:15px; text-align:right;">
                        <button onclick="alert('Historial de Logs: Proximamente')" style="background:none; border:1px solid #444; color:#888; cursor:pointer; padding:5px; border-radius:4px; font-size:10px;">LOGS</button>
                        <a href="?id=<?php echo $u['id']; ?>&action=toggle_ban" style="color:<?php echo $u['is_banned'] ? '#ff4d4d' : '#888'; ?>; margin-left:10px;"><i class="fa-solid fa-user-slash"></i></a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
// CONFIGURACIÓN DE LA GRÁFICA (PRO)
const ctx = document.getElementById('growthChart').getContext('2d');
new Chart(ctx, {
    type: 'line',
    data: {
        labels: <?php echo json_encode(array_column(array_reverse($graph_data), 'day')); ?>,
        datasets: [{
            label: 'New Registrations',
            data: <?php echo json_encode(array_column(array_reverse($graph_data), 'qty')); ?>,
            borderColor: '#00ff88',
            backgroundColor: 'rgba(0, 255, 136, 0.1)',
            fill: true,
            tension: 0.4
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: { y: { beginAtZero: true, grid: { color: '#222' } }, x: { grid: { display: false } } },
        plugins: { legend: { display: false } }
    }
});
</script>

<?php include '../includes/footer.php'; ?>