<?php
// ============================================================
// FILE: admin/index.php — Dashboard Admin
// Fitur:
//  - 7 stat cards dengan highlight warna per kondisi
//  - Grafik pesanan 7 hari terakhir (Chart.js bar chart)
//  - Tabel 10 pesanan terbaru + quick verifikasi
//  - List stok rendah dengan tombol edit cepat
//  - Quick actions: tambah produk, kelola pesanan pending
//  - Notifikasi banner jika ada pesanan yang butuh aksi
// ============================================================
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';
requireAdmin();

$pdo = db();

// ── Statistik Utama ──────────────────────────────────────────
$stats = [
    'pesanan_baru'   => (int)$pdo->query("SELECT COUNT(*) FROM pesanan WHERE status='pending'")->fetchColumn(),
    'diproses'       => (int)$pdo->query("SELECT COUNT(*) FROM pesanan WHERE status IN('diverifikasi','diproses')")->fetchColumn(),
    'selesai_bulan'  => (int)$pdo->query("SELECT COUNT(*) FROM pesanan WHERE status='selesai' AND MONTH(created_at)=MONTH(NOW()) AND YEAR(created_at)=YEAR(NOW())")->fetchColumn(),
    'total_produk'   => (int)$pdo->query("SELECT COUNT(*) FROM produk WHERE is_aktif=1")->fetchColumn(),
    'stok_rendah'    => (int)$pdo->query("SELECT COUNT(*) FROM produk WHERE stok <= stok_minimum AND is_aktif=1")->fetchColumn(),
    'pendapatan_bln' => (float)$pdo->query("SELECT COALESCE(SUM(total_harga),0) FROM pesanan WHERE status='selesai' AND MONTH(created_at)=MONTH(NOW()) AND YEAR(created_at)=YEAR(NOW())")->fetchColumn(),
    'total_pesanan'  => (int)$pdo->query("SELECT COUNT(*) FROM pesanan")->fetchColumn(),
];

// ── Pesanan 7 hari terakhir (untuk chart) ────────────────────
$chart7 = $pdo->query("
    SELECT DATE(created_at) AS tgl, COUNT(*) AS jml
    FROM pesanan
    WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)
    GROUP BY DATE(created_at)
    ORDER BY tgl ASC
")->fetchAll(PDO::FETCH_KEY_PAIR);

// Isi hari yang tidak ada data dengan 0
$chartLabels = [];
$chartData   = [];
for ($i = 6; $i >= 0; $i--) {
    $tgl            = date('Y-m-d', strtotime("-$i days"));
    $chartLabels[]  = date('d/m', strtotime($tgl));
    $chartData[]    = (int)($chart7[$tgl] ?? 0);
}

