<?php
session_start();
require_once "config.php";
include "header.php";

if (!isset($_SESSION['user']) || $_SESSION['user']['role'] !== 'admin') {
    header('Location: login.php');
    exit;
}

// stats
$countUsers = $pdo->query("SELECT COUNT(*) FROM utilisateurs")->fetchColumn();
$countPosts = $pdo->query("SELECT COUNT(*) FROM posts")->fetchColumn();
$postsPerUser = $pdo->query("
    SELECT u.username, COUNT(p.id) AS total
    FROM utilisateurs u
    LEFT JOIN posts p ON p.user_id = u.id
    GROUP BY u.id
")->fetchAll(PDO::FETCH_ASSOC);

$users = $pdo->query("SELECT id, username, role FROM utilisateurs ORDER BY id")->fetchAll();
$posts = $pdo->query("SELECT p.id, p.title, u.username FROM posts p JOIN utilisateurs u ON p.user_id = u.id ORDER BY p.date_creation DESC")->fetchAll();

$msg = '';
if (isset($_GET['delete_user'])) {
    $id = (int)$_GET['delete_user'];
    if ($id !== (int)$_SESSION['user']['id']) {
        $pdo->prepare("DELETE FROM utilisateurs WHERE id = ?")->execute([$id]);
        $msg = "Utilisateur supprimé ✅";
    }
}
if (isset($_GET['delete_post'])) {
    $pdo->prepare("DELETE FROM posts WHERE id = ?")->execute([(int)$_GET['delete_post']]);
    $msg = "Article supprimé ✅";
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Dashboard - Admin</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body {
  font-family: 'Poppins', sans-serif;
  background: #fff4f7;
  margin: 0;
  padding: 0;
  color: #222;
}
.dashboard-container {
  max-width: 1100px;
  margin: 40px auto;
  background: #fff;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 6px 14px rgba(0,0,0,0.08);
}
h2 {
  color: #ff69b4;
  text-align: center;
  margin-bottom: 20px;
}
.stats-cards {
  display: flex;
  gap: 20px;
  justify-content: center;
  margin-bottom: 40px;
}
.card {
  flex: 1;
  background: linear-gradient(135deg, #ff69b4, #ffa07a, #d17eff);
  color: white;
  padding: 25px;
  border-radius: 15px;
  text-align: center;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}
.card p {
  font-size: 26px;
  margin: 0;
}
table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 25px;
}
th {
  background: #ffe1ec;
  padding: 10px;
  text-align: left;
}
td {
  padding: 10px;
  border-bottom: 1px solid #f3cbd7;
}
.btn-delete, .btn-edit {
  text-decoration: none;
  color: #fff;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 13px;
  font-weight: 600;
}
.btn-delete { background: #ff8b94; }
.btn-edit { background: #ff69b4; }
.chart-container {
  margin-top: 30px;
  background: #fffafc;
  border-radius: 10px;
  padding: 20px;
}
.msg {
  text-align: center;
  color: green;
  font-weight: bold;
}
</style>
</head>
<body>
<div class="dashboard-container">
  <h2>🌸 Tableau de bord administrateur</h2>
  <?php if ($msg): ?><div class="msg"><?= htmlspecialchars($msg) ?></div><?php endif; ?>

  <div class="stats-cards">
    <div class="card"><h3>Utilisateurs</h3><p><?= (int)$countUsers ?></p></div>
    <div class="card"><h3>Articles</h3><p><?= (int)$countPosts ?></p></div>
  </div>

  <div class="chart-container">
    <canvas id="statsChart"></canvas>
  </div>

  <h3>👥 Gestion des utilisateurs</h3>
  <table>
    <tr><th>ID</th><th>Nom</th><th>Rôle</th><th>Actions</th></tr>
    <?php foreach($users as $u): ?>
      <tr>
        <td><?= $u['id'] ?></td>
        <td><?= htmlspecialchars($u['username']) ?></td>
        <td><?= htmlspecialchars($u['role']) ?></td>
        <td>
          <?php if ($u['id'] !== $_SESSION['user']['id']): ?>
            <a href="dashboard.php?delete_user=<?= $u['id'] ?>" class="btn-delete" onclick="return confirm('Supprimer cet utilisateur ?')">Supprimer</a>
          <?php else: ?>
            (vous)
          <?php endif; ?>
        </td>
      </tr>
    <?php endforeach; ?>
  </table>

  <h3 style="margin-top:25px;">📝 Gestion des articles</h3>
  <table>
    <tr><th>ID</th><th>Titre</th><th>Auteur</th><th>Actions</th></tr>
    <?php foreach($posts as $p): ?>
      <tr>
        <td><?= $p['id'] ?></td>
        <td><?= htmlspecialchars($p['title']) ?></td>
        <td><?= htmlspecialchars($p['username']) ?></td>
        <td>
          <a href="edit_article.php?id=<?= $p['id'] ?>" class="btn-edit">Modifier</a>
          <a href="dashboard.php?delete_post=<?= $p['id'] ?>" class="btn-delete" onclick="return confirm('Supprimer cet article ?')">Supprimer</a>
        </td>
      </tr>
    <?php endforeach; ?>
  </table>
</div>

<script>
const ctx = document.getElementById('statsChart');
const chartData = {
  labels: <?= json_encode(array_column($postsPerUser, 'username')) ?>,
  datasets: [{
    label: 'Articles par auteur',
    data: <?= json_encode(array_column($postsPerUser, 'total')) ?>,
    backgroundColor: ['#ff69b4', '#ffa07a', '#d17eff', '#ffc3a0', '#c99aff'],
    borderRadius: 8
  }]
};
new Chart(ctx, {
  type: 'bar',
  data: chartData,
  options: {
    plugins: {
      legend: { display: false },
      title: { display: true, text: 'Répartition des articles par utilisateur', color: '#ff69b4' }
    },
    scales: {
      y: { beginAtZero: true }
    }
  }
});
</script>
</body>
</html>
<?php include "footer.php"; ?>

