<?php
// admin/laporan.php
require_once '../includes/config.php';
require_once '../includes/auth.php';
requireAdmin();

$dari     = $_GET['dari']    ?? date('Y-m-d');
$sampai   = $_GET['sampai']  ?? date('Y-m-d');
$kasirId  = (int)($_GET['kasir_id'] ?? 0);

// Daftar kasir untuk dropdown
$kasirList = $pdo->query("SELECT id, nama FROM akun WHERE role IN ('kasir','admin') AND aktif=1 ORDER BY nama")->fetchAll();

// Bangun kondisi WHERE dinamis
$where  = "DATE(t.tanggal) BETWEEN ? AND ?";
$params = [$dari, $sampai];
if ($kasirId > 0) {
    $where   .= " AND t.kasir_id = ?";
    $params[] = $kasirId;
}

// Total periode
$stmt = $pdo->prepare("SELECT COUNT(*) AS jml, COALESCE(SUM(total),0) AS omzet, COALESCE(SUM(kembalian),0) AS kembalian FROM transaksi t WHERE $where");
$stmt->execute($params);
$ringkasan = $stmt->fetch();

// Per kasir
$stmt = $pdo->prepare("SELECT a.nama, COUNT(t.id) AS jml, SUM(t.total) AS omzet FROM transaksi t JOIN akun a ON t.kasir_id=a.id WHERE $where GROUP BY a.id ORDER BY omzet DESC");
$stmt->execute($params);
$perKasir = $stmt->fetchAll();

// Barang terlaris
$stmt = $pdo->prepare("SELECT dt.nama_barang, SUM(dt.qty) AS total_qty, SUM(dt.subtotal) AS total_omzet FROM detail_transaksi dt JOIN transaksi t ON dt.transaksi_id=t.id WHERE $where GROUP BY dt.nama_barang ORDER BY total_qty DESC LIMIT 10");
$stmt->execute($params);
$terlaris = $stmt->fetchAll();