// ── Pesanan terbaru 10 ────────────────────────────────────────
$pesananBaru = $pdo->query("
    SELECT p.*, pay.id AS pay_id, pay.midtrans_status
    FROM pesanan p
    LEFT JOIN pembayaran pay ON pay.pesanan_id=p.id
    ORDER BY p.created_at DESC LIMIT 10
")->fetchAll();

// ── Stok rendah ──────────────────────────────────────────────
$stokRendah = $pdo->query("
    SELECT p.id, p.nama, p.stok, p.stok_minimum, p.satuan, k.nama AS nama_kategori
    FROM produk p JOIN kategori k ON p.kategori_id=k.id
    WHERE p.stok <= p.stok_minimum AND p.is_aktif=1
    ORDER BY (p.stok / GREATEST(p.stok_minimum,0.01)) ASC LIMIT 8
")->fetchAll();

// ── Aktivitas pesanan per status (bulan ini) ─────────────────
$statusBulan = $pdo->query("
    SELECT status, COUNT(*) AS jml
    FROM pesanan
    WHERE MONTH(created_at)=MONTH(NOW()) AND YEAR(created_at)=YEAR(NOW())
    GROUP BY status
")->fetchAll(PDO::FETCH_KEY_PAIR);

$butuhAksi = $stats['pesanan_baru'];

$pageTitle = 'Dashboard';
include __DIR__ . '/admin_layout.php';
?>

<?php if ($butuhAksi > 0): ?>
<!-- Banner notifikasi -->
<div class="adm-notif-banner mb-4">
  <div class="adm-notif-icon"><i class="bi bi-bell-fill"></i></div>
  <div>
    <strong><?= $butuhAksi ?> pesanan butuh perhatian Anda!</strong>
    <?php if ($stats['pesanan_baru']): ?>
      <span class="ms-2"><?= $stats['pesanan_baru'] ?> pesanan pending belum dibayar</span>
    <?php endif; ?>
  </div>
  <a href="<?= BASE_URL ?>/admin/pesanan.php?status=pending"
     class="btn btn-sm btn-warning ms-auto fw-bold">
    <i class="bi bi-arrow-right me-1"></i>Tangani Sekarang
  </a>
</div>
<?php endif; ?>

<!-- ── Row 1: Stat Cards Utama ─────────────────────────────── -->
<div class="row g-3 mb-3">
  <div class="col-xl-3 col-sm-6">
    <a href="<?= BASE_URL ?>/admin/pesanan.php?status=pending" class="stat-card stat-warning text-decoration-none">
      <div class="stat-icon"><i class="bi bi-clock-history"></i></div>
      <div class="stat-info">
        <div class="stat-num"><?= $stats['pesanan_baru'] ?></div>
        <div class="stat-label">Pesanan Pending</div>
      </div>
      <?php if ($stats['pesanan_baru'] > 0): ?>
        <div class="stat-alert-dot"></div>
      <?php endif; ?>
    </a>
  </div>
  <div class="col-xl-3 col-sm-6">
    <a href="<?= BASE_URL ?>/admin/pesanan.php?status=diverifikasi" class="stat-card stat-info text-decoration-none">
      <div class="stat-icon"><i class="bi bi-patch-check-fill"></i></div>
      <div class="stat-info">
        <div class="stat-num"><?= $stats['diproses'] ?></div>
        <div class="stat-label">Dibayar / Diproses</div>
      </div>
    </a>
  </div>
  <div class="col-xl-3 col-sm-6">
    <a href="<?= BASE_URL ?>/admin/pesanan.php?status=diproses" class="stat-card stat-primary text-decoration-none">
      <div class="stat-icon"><i class="bi bi-gear-fill"></i></div>
      <div class="stat-info">
        <div class="stat-num"><?= $stats['diproses'] ?></div>
        <div class="stat-label">Sedang Diproses</div>
      </div>
    </a>
  </div>
  <div class="col-xl-3 col-sm-6">
    <a href="<?= BASE_URL ?>/admin/pesanan.php?status=selesai" class="stat-card stat-success text-decoration-none">
      <div class="stat-icon"><i class="bi bi-check2-circle"></i></div>
      <div class="stat-info">
        <div class="stat-num"><?= $stats['selesai_bulan'] ?></div>
        <div class="stat-label">Selesai Bulan Ini</div>
      </div>
    </a>
  </div>
</div>

<!-- ── Row 2: Stat Cards Sekunder ──────────────────────────── -->
<div class="row g-3 mb-4">
  <div class="col-xl-4 col-sm-6">
    <a href="<?= BASE_URL ?>/admin/produk.php" class="stat-card stat-dark text-decoration-none">
      <div class="stat-icon"><i class="bi bi-box-seam"></i></div>
      <div class="stat-info">
        <div class="stat-num"><?= $stats['total_produk'] ?></div>
        <div class="stat-label">Produk Aktif</div>
      </div>
    </a>
  </div>
  <div class="col-xl-4 col-sm-6">
    <a href="<?= BASE_URL ?>/admin/produk.php?aktif=1&q=" class="stat-card stat-danger text-decoration-none">
      <div class="stat-icon"><i class="bi bi-exclamation-triangle-fill"></i></div>
      <div class="stat-info">
        <div class="stat-num"><?= $stats['stok_rendah'] ?></div>
        <div class="stat-label">Stok Perlu Diisi</div>
      </div>
      <?php if ($stats['stok_rendah'] > 0): ?>
        <div class="stat-alert-dot"></div>
      <?php endif; ?>
    </a>
  </div>
  <div class="col-xl-4 col-sm-12">
    <div class="stat-card stat-success" style="cursor:default">
      <div class="stat-icon"><i class="bi bi-wallet2"></i></div>
      <div class="stat-info">
        <div class="stat-num" style="font-size:1.25rem;line-height:1.3"><?= formatRupiah($stats['pendapatan_bln']) ?></div>
        <div class="stat-label">Pendapatan Bulan Ini</div>
      </div>
    </div>
  </div>
</div>

<!-- ── Row 3: Chart + Quick Actions ────────────────────────── -->
<div class="row g-4 mb-4">

  <!-- Chart pesanan 7 hari -->
  <div class="col-lg-8">
    <div class="admin-card h-100">
      <div class="admin-card-header">
        <h6 class="mb-0"><i class="bi bi-bar-chart-fill me-2 text-primary"></i>Pesanan 7 Hari Terakhir</h6>
        <span class="badge bg-primary-subtle text-primary border border-primary-subtle">
          Total: <?= array_sum($chartData) ?>
        </span>
      </div>
      <div class="p-4" style="height:220px">
        <canvas id="chartPesanan"></canvas>
      </div>
    </div>
  </div>

  <!-- Quick Actions -->
  <div class="col-lg-4">
    <div class="admin-card h-100">
      <div class="admin-card-header">
        <h6 class="mb-0"><i class="bi bi-lightning-fill me-2 text-warning"></i>Aksi Cepat</h6>
      </div>
      <div class="p-3 d-grid gap-2">
        <a href="<?= BASE_URL ?>/admin/produk_tambah.php" class="btn btn-primary-brand">
          <i class="bi bi-plus-circle me-2"></i>Tambah Produk Baru
        </a>
        <a href="<?= BASE_URL ?>/admin/pesanan.php?status=diverifikasi" class="btn btn-outline-success">
          <i class="bi bi-patch-check me-2"></i>Pesanan Dibayar
          <?php if ($stats['diproses'] > 0): ?>
            <span class="badge bg-success ms-1"><?= $stats['diproses'] ?></span>
          <?php endif; ?>
        </a>
        <a href="<?= BASE_URL ?>/admin/pesanan.php?status=pending" class="btn btn-outline-warning">
          <i class="bi bi-clock-history me-2"></i>Pesanan Pending
          <?php if ($stats['pesanan_baru'] > 0): ?>
            <span class="badge bg-warning text-dark ms-1"><?= $stats['pesanan_baru'] ?></span>
          <?php endif; ?>
        </a>
        <a href="<?= BASE_URL ?>/admin/galeri.php" class="btn btn-outline-secondary">
          <i class="bi bi-images me-2"></i>Kelola Galeri
        </a>
        <a href="<?= BASE_URL ?>" target="_blank" class="btn btn-outline-secondary">
          <i class="bi bi-globe me-2"></i>Lihat Toko
        </a>
      </div>
    </div>
  </div>
</div>

<!-- ── Row 4: Pesanan Terbaru + Stok Rendah ────────────────── -->
<div class="row g-4">

  <!-- Pesanan Terbaru -->
  <div class="col-lg-8">
    <div class="admin-card">
      <div class="admin-card-header">
        <h6 class="mb-0"><i class="bi bi-receipt me-2"></i>10 Pesanan Terbaru</h6>
        <a href="<?= BASE_URL ?>/admin/pesanan.php" class="btn btn-sm btn-outline-primary">
          Lihat Semua <i class="bi bi-arrow-right ms-1"></i>
        </a>
      </div>
      <div class="table-responsive">
        <table class="table table-hover admin-table mb-0">
          <thead>
            <tr>
              <th>Kode</th>
              <th>Pembeli</th>
              <th>Total</th>
              <th>Waktu</th>
              <th>Status</th>
              <th class="text-center">Aksi</th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($pesananBaru)): ?>
              <tr><td colspan="6" class="text-center py-4 text-muted">Belum ada pesanan.</td></tr>
            <?php endif; ?>
            <?php foreach ($pesananBaru as $p):
              $urgent = in_array($p['status'], ['pending','dibayar']);
            ?>
              <tr class="<?= $urgent ? 'adm-row--urgent' : '' ?>">
                <td>
                  <a href="<?= BASE_URL ?>/admin/pesanan_detail.php?id=<?= $p['id'] ?>"
                     class="adm-kode-link">
                    <code class="small"><?= e($p['kode_pesanan']) ?></code>
                  </a>
                </td>
                <td>
                  <div class="fw-semibold small"><?= e($p['nama_pembeli']) ?></div>
                </td>
                <td class="fw-bold small"><?= formatRupiah($p['total_harga']) ?></td>
                <td class="small text-muted"><?= date('d/m H:i', strtotime($p['created_at'])) ?></td>
                <td><?= statusBadge($p['status']) ?></td>
                <td class="text-center">
                  <div class="d-flex gap-1 justify-content-center">
                    <a href="<?= BASE_URL ?>/admin/pesanan_detail.php?id=<?= $p['id'] ?>"
                       class="btn btn-xs btn-primary" title="Detail">
                      <i class="bi bi-eye"></i>
                    </a>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- Stok Rendah -->
  <div class="col-lg-4">
    <div class="admin-card">
      <div class="admin-card-header">
        <h6 class="mb-0 text-danger">
          <i class="bi bi-exclamation-triangle me-2"></i>Stok Rendah
        </h6>
        <a href="<?= BASE_URL ?>/admin/produk.php" class="btn btn-sm btn-outline-danger">Kelola</a>
      </div>
      <?php if (empty($stokRendah)): ?>
        <div class="p-4 text-center">
          <i class="bi bi-check-circle-fill text-success fs-3 d-block mb-2"></i>
          <p class="text-muted small mb-0">Semua stok dalam kondisi aman.</p>
        </div>
      <?php else: ?>
        <?php foreach ($stokRendah as $pr):
          $pct = $pr['stok_minimum'] > 0 ? ($pr['stok'] / $pr['stok_minimum']) * 100 : 0;
          $warna = $pr['stok'] <= 0 ? 'danger' : ($pct < 50 ? 'danger' : 'warning');
        ?>
          <div class="adm-stok-item">
            <div class="d-flex justify-content-between align-items-start mb-1">
              <div class="adm-stok-nama"><?= e($pr['nama']) ?></div>
              <span class="badge bg-<?= $warna ?>-subtle text-<?= $warna ?> border border-<?= $warna ?>-subtle ms-2 flex-shrink-0" style="font-size:.65rem">
                <?= $pr['stok'] <= 0 ? 'HABIS' : number_format($pr['stok'],1).' '.$pr['satuan'] ?>
              </span>
            </div>
            <div class="adm-stok-kat"><?= e($pr['nama_kategori']) ?></div>
            <div class="progress mt-1" style="height:4px">
              <div class="progress-bar bg-<?= $warna ?>"
                   style="width:<?= min(100,max(0,$pct)) ?>%"></div>
            </div>
            <div class="d-flex justify-content-between mt-1">
              <span class="text-muted" style="font-size:.68rem">Sisa: <?= number_format($pr['stok'],1) ?></span>
              <a href="<?= BASE_URL ?>/admin/produk_edit.php?id=<?= $pr['id'] ?>"
                 class="text-primary text-decoration-none" style="font-size:.68rem;font-weight:700">
                Edit Stok →
              </a>
            </div>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </div>

    <!-- Ringkasan Status Bulan Ini -->
    <div class="admin-card mt-4">
      <div class="admin-card-header">
        <h6 class="mb-0"><i class="bi bi-pie-chart me-2"></i>Status Bulan Ini</h6>
      </div>
      <div class="p-3">
        <?php
        $statusMap = [
            'pending'      => ['label'=>'Pending',       'color'=>'warning'],
            'diverifikasi' => ['label'=>'Dibayar',        'color'=>'primary'],
            'diproses'     => ['label'=>'Diproses',       'color'=>'secondary'],
            'selesai'      => ['label'=>'Selesai',         'color'=>'success'],
            'dibatalkan'   => ['label'=>'Dibatalkan',      'color'=>'danger'],
        ];
        $totalBulan = array_sum($statusBulan) ?: 1;
        foreach ($statusMap as $s => $info):
            $jml = (int)($statusBulan[$s] ?? 0);
            if ($jml === 0) continue;
            $pct = round($jml / $totalBulan * 100);
        ?>
          <div class="mb-2">
            <div class="d-flex justify-content-between small mb-1">
              <span class="fw-semibold"><?= $info['label'] ?></span>
              <span class="text-muted"><?= $jml ?> (<?= $pct ?>%)</span>
            </div>
            <div class="progress" style="height:6px">
              <div class="progress-bar bg-<?= $info['color'] ?>" style="width:<?= $pct ?>%"></div>
            </div>
          </div>
        <?php endforeach; ?>
        <?php if (empty($statusBulan)): ?>
          <p class="text-muted small text-center mb-0">Belum ada pesanan bulan ini.</p>
        <?php endif; ?>
      </div>
    </div>
  </div>

</div><!-- /row -->

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.3/dist/chart.umd.min.js"></script>
<script>
(function(){
  const ctx = document.getElementById('chartPesanan');
  if (!ctx) return;
  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: <?= json_encode($chartLabels) ?>,
      datasets: [{
        label: 'Jumlah Pesanan',
        data: <?= json_encode($chartData) ?>,
        backgroundColor: 'rgba(139,94,60,.2)',
        borderColor: '#8B5E3C',
        borderWidth: 2,
        borderRadius: 6,
        borderSkipped: false,
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: { display: false },
        tooltip: {
          callbacks: {
            label: ctx => ' ' + ctx.parsed.y + ' pesanan'
          }
        }
      },
      scales: {
        y: {
          beginAtZero: true,
          ticks: { stepSize: 1, font: { family: 'Nunito', size: 11 } },
          grid: { color: 'rgba(0,0,0,.05)' }
        },
        x: {
          ticks: { font: { family: 'Nunito', size: 11 } },
          grid: { display: false }
        }
      }
    }
  });
})();
</script>

<?php include __DIR__ . '/admin_footer.php'; ?>
