<?php
session_start();
include('../includes/config.php');

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

function queryCount($conn, $sql){
    $result = mysqli_query($conn, $sql);
    if(!$result){
        die("Query Error: ".mysqli_error($conn));
    }
    $row = mysqli_fetch_assoc($result);
    return $row['total'] ?? 0;
}


$totalProduk = queryCount($conn, "SELECT COUNT(*) AS total FROM produk");
$totalPesanan = queryCount($conn, "SELECT COUNT(*) AS total FROM pesanan");
$totalPendapatan = queryCount($conn, "SELECT SUM(jumlah) AS total FROM pembayaran WHERE status='Lunas'");
$totalUser = queryCount($conn, "SELECT COUNT(*) AS total FROM users WHERE role='user'");
$pesananPending = queryCount($conn, "SELECT COUNT(*) AS total FROM pesanan WHERE status='Menunggu Verifikasi'");
$produkHabis = queryCount($conn, "SELECT COUNT(DISTINCT id_produk) AS total FROM produk_detail WHERE stok = 0");
$produkMinim = queryCount($conn, "SELECT COUNT(DISTINCT id_produk) AS total FROM produk_detail WHERE stok > 0 AND stok <= 2");


$dataBulan = [];
$dataTotal = [];
$pendapatanBulanan = mysqli_query($conn, "
    SELECT DATE_FORMAT(tanggal_pembayaran, '%M %Y') AS bulan, SUM(jumlah) AS total 
    FROM pembayaran WHERE status='Lunas' 
    GROUP BY YEAR(tanggal_pembayaran), MONTH(tanggal_pembayaran)
    ORDER BY YEAR(tanggal_pembayaran) DESC, MONTH(tanggal_pembayaran) DESC LIMIT 3
");
$resGrafik = mysqli_query($conn, "SELECT DATE_FORMAT(tanggal_pembayaran, '%M %Y') AS bln, SUM(jumlah) AS tot FROM pembayaran WHERE status='Lunas' GROUP BY YEAR(tanggal_pembayaran), MONTH(tanggal_pembayaran) ORDER BY YEAR(tanggal_pembayaran) ASC, MONTH(tanggal_pembayaran) ASC LIMIT 3");
while($rg = mysqli_fetch_assoc($resGrafik)){
    $dataBulan[] = $rg['bln'];
    $dataTotal[] = $rg['tot'];
}

$semuaProduk = mysqli_query($conn,"SELECT * FROM produk ORDER BY id DESC");
$pesananTerbaru = mysqli_query($conn,"
    SELECT p.*, u.username, pm.bukti_pembayaran
    FROM pesanan p
    LEFT JOIN pembayaran pm ON pm.id_pesanan = p.id
    JOIN users u ON p.id_user = u.id
    ORDER BY p.tanggal DESC LIMIT 10
");
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dashboard Admin - Alfateeh Sepatuku</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body{font-family:'Poppins',sans-serif;background:#f5f7fa;margin:0;padding:0;}
header{background:#1e88e5;color:#fff;padding:20px;text-align:center;font-size:1.5rem;}
nav{background:#2196f3;padding:10px 20px;display:flex;justify-content:space-between;align-items:center;color:#fff;}
nav a{color:#fff;text-decoration:none;margin-left:15px;font-weight:500;}
.container{width:95%;margin:20px auto;}
.cards{display:flex;flex-wrap:wrap;gap:20px;margin-bottom:30px;}
.card{flex:1 1 200px;background:#fff;padding:20px;border-radius:12px;box-shadow:0 4px 10px rgba(0,0,0,0.1);text-align:center;}
.card h3{margin-bottom:10px;color:#1e88e5;}
table{width:100%;border-collapse:collapse;background:#fff;border-radius:10px;overflow:hidden;box-shadow:0 4px 10px rgba(0,0,0,0.1);margin-bottom:30px;}
th,td{padding:10px;text-align:left;border-bottom:1px solid #ddd;}
th{background:#1e88e5;color:#fff;}
.btn{padding:5px 10px;background:#00b4d8;color:#fff;text-decoration:none;border-radius:5px;font-weight:600;transition:.3s;}
.btn:hover{background:#0096c7;}
.img-thumb{width:60px;height:60px;object-fit:cover;border-radius:5px;}
.status-label{font-weight:bold;}
.status-pending{color:orange;}
.status-kirim{color:blue;}
.status-selesai{color:green;}
.status-ditolak{color:red;}
.size-badge { display: inline-block; padding: 2px 6px; background: #e3f2fd; border: 1px solid #bbdefb; border-radius: 4px; margin: 2px; font-size: 11px; }
.out-of-stock-badge { background: #ff6b6b; color: white; border: none; }
</style>
</head>
<body>
<header>Dashboard Admin - Alfateeh Sepatuku</header>
<nav>
  <div>👑 Admin Panel</div>
  <div>
    <a href="index_admin.php">Dashboard</a>
    <a href="product_admin.php">Kelola Produk</a>
    <a href="logout.php">Logout</a>
  </div>
</nav>

<div class="container">

<div class="cards">
  <div class="card"><h3>Total Produk</h3><p><?= $totalProduk ?></p></div>
  <div class="card"><h3>Total Pesanan</h3><p><?= $totalPesanan ?></p></div>
  <div class="card"><h3>Total Pendapatan</h3><p>Rp <?= number_format($totalPendapatan,0,",",".") ?></p></div>
  <div class="card"><h3>Total User</h3><p><?= $totalUser ?></p></div>
  <div class="card"><h3>Pending</h3><p><?= $pesananPending ?></p></div>
  <div class="card"><h3>Stok Habis</h3><p><?= $produkHabis ?></p></div>
</div>

<div style="background:white; padding:20px; border-radius:12px; margin-bottom:30px; box-shadow:0 4px 10px rgba(0,0,0,0.1);">
    <h3 style="text-align:center;">Grafik Pendapatan 3 Bulan Terakhir</h3>
    <canvas id="incomeChart" style="max-height:300px;"></canvas>
</div>



<h2>Semua Produk</h2>
<table>
<thead>
<tr>
<th>Nama Produk</th>
<th>Harga</th>
<th>Stok per Ukuran</th>
<th>Gambar</th>
<th>Kategori</th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
<?php while($p=mysqli_fetch_assoc($semuaProduk)): ?>
<tr>
<td><?= htmlspecialchars($p['nama']) ?></td>
<td>Rp <?= number_format($p['harga'],0,",",".") ?></td>
<td>
    <?php 
    $id_p = $p['id'];
    $res_detail = mysqli_query($conn, "SELECT * FROM produk_detail WHERE id_produk = '$id_p' ORDER BY ukuran ASC");
    while($d = mysqli_fetch_assoc($res_detail)){
        $style = ($d['stok'] == 0) ? 'out-of-stock-badge' : '';
        echo "<span class='size-badge $style'>Size " . $d['ukuran'] . ": <b>" . $d['stok'] . "</b></span>";
    }
    ?>
</td>
<td><img src="../assets/img/<?= $p['gambar'] ?>" class="img-thumb"></td>
<td><?= htmlspecialchars($p['kategori'] ?? '-') ?></td>
<td>
  <a href="edit_produk.php?id=<?= $p['id'] ?>" class="btn">Edit</a>
  <a href="hapus_produk.php?id=<?= $p['id'] ?>" class="btn" style="background:red;" onclick="return confirm('Hapus?')">Hapus</a>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>

<h2>Pesanan Terbaru</h2>
<table>
<thead>
<tr>
<th>No Pesanan</th>
<th>No Resi</th>
<th>User</th>
<th>Total</th>
<th>Status</th>
<th>Tanggal</th>
<th>Bukti</th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
<?php while($o=mysqli_fetch_assoc($pesananTerbaru)): ?>
<tr>
<td><?= htmlspecialchars($o['no_pesanan']) ?></td>
<td><?= !empty($o['no_resi']) ? htmlspecialchars($o['no_resi']) : '-' ?></td>
<td><?= htmlspecialchars($o['username']) ?></td>
<td>Rp <?= number_format($o['total'],0,",",".") ?></td>
<td>
    <?php
    switch($o['status']){
        case 'Menunggu Verifikasi': echo '<span class="status-label status-pending">Menunggu Verifikasi</span>'; break;
        case 'Sedang dikirim': echo '<span class="status-label status-kirim">Sedang dikirim</span>'; break;
        case 'Selesai': echo '<span class="status-label status-selesai">Selesai</span>'; break;
        case 'Ditolak': echo '<span class="status-label status-ditolak">Ditolak</span>'; break;
        default: echo htmlspecialchars($o['status']);
    }
    ?>
</td>
<td><?= $o['tanggal'] ?></td>
<td>
    <?php if(!empty($o['bukti_pembayaran'])): ?>
    <img src="../<?= $o['bukti_pembayaran'] ?>" width="60">
    <?php else: ?> <small>Belum Upload</small> <?php endif; ?>
</td>
<td>
    <?php if($o['status'] == 'Menunggu Verifikasi'): ?>
    <a href="verifikasi_pembayaran.php?id=<?= $o['id'] ?>" class="btn">Verifikasi</a>
    <?php else: ?> - <?php endif; ?>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>

</div>

<script>
const ctx = document.getElementById('incomeChart').getContext('2d');
new Chart(ctx, {
    type: 'bar',
    data: {
        labels: <?= json_encode($dataBulan) ?>,
        datasets: [{
            label: 'Pendapatan (Rp)',
            data: <?= json_encode($dataTotal) ?>,
            backgroundColor: 'rgba(30, 136, 229, 0.7)',
            borderRadius: 5
        }]
    },
    options: { responsive: true, maintainAspectRatio: false }
});
</script>
</body>
</html>