// Daftar transaksi
$stmt = $pdo->prepare("SELECT t.*, a.nama AS kasir_nama FROM transaksi t JOIN akun a ON t.kasir_id=a.id WHERE $where ORDER BY t.tanggal DESC");
$stmt->execute($params);
$transaksiList = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <title>Laporan — <?= NAMA_TOKO ?></title>
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="<?= BASE_URL ?>css/style.css?v=<?= time() ?>">
</head>
<body>
<div class="layout">
  <?php include '../includes/sidebar.php'; ?>

  <div class="main-content">
    <div class="topbar">
      <button class="hamburger" id="hamburgerBtn" aria-label="Menu">☰</button>
      <div class="topbar-title">📋 Laporan Penjualan</div>
      <button class="topbar-btn secondary" onclick="window.print()">🖨️ Cetak</button>
    </div>

    <div class="page-body">

      <!-- Filter Tanggal -->
      <div class="card" style="margin-bottom:20px">
        <div class="card-body" style="padding:14px 20px">
          <form method="GET" class="filter-form" style="display:flex;gap:12px;align-items:flex-end;flex-wrap:wrap">
            <div class="form-group" style="margin:0">
              <label style="display:block;margin-bottom:4px;font-size:12px;color:var(--muted);font-weight:700">DARI</label>
              <input type="date" name="dari" class="form-control" value="<?= $dari ?>" style="width:auto">
            </div>
            <div class="form-group" style="margin:0">
              <label style="display:block;margin-bottom:4px;font-size:12px;color:var(--muted);font-weight:700">SAMPAI</label>
              <input type="date" name="sampai" class="form-control" value="<?= $sampai ?>" style="width:auto">
            </div>
            <div class="form-group" style="margin:0">
              <label style="display:block;margin-bottom:4px;font-size:12px;color:var(--muted);font-weight:700">KASIR</label>
              <select name="kasir_id" class="form-control" style="width:auto">
                <option value="0">Semua Kasir</option>
                <?php foreach ($kasirList as $k): ?>
                <option value="<?= $k['id'] ?>" <?= $kasirId == $k['id'] ? 'selected' : '' ?>>
                  <?= htmlspecialchars($k['nama']) ?>
                </option>
                <?php endforeach; ?>
              </select>
            </div>
            <button type="submit" class="btn btn-primary">Tampilkan</button>
          </form>
        </div>
      </div>

      <!-- Ringkasan -->
      <div class="stat-grid" style="margin-bottom:20px">
        <div class="stat-card sc-blue">
          <div class="sc-label">Total Omzet</div>
          <div class="sc-val"><?= formatRp((float)$ringkasan['omzet']) ?></div>
          <div class="sc-sub">
            <?= $dari ?> s/d <?= $sampai ?>
            <?php if ($kasirId > 0): ?>
              <?php $kNama = array_column($kasirList,'nama','id')[$kasirId] ?? ''; ?>
              <br><strong><?= htmlspecialchars($kNama) ?></strong>
            <?php endif; ?>
          </div>
        </div>
        <div class="stat-card sc-green">
          <div class="sc-label">Jumlah Transaksi</div>
          <div class="sc-val"><?= $ringkasan['jml'] ?></div>
          <div class="sc-sub">transaksi berhasil</div>
        </div>
        <div class="stat-card sc-amber">
          <div class="sc-label">Rata-rata Transaksi</div>
          <div class="sc-val"><?= $ringkasan['jml'] > 0 ? formatRp($ringkasan['omzet'] / $ringkasan['jml']) : 'Rp 0' ?></div>
          <div class="sc-sub">per transaksi</div>
        </div>
      </div>

      <div class="laporan-grid-2" style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px">
        <!-- Per Kasir -->
        <div class="card">
          <div class="card-header"><h3>👥 Omzet per Kasir</h3></div>
          <div class="table-wrap">
            <table>
              <thead><tr><th>Kasir</th><th>Transaksi</th><th>Omzet</th></tr></thead>
              <tbody>
                <?php foreach ($perKasir as $pk): ?>
                <tr>
                  <td><strong><?= htmlspecialchars($pk['nama']) ?></strong></td>
                  <td><?= $pk['jml'] ?></td>
                  <td><?= formatRp((float)$pk['omzet']) ?></td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($perKasir)): ?><tr><td colspan="3" style="text-align:center;color:var(--muted);padding:20px">Tidak ada data</td></tr><?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>

        <!-- Terlaris -->
        <div class="card">
          <div class="card-header"><h3>🏆 Barang Terlaris</h3></div>
          <div class="table-wrap">
            <table>
              <thead><tr><th>Barang</th><th>Qty</th><th>Omzet</th></tr></thead>
              <tbody>
                <?php foreach ($terlaris as $t): ?>
                <tr>
                  <td><?= htmlspecialchars($t['nama_barang']) ?></td>
                  <td><span class="badge badge-blue"><?= $t['total_qty'] ?></span></td>
                  <td><?= formatRp((float)$t['total_omzet']) ?></td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($terlaris)): ?><tr><td colspan="3" style="text-align:center;color:var(--muted);padding:20px">Tidak ada data</td></tr><?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- Semua Transaksi -->
      <div class="card">
        <div class="card-header"><h3>📄 Detail Transaksi (<?= count($transaksiList) ?>)</h3></div>
        <div class="table-wrap">
          <table>
            <thead><tr><th>No Transaksi</th><th>Kasir</th><th>Total</th><th class="hide-mobile">Bayar</th><th class="hide-mobile">Kembalian</th><th>Metode</th><th>Waktu</th><th>Aksi</th></tr></thead>
            <tbody>
              <?php foreach ($transaksiList as $t): ?>
              <tr>
                <td><strong><?= htmlspecialchars($t['no_transaksi']) ?></strong></td>
                <td><?= htmlspecialchars($t['kasir_nama']) ?></td>
                <td><?= formatRp((float)$t['total']) ?></td>
                <td class="hide-mobile"><?= formatRp((float)$t['bayar']) ?></td>
                <td class="hide-mobile"><?= formatRp((float)$t['kembalian']) ?></td>
                <td><span class="badge badge-blue"><?= ucfirst($t['metode']) ?></span></td>
                <td style="font-size:12px;color:var(--muted)"><?= date('d/m/Y H:i', strtotime($t['tanggal'])) ?></td>
                <td><a href="detail_transaksi.php?id=<?= $t['id'] ?>" class="btn btn-ghost btn-sm">Detail</a></td>
              </tr>
              <?php endforeach; ?>
              <?php if (empty($transaksiList)): ?><tr><td colspan="8" style="text-align:center;color:var(--muted);padding:30px">Tidak ada transaksi</td></tr><?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>

    </div>
  </div>
</div>
<script src="<?= BASE_URL ?>js/app.js"></script>
</body>
</html>
