<?php
// ============================================================
// FILE: admin/kategori.php — CRUD Kategori
// ============================================================
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();
$errors = [];
$mode   = 'list';  // list | tambah | edit
$editData = null;

// ── Tambah ────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['aksi'] ?? '') === 'tambah') {
    $nama      = trim($_POST['nama']      ?? '');
    $deskripsi = trim($_POST['deskripsi'] ?? '');
    if (!$nama) $errors[] = 'Nama kategori wajib diisi.';
    if (empty($errors)) {
        $slug = buatSlug($nama);
        $chk  = $pdo->prepare("SELECT COUNT(*) FROM kategori WHERE slug=?");
        $chk->execute([$slug]);
        if ((int)$chk->fetchColumn() > 0) $slug .= '-' . substr(uniqid(), -4);
        $pdo->prepare("INSERT INTO kategori (nama,slug,deskripsi) VALUES (?,?,?)")
            ->execute([$nama, $slug, $deskripsi ?: null]);
        setFlash('success', 'Kategori <strong>' . e($nama) . '</strong> berhasil ditambahkan!');
        redirect(BASE_URL . '/admin/kategori.php');
    }
    $mode = 'tambah';
}

// ── Edit simpan ───────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['aksi'] ?? '') === 'edit') {
    $kid       = (int)($_POST['kid'] ?? 0);
    $nama      = trim($_POST['nama']      ?? '');
    $deskripsi = trim($_POST['deskripsi'] ?? '');
    if (!$nama) $errors[] = 'Nama kategori wajib diisi.';
    if (empty($errors) && $kid) {
        $slug = buatSlug($nama);
        $chk  = $pdo->prepare("SELECT COUNT(*) FROM kategori WHERE slug=? AND id != ?");
        $chk->execute([$slug, $kid]);
        if ((int)$chk->fetchColumn() > 0) $slug .= '-' . substr(uniqid(), -4);
        $pdo->prepare("UPDATE kategori SET nama=?, slug=?, deskripsi=? WHERE id=?")
            ->execute([$nama, $slug, $deskripsi ?: null, $kid]);
        setFlash('success', 'Kategori berhasil diperbarui.');
        redirect(BASE_URL . '/admin/kategori.php');
    }
    $mode = 'edit';
    $editData = ['id'=>$kid, 'nama'=>$nama, 'deskripsi'=>$deskripsi];
}

// ── Hapus ─────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['aksi'] ?? '') === 'hapus') {
    $kid = (int)($_POST['kid'] ?? 0);
    // Cek apakah ada produk terkait
    $cnt = $pdo->prepare("SELECT COUNT(*) FROM produk WHERE kategori_id=?");
    $cnt->execute([$kid]);
    if ((int)$cnt->fetchColumn() > 0) {
        setFlash('danger', 'Kategori tidak bisa dihapus karena masih memiliki produk terkait.');
    } else {
        $pdo->prepare("DELETE FROM kategori WHERE id=?")->execute([$kid]);
        setFlash('success', 'Kategori berhasil dihapus.');
    }
    redirect(BASE_URL . '/admin/kategori.php');
}

// ── Mode edit (GET) ───────────────────────────────────────
if (isset($_GET['edit'])) {
    $kid = (int)$_GET['edit'];
    $s   = $pdo->prepare("SELECT * FROM kategori WHERE id=? LIMIT 1");
    $s->execute([$kid]); $editData = $s->fetch();
    if ($editData) $mode = 'edit';
}
if (isset($_GET['tambah'])) $mode = 'tambah';

