<?php
// ============================================================
// FILE: admin/produk.php — Daftar & Kelola Produk
// ============================================================
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();

// Toggle aktif
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_aktif'])) {
    $id  = (int)$_POST['toggle_aktif'];
    $cur = (int)$pdo->prepare("SELECT is_aktif FROM produk WHERE id=?")->execute([$id]);
    $r   = $pdo->prepare("SELECT is_aktif FROM produk WHERE id=?"); $r->execute([$id]);
    $cur = (int)$r->fetchColumn();
    $pdo->prepare("UPDATE produk SET is_aktif=? WHERE id=?")->execute([!$cur, $id]);
    redirect(BASE_URL . '/admin/produk.php?' . http_build_query($_GET));
}

$q      = trim($_GET['q'] ?? '');
$katId  = (int)($_GET['kategori_id'] ?? 0);
$aktif  = $_GET['aktif'] ?? '';
$page   = max(1,(int)($_GET['page']??1));
$perPage= 20;
$offset = ($page-1)*$perPage;

$where  = ['1=1'];
$params = [];
if ($q)     { $where[] = 'p.nama LIKE ?'; $params[] = "%$q%"; }
if ($katId) { $where[] = 'p.kategori_id = ?'; $params[] = $katId; }
if ($aktif !== '') { $where[] = 'p.is_aktif = ?'; $params[] = (int)$aktif; }
$ws = implode(' AND ', $where);

$total = (int)$pdo->prepare("SELECT COUNT(*) FROM produk p WHERE $ws")->execute($params) ?: 0;
$sc = $pdo->prepare("SELECT COUNT(*) FROM produk p WHERE $ws"); $sc->execute($params);
$total = (int)$sc->fetchColumn();
$totalPage = (int)ceil($total/$perPage);

