<?php include 'comp/header.php'; ?>

<!-- Content Wrapper -->
<div class="content-wrapper">

  <!-- Page Header -->
  <div class="content-header">
    <div class="container-fluid">
      <div class="page-header">
        <div>
          <h1>Dashboard</h1>
          <ul class="page-breadcrumb">
            <li><a href="index.php">Home</a></li>
            <li><span class="sep">&rsaquo;</span></li>
            <li>Dashboard</li>
          </ul>
        </div>
        <div style="font-size:0.78rem;color:var(--text-muted);">
          <i class="fas fa-calendar-alt" style="margin-right:4px;"></i>
          <?php echo date('d F Y'); ?>
        </div>
      </div>
    </div>
  </div>

  <section class="content">
    <div class="container-fluid">

      <!-- STAT CARDS ROW -->
      <div class="row" style="margin-bottom:24px;">

        <div class="col-lg-3 col-md-6 col-sm-6 col-12" style="margin-bottom:16px;">
          <a href="index.php?m=admin" style="text-decoration:none;">
            <div class="stat-card">
              <div style="min-width:0;flex:1;container-type:inline-size;">
                <span class="stat-card-label">Jumlah Pengguna</span>
                <div class="stat-card-value"><?= select_user_2(); ?></div>
              </div>
              <div class="stat-card-icon stat-icon-green">
                <i class="fas fa-users"></i>
              </div>
            </div>
          </a>
        </div>

        <div class="col-lg-3 col-md-6 col-sm-6 col-12" style="margin-bottom:16px;">
          <a href="index.php?m=barang&s=title" style="text-decoration:none;">
            <div class="stat-card">
              <div style="min-width:0;flex:1;container-type:inline-size;">
                <span class="stat-card-label">Jumlah Barang</span>
                <div class="stat-card-value"><?= select_barang(); ?></div>
              </div>
              <div class="stat-card-icon stat-icon-blue">
                <i class="fas fa-box-open"></i>
              </div>
            </div>
          </a>
        </div>

        <div class="col-lg-3 col-md-6 col-sm-6 col-12" style="margin-bottom:16px;">
          <a href="index.php?m=laporan" style="text-decoration:none;">
            <div class="stat-card">
              <div style="min-width:0;flex:1;container-type:inline-size;">
                <span class="stat-card-label">Total Pendapatan</span>
                <div class="stat-card-value<?php 
                    ob_start(); 
                    jumlah_saldo(); 
                    $saldo_str = ob_get_clean(); 
                    $saldo_num = (int)filter_var($saldo_str, FILTER_SANITIZE_NUMBER_INT);
                    echo $saldo_num > 30000 ? ' stat-compact' : '';
                  ?>">
                  <?= str_replace(" ", "&nbsp;", $saldo_str); ?>
                </div>
              </div>
              <div class="stat-card-icon stat-icon-yellow">
                <i class="fas fa-coins"></i>
              </div>
            </div>
          </a>
        </div>

        <div class="col-lg-3 col-md-6 col-sm-6 col-12" style="margin-bottom:16px;">
          <a href="index.php?m=laporan" style="text-decoration:none;">
            <div class="stat-card">
              <div style="min-width:0;flex:1;container-type:inline-size;">
                <span class="stat-card-label">Barang Terjual</span>
                <div class="stat-card-value"><?= jumlah_terjual(); ?></div>
              </div>
              <div class="stat-card-icon stat-icon-red">
                <i class="fas fa-shopping-bag"></i>
              </div>
            </div>
          </a>
        </div>

      </div>

      <!-- MIDDLE ROW: Chart + Info Panels -->
      <div class="row" style="margin-bottom:20px;">

        <!-- LEFT: Revenue Chart -->
        <div class="col-lg-8" style="margin-bottom:20px;">
          <div class="pm-card" style="height:100%; display:flex; flex-direction:column;">
            <div class="pm-card-header" style="flex-wrap:wrap;gap:8px; flex-shrink:0;">
              <span class="pm-card-title">
                <i class="fas fa-chart-line" style="margin-right:8px;color:var(--primary);"></i>
                Pendapatan
              </span>
              <div style="display:flex;gap:6px;flex-wrap:wrap;">
                <a href="?range=7" class="btn btn-sm <?= (!isset($_GET['range']) || $_GET['range']=='7') ? 'btn-primary' : 'btn-light' ?>" style="border-radius:20px;font-weight:600;">7 Hari</a>
                <a href="?range=14" class="btn btn-sm <?= (isset($_GET['range']) && $_GET['range']=='14') ? 'btn-primary' : 'btn-light' ?>" style="border-radius:20px;font-weight:600;">14 Hari</a>
                <a href="?range=21" class="btn btn-sm <?= (isset($_GET['range']) && $_GET['range']=='21') ? 'btn-primary' : 'btn-light' ?>" style="border-radius:20px;font-weight:600;">21 Hari</a>
                <a href="?range=30" class="btn btn-sm <?= (isset($_GET['range']) && $_GET['range']=='30') ? 'btn-primary' : 'btn-light' ?>" style="border-radius:20px;font-weight:600;">1 Bulan</a>
              </div>
            </div>
            <div style="padding:16px 16px 0 16px; flex:1; display:flex; flex-direction:column; min-height:260px;">
              <div style="flex:1; position:relative;">
                <canvas id="revenueChart" style="position:absolute; top:0; left:0; width:100%; height:100%;"></canvas>
              </div>
            </div>
          </div>
        </div>

        <!-- RIGHT: Quick Info Panels -->
        <div class="col-lg-4" style="margin-bottom:20px;">

          <!-- Popular Products -->
          <div class="pm-card" style="margin-bottom:16px;">
            <div class="pm-card-header">
              <span class="pm-card-title">
                <i class="fas fa-fire" style="margin-right:8px;color:#E76F51;"></i>
                Barang Terlaris
              </span>
              <a href="index.php?m=barang&s=title" style="font-size:0.78rem;color:var(--primary);font-weight:600;text-decoration:none;">Lihat &rarr;</a>
            </div>
            <div class="pm-card-body" style="padding:14px 22px;">
              <?php
                $q_pop = barang_terpopuler();
                $total_qty_all = total_barang_terjual();
                if ($q_pop && mysqli_num_rows($q_pop) > 0):
                  $pop_colors = ['avatar-bg-green', 'avatar-bg-yellow', 'avatar-bg-gray'];
                  $pi = 0;
                  while ($row_pop = mysqli_fetch_assoc($q_pop)):
                    $pct = $total_qty_all > 0 ? round(($row_pop['total_qty'] / $total_qty_all) * 100) : 0;
                    $inisial = strtoupper(substr($row_pop['nm_barang'], 0, 2));
              ?>
              <div class="list-row">
                <div class="avatar-block <?= $pop_colors[$pi % count($pop_colors)]; ?>" style="border-radius:10px;font-size:0.7rem;"><?= $inisial; ?></div>
                <div class="list-text">
                  <h6 class="list-title"><?= htmlspecialchars($row_pop['nm_barang']); ?></h6>
                  <p class="list-subtitle"><?= $row_pop['total_qty'] . ' terjual &bull; ' . rupiah($row_pop['total_omzet']); ?></p>
                </div>
                <span style="font-size:0.8rem;font-weight:700;color:var(--primary);"><?= $pct; ?>%</span>
              </div>
              <?php
                    $pi++;
                  endwhile;
                else:
              ?>
              <div style="padding:12px 0;text-align:center;color:var(--text-muted);font-size:0.85rem;">
                <i class="fas fa-chart-bar" style="margin-right:6px;"></i> Belum ada data penjualan
              </div>
              <?php endif; ?>
            </div>
          </div>

          <!-- Out of Stock -->
          <div class="pm-card">
            <div class="pm-card-header">
              <span class="pm-card-title">
                <i class="fas fa-exclamation-triangle" style="margin-right:8px;color:#DC2626;"></i>
                Stok Habis
              </span>
              <a href="index.php?m=barang&s=title" style="font-size:0.78rem;color:var(--primary);font-weight:600;text-decoration:none;">Lihat &rarr;</a>
            </div>
            <div class="pm-card-body" style="padding:14px 22px;">
              <?php
                global $koneksi;
                $q_stok = mysqli_query($koneksi, "SELECT * FROM tb_barang WHERE stok <= 0 OR stok IS NULL ORDER BY nm_barang ASC LIMIT 5");
                if (mysqli_num_rows($q_stok) > 0):
                  while ($row_stok = mysqli_fetch_array($q_stok)):
              ?>
              <div class="list-row">
                <div class="list-text">
                  <h6 class="list-title"><?= htmlspecialchars($row_stok['nm_barang']); ?></h6>
                  <p class="list-subtitle">Stok: <?= $row_stok['stok']; ?></p>
                </div>
                <span class="badge badge-habis"><?= $row_stok['stok']; ?></span>
              </div>
              <?php
                  endwhile;
                else:
              ?>
              <div style="padding:12px 0;text-align:center;color:var(--text-muted);font-size:0.85rem;">
                <i class="fas fa-check-circle" style="color:var(--success-text);margin-right:6px;"></i> Semua stok tersedia
              </div>
              <?php endif; ?>
            </div>
          </div>

        </div>

      </div>

      <!-- BOTTOM ROW: Recent Sales (Full Width) -->
      <div class="row">
        <div class="col-12" style="margin-bottom:20px;">
          <div class="pm-card">
            <div class="pm-card-header">
              <span class="pm-card-title">
                <i class="fas fa-receipt" style="margin-right:8px;color:var(--primary);"></i>
                Penjualan Terkini
              </span>
              <a href="index.php?m=laporan&s=title" style="font-size:0.78rem;color:var(--primary);font-weight:600;text-decoration:none;">Lihat Semua &rarr;</a>
            </div>
            <div class="pm-card-body">
              <?php
                $q_recent = penjualan_terkini();
                if ($q_recent && mysqli_num_rows($q_recent) > 0):
                  $avatar_colors = ['avatar-bg-green', 'avatar-bg-yellow', 'avatar-bg-gray'];
                  $i = 0;
                  while ($row = mysqli_fetch_assoc($q_recent)):
                    $inisial = strtoupper(substr($row['nm_barang'], 0, 2));
                    $color = $avatar_colors[$i % count($avatar_colors)];
              ?>
              <div class="list-row">
                <div class="avatar-block <?= $color; ?>"><?= $inisial; ?></div>
                <div class="list-text">
                  <h6 class="list-title"><?= htmlspecialchars($row['nm_barang']); ?></h6>
                  <p class="list-subtitle"><?= $row['jumlah_beli'] . ' item &bull; ' . rupiah($row['total']); ?></p>
                </div>
                <span style="font-size:0.72rem;color:var(--text-muted);white-space:nowrap;"><?= date('d M H:i', strtotime($row['tanggal'] . ' ' . $row['jam'])); ?></span>
              </div>
              <?php
                    $i++;
                  endwhile;
                else:
              ?>
              <div style="padding:12px 0;text-align:center;color:var(--text-muted);font-size:0.85rem;">
                <i class="fas fa-inbox" style="margin-right:6px;"></i> Belum ada penjualan
              </div>
              <?php endif; ?>
            </div>
          </div>
        </div>
      </div>

    </div>
  </section>

