<?php
session_start();

if (!isset($_SESSION['id'])) {
    header("Location: index.php");
    exit();
}

$db = new SQLite3("api/.anspanel.db");
$message = '';

// ==================== EXCLUSÃO ====================
if (isset($_GET['delete']) && $_SESSION['admin']) {
    $id = intval($_GET['delete']);
    $stmt = $db->prepare("DELETE FROM USERS WHERE id=:id");
    $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
    $stmt->execute();
    $message = '<div class="alert alert-success text-center">Usuário excluído com sucesso.</div>';
}

// ==================== EDIÇÃO ====================
if (isset($_POST['edit']) && $_SESSION['admin']) {
    $id = intval($_POST['id']);
    $validade = trim($_POST['validade']);
    $username = trim($_POST['username']);
    $password = trim($_POST['password'] ?? '');

    if ($password !== '') {
        $hashed = password_hash($password, PASSWORD_DEFAULT);
        $stmt = $db->prepare("UPDATE USERS SET NAME=:name, USERNAME=:username, PASSWORD=:password WHERE id=:id");
        $stmt->bindValue(':password', $hashed, SQLITE3_TEXT);
    } else {
        $stmt = $db->prepare("UPDATE USERS SET NAME=:name, USERNAME=:username WHERE id=:id");
    }
    $stmt->bindValue(':name', $validade, SQLITE3_TEXT);
    $stmt->bindValue(':username', $username, SQLITE3_TEXT);
    $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
    $stmt->execute();
    $message = '<div class="alert alert-success text-center">Usuário atualizado com sucesso.</div>';
}

// ==================== FILTRO ====================
$search = trim($_GET['search'] ?? '');
$filterSql = '';
if ($search !== '') {
    $filterSql = " WHERE USERNAME LIKE :search OR NAME LIKE :search ";
}

// ==================== PAGINAÇÃO ====================
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 12;
$offset = ($page - 1) * $perPage;

$totalQuery = $db->prepare("SELECT COUNT(*) as total FROM USERS $filterSql");
if ($search !== '') $totalQuery->bindValue(':search', "%$search%", SQLITE3_TEXT);
$total = $totalQuery->execute()->fetchArray(SQLITE3_ASSOC)['total'] ?? 0;
$totalPages = ceil($total / $perPage);

// ==================== BUSCA USUÁRIOS ====================
$sql = "SELECT id, USERNAME, NAME, ADMIN FROM USERS $filterSql ORDER BY id DESC LIMIT :limit OFFSET :offset";
$stmt = $db->prepare($sql);
if ($search !== '') $stmt->bindValue(':search', "%$search%", SQLITE3_TEXT);
$stmt->bindValue(':limit', $perPage, SQLITE3_INTEGER);
$stmt->bindValue(':offset', $offset, SQLITE3_INTEGER);
$users = $stmt->execute();