$stmt = $pdo->prepare("
    SELECT p.*, k.nama AS nama_kategori,
           COUNT(pf.id) AS jml_foto,
           (SELECT pf2.nama_file FROM produk_foto pf2
            WHERE pf2.produk_id=p.id ORDER BY pf2.urutan ASC LIMIT 1) AS foto_utama
    FROM produk p
    JOIN kategori k ON p.kategori_id=k.id
    LEFT JOIN produk_foto pf ON pf.produk_id=p.id
    WHERE $ws
    GROUP BY p.id
    ORDER BY p.created_at DESC
    LIMIT $perPage OFFSET $offset
");
$stmt->execute($params);
$produkList = $stmt->fetchAll();

$kategoriList = $pdo->query("SELECT * FROM kategori ORDER BY nama")->fetchAll();
$pageTitle    = 'Manajemen Produk';
include __DIR__ . '/admin_layout.php';
?>

<div class="adm-page-header mb-4">
  <div>
    <h4 class="adm-page-title"><i class="bi bi-box-seam me-2"></i>Manajemen Produk</h4>
    <p class="adm-page-sub mb-0"><?= $total ?> produk ditemukan</p>
  </div>
  <a href="<?= BASE_URL ?>/admin/produk_tambah.php" class="btn btn-primary-brand">
    <i class="bi bi-plus-lg me-2"></i>Tambah Produk
  </a>
</div>

<!-- Filter bar -->
<div class="admin-card mb-4">
  <form class="adm-filter-bar" method="GET">
    <div class="adm-filter-group">
      <div class="adm-search-wrap" style="flex:1.5">
        <i class="bi bi-search adm-search-icon"></i>
        <input type="text" name="q" class="adm-search-input"
               placeholder="Cari nama produk…" value="<?= e($q) ?>">
      </div>
      <select name="kategori_id" class="form-select form-select-sm" style="max-width:180px">
        <option value="">Semua Kategori</option>
        <?php foreach ($kategoriList as $k): ?>
          <option value="<?= $k['id'] ?>" <?= $katId===$k['id']?'selected':'' ?>><?= e($k['nama']) ?></option>
        <?php endforeach; ?>
      </select>
      <select name="aktif" class="form-select form-select-sm" style="max-width:140px">
        <option value="">Semua Status</option>
        <option value="1" <?= $aktif==='1'?'selected':'' ?>>Aktif</option>
        <option value="0" <?= $aktif==='0'?'selected':'' ?>>Nonaktif</option>
      </select>
      <button type="submit" class="btn btn-sm btn-primary">
        <i class="bi bi-funnel me-1"></i>Filter
      </button>
      <?php if ($q||$katId||$aktif!==''): ?>
        <a href="<?= BASE_URL ?>/admin/produk.php" class="btn btn-sm btn-outline-secondary">Reset</a>
      <?php endif; ?>
    </div>
  </form>
</div>

<div class="admin-card">
  <div class="table-responsive">
    <table class="table table-hover admin-table mb-0">
      <thead>
        <tr>
          <th width="60">Foto</th>
          <th>Produk</th>
          <th>Kategori</th>
          <th>Harga</th>
          <th>Stok</th>
          <th class="text-center">Foto</th>
          <th class="text-center">Aktif</th>
          <th class="text-center" width="110">Aksi</th>
        </tr>
      </thead>
      <tbody>
        <?php if (empty($produkList)): ?>
          <tr>
            <td colspan="8" class="text-center py-5">
              <i class="bi bi-box fs-2 text-muted d-block mb-2"></i>
              <span class="text-muted">Belum ada produk.</span>
              <div class="mt-2">
                <a href="<?= BASE_URL ?>/admin/produk_tambah.php" class="btn btn-sm btn-primary">
                  <i class="bi bi-plus-lg me-1"></i>Tambah Pertama
                </a>
              </div>
            </td>
          </tr>
        <?php endif; ?>
        <?php foreach ($produkList as $p):
          $kritis = (float)$p['stok'] <= (float)$p['stok_minimum'];
          $src = $p['foto_utama']
            ? UPLOAD_URL.'/produk/'.e($p['foto_utama'])
            : 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=60&q=60';
        ?>
          <tr class="<?= !$p['is_aktif']?'adm-row--inactive':'' ?>">
            <td>
              <a href="<?= BASE_URL ?>/produk.php?slug=<?= e($p['slug']) ?>" target="_blank">
                <img src="<?= $src ?>" class="admin-thumb" alt="<?= e($p['nama']) ?>"
                     loading="lazy">
              </a>
            </td>
            <td>
              <div class="fw-semibold"><?= e($p['nama']) ?></div>
              <div class="font-monospace text-muted" style="font-size:.72rem"><?= e($p['slug']) ?></div>
            </td>
            <td>
              <span class="adm-kat-badge"><?= e($p['nama_kategori']) ?></span>
            </td>
            <td>
              <div class="fw-bold"><?= formatRupiah($p['harga']) ?></div>
              <small class="text-muted">/ <?= e($p['satuan']) ?></small>
            </td>
            <td>
              <span class="<?= $kritis?'text-danger fw-bold':'' ?>">
                <?= number_format($p['stok'],2) ?> <?= e($p['satuan']) ?>
              </span>
              <?php if ($kritis): ?>
                <div>
                  <span class="badge bg-danger-subtle text-danger border border-danger-subtle"
                        style="font-size:.65rem">
                    <i class="bi bi-exclamation-triangle me-1"></i>Rendah
                  </span>
                </div>
              <?php endif; ?>
            </td>
            <td class="text-center">
              <span class="badge bg-secondary-subtle text-secondary border">
                <?= $p['jml_foto'] ?> foto
              </span>
            </td>
            <td class="text-center">
              <form method="POST">
                <input type="hidden" name="toggle_aktif" value="<?= $p['id'] ?>">
                <button class="btn btn-xs <?= $p['is_aktif']?'btn-success':'btn-secondary' ?>"
                        title="<?= $p['is_aktif']?'Klik untuk nonaktifkan':'Klik untuk aktifkan' ?>">
                  <i class="bi <?= $p['is_aktif']?'bi-toggle-on':'bi-toggle-off' ?>"></i>
                </button>
              </form>
            </td>
            <td class="text-center">
              <div class="d-flex gap-1 justify-content-center">
                <a href="<?= BASE_URL ?>/admin/produk_edit.php?id=<?= $p['id'] ?>"
                   class="btn btn-xs btn-outline-warning" title="Edit">
                  <i class="bi bi-pencil"></i>
                </a>
                <a href="<?= BASE_URL ?>/produk.php?slug=<?= e($p['slug']) ?>"
                   target="_blank" class="btn btn-xs btn-outline-info" title="Lihat Toko">
                  <i class="bi bi-eye"></i>
                </a>
                <form method="POST" action="<?= BASE_URL ?>/admin/produk_hapus.php">
                  <input type="hidden" name="hapus_id" value="<?= $p['id'] ?>">
                  <button class="btn btn-xs btn-outline-danger"
                          onclick="return confirm('Hapus produk «<?= e(addslashes($p['nama'])) ?>»?\nSemua foto produk juga akan dihapus.')"
                          title="Hapus">
                    <i class="bi bi-trash3"></i>
                  </button>
                </form>
              </div>
            </td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <!-- Pagination -->
  <?php if ($totalPage > 1): ?>
    <div class="d-flex justify-content-between align-items-center px-4 py-3 border-top">
      <small class="text-muted">
        <?= ($offset+1) ?>–<?= min($offset+$perPage,$total) ?> dari <?= $total ?>
      </small>
      <nav>
        <ul class="pagination pagination-sm mb-0">
          <?php for ($i=1;$i<=$totalPage;$i++): ?>
            <li class="page-item <?= $i===$page?'active':'' ?>">
              <a class="page-link" href="?<?= http_build_query(array_merge($_GET,['page'=>$i])) ?>"><?= $i ?></a>
            </li>
          <?php endfor; ?>
        </ul>
      </nav>
    </div>
  <?php endif; ?>
</div>

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