// ── List + jumlah produk ──────────────────────────────────
$katList = $pdo->query("
    SELECT k.*, COUNT(p.id) AS jml_produk
    FROM kategori k
    LEFT JOIN produk p ON p.kategori_id=k.id AND p.is_aktif=1
    GROUP BY k.id ORDER BY k.nama ASC
")->fetchAll();

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

<div class="adm-page-header mb-4">
  <div>
    <h4 class="adm-page-title"><i class="bi bi-tag me-2"></i>Manajemen Kategori</h4>
    <p class="adm-page-sub mb-0"><?= count($katList) ?> kategori</p>
  </div>
  <?php if ($mode === 'list'): ?>
    <a href="?tambah=1" class="btn btn-primary-brand btn-sm">
      <i class="bi bi-plus-lg me-1"></i>Tambah Kategori
    </a>
  <?php endif; ?>
</div>

<div class="row g-4">

  <!-- ═══ Daftar Kategori ════════════════════════════════ -->
  <div class="col-lg-<?= ($mode!=='list') ? '7' : '12' ?>">
    <div class="admin-card">
      <div class="admin-card-header">
        <h6 class="mb-0">Semua Kategori</h6>
      </div>
      <div class="table-responsive">
        <table class="table table-hover admin-table mb-0">
          <thead>
            <tr>
              <th>Nama</th>
              <th>Slug</th>
              <th>Deskripsi</th>
              <th class="text-center">Produk Aktif</th>
              <th class="text-center">Aksi</th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($katList)): ?>
              <tr><td colspan="5" class="text-center py-4 text-muted">Belum ada kategori.</td></tr>
            <?php endif; ?>
            <?php foreach ($katList as $k): ?>
              <tr>
                <td class="fw-semibold"><?= e($k['nama']) ?></td>
                <td><code class="small"><?= e($k['slug']) ?></code></td>
                <td class="small text-muted">
                  <?= $k['deskripsi'] ? e(mb_substr($k['deskripsi'],0,60).(mb_strlen($k['deskripsi'])>60?'…':'')) : '—' ?>
                </td>
                <td class="text-center">
                  <span class="badge bg-primary-subtle text-primary border border-primary-subtle">
                    <?= $k['jml_produk'] ?> produk
                  </span>
                </td>
                <td class="text-center">
                  <div class="d-flex gap-1 justify-content-center">
                    <a href="?edit=<?= $k['id'] ?>" class="btn btn-xs btn-outline-warning">
                      <i class="bi bi-pencil"></i>
                    </a>
                    <form method="POST"
                          onsubmit="return confirm('Hapus kategori «<?= e(addslashes($k['nama'])) ?>»?')">
                      <input type="hidden" name="aksi" value="hapus">
                      <input type="hidden" name="kid" value="<?= $k['id'] ?>">
                      <button class="btn btn-xs btn-outline-danger"
                              <?= $k['jml_produk']>0?'disabled title="Ada produk terkait"':'' ?>>
                        <i class="bi bi-trash3"></i>
                      </button>
                    </form>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- ═══ Form Tambah / Edit ══════════════════════════════ -->
  <?php if ($mode !== 'list'): ?>
    <div class="col-lg-5">
      <div class="admin-card">
        <div class="admin-card-header">
          <h6 class="mb-0">
            <i class="bi bi-<?= $mode==='edit'?'pencil':'plus-circle' ?> me-2"></i>
            <?= $mode==='edit' ? 'Edit Kategori' : 'Tambah Kategori' ?>
          </h6>
        </div>
        <div class="p-4">
          <?php if (!empty($errors)): ?>
            <div class="alert alert-danger small mb-3">
              <?php foreach($errors as $e): ?><div><i class="bi bi-exclamation-circle me-1"></i><?= $e ?></div><?php endforeach; ?>
            </div>
          <?php endif; ?>

          <form method="POST">
            <input type="hidden" name="aksi" value="<?= $mode ?>">
            <?php if ($mode==='edit' && $editData): ?>
              <input type="hidden" name="kid" value="<?= $editData['id'] ?>">
            <?php endif; ?>

            <div class="mb-3">
              <label class="ck-label" for="iNamaKat">Nama Kategori <span class="text-danger">*</span></label>
              <input type="text" id="iNamaKat" name="nama" class="form-control ck-input"
                     value="<?= e($editData['nama'] ?? ($_POST['nama'] ?? '')) ?>"
                     placeholder="Misal: Kusen Kayu" required>
            </div>
            <div class="mb-4">
              <label class="ck-label" for="iDeskKat">Deskripsi <span class="text-muted small">(opsional)</span></label>
              <textarea id="iDeskKat" name="deskripsi" class="form-control ck-input" rows="3"
                        placeholder="Deskripsi singkat kategori…"><?= e($editData['deskripsi'] ?? ($_POST['deskripsi'] ?? '')) ?></textarea>
            </div>
            <div class="d-flex gap-2">
              <button type="submit" class="btn btn-primary-brand flex-grow-1">
                <i class="bi bi-check-lg me-1"></i>
                <?= $mode==='edit' ? 'Simpan Perubahan' : 'Tambah Kategori' ?>
              </button>
              <a href="<?= BASE_URL ?>/admin/kategori.php" class="btn btn-outline-secondary">
                Batal
              </a>
            </div>
          </form>
        </div>
      </div>
    </div>
  <?php endif; ?>

</div>

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