</div>

<?php 
// Prepare Data for Chart with dynamic range
$range = isset($_GET['range']) ? (int)$_GET['range'] : 7;
if (!in_array($range, [7,14,21,30])) $range = 7;
$chart_labels = [];
$chart_data = [];
for ($i = $range - 1; $i >= 0; $i--) {
    $date = date('Y-m-d', strtotime("-$i days"));
    $chart_labels[] = date('d M', strtotime($date));
    $q = mysqli_query($koneksi, "SELECT sum(total) as t FROM laporan_penjualan WHERE tanggal = '$date'");
    $r = mysqli_fetch_array($q);
    $chart_data[] = $r['t'] ? (int)$r['t'] : 0;
}
?>

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

<!-- Chart.js v2 via CDN -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
  const ctx = document.getElementById('revenueChart');
  if(ctx) {
    new Chart(ctx, {
      type: 'line',
      data: {
        labels: <?= json_encode($chart_labels) ?>,
        datasets: [{
          label: 'Pendapatan (Rp)',
          data: <?= json_encode($chart_data) ?>,
          borderColor: '#1a3a2a',
          backgroundColor: 'rgba(26, 58, 42, 0.1)',
          borderWidth: 3,
          pointBackgroundColor: '#f5b800',
          pointRadius: 4,
          fill: true,
          lineTension: 0.4
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        layout: {
          padding: { top: 0, right: 0, bottom: 0, left: 0 }
        },
        legend: { display: false },
        tooltips: {
          callbacks: {
            label: function(tooltipItem, data) { 
                return 'Rp ' + Number(tooltipItem.yLabel).toLocaleString('id-ID'); 
            }
          }
        },
        scales: {
          xAxes: [{
            gridLines: { display: false },
            ticks: { padding: 4 }
          }],
          yAxes: [{
            ticks: {
              beginAtZero: true,
              padding: 8,
              callback: function(value) {
                return 'Rp ' + Number(value).toLocaleString('id-ID');
              }
            },
            gridLines: { drawBorder: false }
          }]
        }
      }
    });
  }
});
</script>