// ==================== GRÁFICOS ====================
// Total de revendas
$totalRevendas = $db->querySingle("SELECT COUNT(*) FROM USERS");
// Total de admins
$totalAdmins = $db->querySingle("SELECT COUNT(*) FROM USERS WHERE ADMIN=1");
// Usuários por validade (ex: por mês) - exemplo simples
$validades = $db->query("SELECT NAME, COUNT(*) as total FROM USERS GROUP BY NAME");
$chartLabels = [];
$chartData = [];
while ($row = $validades->fetchArray(SQLITE3_ASSOC)) {
    $chartLabels[] = $row['NAME'];
    $chartData[] = $row['total'];
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Gerenciador de Revendas</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body { font-family: 'Roboto', sans-serif; background: #0f1b34; color: #e0e0e0; padding: 20px; }
.container { max-width: 1200px; margin: auto; }
h2 { text-align: center; margin-bottom: 30px; color: #00ffff; text-shadow: 1px 1px 5px #000; }
.card { background: #0f172a; border-radius: 15px; padding: 20px; box-shadow: 0 0 0px rgba(0,255,255,0.2); transition: transform 0.2s, box-shadow 0.2s; }
.card:hover { transform: translateY(-5px); box-shadow: 0 0 30px rgba(0,255,255,0.5); }
.btn { border-radius: 50px; transition: all 0.2s; }
.btn:hover { opacity: 0.85; }
.search-bar { margin-bottom: 20px; }
.badge-admin { background: #ff00ff; }
.alert { margin-top: 15px; }
.pagination { justify-content: center; }
.stats-card { text-align: center; color: #fff; }
.stats-card h3 { color: #00ffff; }
</style>

<style>
/* ===== TEMA DARK GLOBAL ===== */
*{color:#e5e7eb !important}
html,body{
  background:#0f1b34 !important;
  font-family:Inter,Arial,sans-serif;
}
div,section,header,footer,.container,.card{
  background:#0f1b34 !important;
  border-radius:12px;
}
table,thead,tbody,tr,td,th{
  background:#0f1b34 !important;
  border-color:#1f2a44 !important;
}
a{color:#93c5fd !important;text-decoration:none}
button,.btn{
  background:#1b2f5a !important;
  color:#fff !important;
  border:none !important;
  border-radius:8px;
  padding:8px 14px;
}
button:hover,.btn:hover{background:#25407a !important}
input,select,textarea{
  background:#111c36 !important;
  color:#fff !important;
  border:1px solid #1f2a44 !important;
  border-radius:6px;
}

/* ===== ANIMAÇÕES ===== */
@keyframes fadeUp{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}
@keyframes fadeIn{from{opacity:0}to{opacity:1}}

body{animation:fadeIn .6s ease-in-out}
.container,.card,table{animation:fadeUp .6s ease forwards}

button,a,.btn{transition:all .25s ease}
button:hover,.btn:hover{
  transform:translateY(-2px) scale(1.03);
  box-shadow:0 12px 30px rgba(0,0,0,.5);
}
input:focus,select:focus,textarea:focus{
  box-shadow:0 0 0 2px rgba(59,130,246,.4);
  border-color:#3b82f6 !important;
}
table tbody tr{
  transition:background .2s ease, transform .2s ease;
}
table tbody tr:hover{
  background:#111c36 !important;
  transform:scale(1.01);
}
</style>

</head>
<body>

<div class="container">
    <h2>Gerenciador de Revendas</h2>

    <div class="mb-3">
        <a href="users.php" class="btn btn-outline-info"><i class="fas fa-arrow-left me-1"></i> Voltar para Meu Usuário</a>
    </div>

    <?php echo $message; ?>

    <div class="row mb-4 g-4">
        <div class="col-md-4">
            <div class="card stats-card">
                <h3>Total de Revendas</h3>
                <p style="font-size: 2rem;"><?= $totalRevendas ?></p>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card stats-card">
                <h3>Total de Admins</h3>
                <p style="font-size: 2rem;"><?= $totalAdmins ?></p>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card stats-card">
                <h3>Distribuição por Validade</h3>
                <canvas id="validadeChart"></canvas>
            </div>
        </div>
    </div>

    <!-- Filtro -->
    <form class="row g-2 search-bar" method="GET">
        <div class="col-md-8 col-sm-12">
            <input type="text" name="search" class="form-control" placeholder="Buscar usuário ou validade" value="<?= htmlspecialchars($search) ?>">
        </div>
        <div class="col-md-2 col-sm-6">
            <button class="btn btn-primary w-100"><i class="fas fa-search me-1"></i> Filtrar</button>
        </div>
    </form>

    <div class="row g-4">
        <?php while($row = $users->fetchArray(SQLITE3_ASSOC)): ?>
        <div class="col-md-4 col-sm-6">
            <div class="card">
                <h5><?= htmlspecialchars($row['USERNAME']) ?> 
                    <?php if($row['ADMIN']): ?><span class="badge badge-admin">ADMIN</span><?php endif; ?>
                </h5>
                <p>Validade: <?= htmlspecialchars($row['NAME']) ?></p>
                <div class="d-flex gap-2 flex-wrap">
                    <button class="btn btn-sm btn-info" onclick="editUser(<?= $row['id'] ?>,'<?= htmlspecialchars($row['USERNAME']) ?>','<?= $row['NAME'] ?>')">
                        <i class="fas fa-edit"></i> Editar
                    </button>
                    <?php if($_SESSION['admin']): ?>
                    <a href="?delete=<?= $row['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Deseja excluir este usuário?')">
                        <i class="fas fa-trash-alt"></i> Excluir
                    </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endwhile; ?>
    </div>

    <!-- Paginação -->
    <nav class="mt-4">
      <ul class="pagination">
        <li class="page-item <?= $page==1?'disabled':'' ?>"><a class="page-link" href="?page=<?= $page-1 ?>&search=<?= htmlspecialchars($search) ?>">Anterior</a></li>
        <?php for($i=1;$i<=$totalPages;$i++): ?>
            <li class="page-item <?= $page==$i?'active':'' ?>">
                <a class="page-link" href="?page=<?= $i ?>&search=<?= htmlspecialchars($search) ?>"><?= $i ?></a>
            </li>
        <?php endfor; ?>
        <li class="page-item <?= $page==$totalPages?'disabled':'' ?>"><a class="page-link" href="?page=<?= $page+1 ?>&search=<?= htmlspecialchars($search) ?>">Próximo</a></li>
      </ul>
    </nav>
</div>

<!-- Modal de edição -->
<div class="modal fade" id="editModal" tabindex="-1">
  <div class="modal-dialog">
    <form method="POST" class="modal-content bg-dark text-white">
      <div class="modal-header">
        <h5 class="modal-title">Editar Usuário</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="id" id="edit_id">
        <div class="mb-3">
            <input type="date" name="validade" id="edit_validade" class="form-control" required>
        </div>
        <div class="mb-3">
            <input type="text" name="username" id="edit_username" class="form-control" required>
        </div>
        <div class="mb-3">
            <input type="password" name="password" class="form-control" placeholder="Nova senha (opcional)">
        </div>
      </div>
      <div class="modal-footer">
        <button type="submit" name="edit" class="btn btn-success">Salvar</button>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
      </div>
    </form>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script>
function editUser(id, username, validade) {
    document.getElementById('edit_id').value = id;
    document.getElementById('edit_username').value = username;
    document.getElementById('edit_validade').value = validade;
    var modal = new bootstrap.Modal(document.getElementById('editModal'));
    modal.show();
}

// Gráfico de validade
const ctx = document.getElementById('validadeChart').getContext('2d');
new Chart(ctx, {
    type: 'bar',
    data: {
        labels: <?= json_encode($chartLabels) ?>,
        datasets: [{
            label: 'Revendas por Validade',
            data: <?= json_encode($chartData) ?>,
            backgroundColor: 'rgba(0, 255, 255, 0.6)',
            borderColor: 'rgba(0, 255, 255, 1)',
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        plugins: { legend: { display: false } },
        scales: { y: { beginAtZero: true } }
    }
});
</script>
</body>
</html>
