<?php
// admin/akun.php — CRUD Akun
require_once '../includes/config.php';
require_once '../includes/auth.php';
requireAdmin();

$msg   = htmlspecialchars($_GET['msg'] ?? '');
$error = '';
$editAkunTemp = null;

// ── HAPUS ──
if (isset($_GET['hapus'])) {
    $hId = (int)$_GET['hapus'];
    if ($hId !== (int)currentUser()['id']) {
        $pdo->prepare("UPDATE akun SET aktif=0 WHERE id=?")->execute([$hId]);
        $msg = 'Akun berhasil dinonaktifkan.';
    } else {
        $error = 'Tidak bisa menghapus akun sendiri.';
    }
}

// ── SIMPAN ──
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id       = (int)($_POST['id'] ?? 0);
    $nama     = trim($_POST['nama']     ?? '');
    $username = trim($_POST['username'] ?? '');
    $role     = $_POST['role'] ?? 'kasir';
    $password = $_POST['password'] ?? '';

    if (!$nama || !$username) {
        $error = 'Nama dan username wajib diisi.';
    } else {
        if ($id > 0) {
            $dup = $pdo->prepare("SELECT id FROM akun WHERE username=? AND id!=?");
            $dup->execute([$username, $id]);
            if ($dup->fetch()) {
                $error = 'Username sudah digunakan.';
                $editAkunTemp = compact('id','nama','username','role');
            } else {
                if ($password) {
                    $pdo->prepare("UPDATE akun SET nama=?,username=?,role=?,password=? WHERE id=?")->execute([$nama, $username, $role, password_hash($password, PASSWORD_BCRYPT), $id]);
                } else {
                    $pdo->prepare("UPDATE akun SET nama=?,username=?,role=? WHERE id=?")->execute([$nama, $username, $role, $id]);
                }
                header('Location: akun.php?msg=' . urlencode('Akun berhasil diperbarui.'));
                exit;
            }
        } else {
            if (!$password) {
                $error = 'Password wajib diisi untuk akun baru.';
                $editAkunTemp = compact('id','nama','username','role');
            } else {
                $dup = $pdo->prepare("SELECT id FROM akun WHERE username=?");
                $dup->execute([$username]);
                if ($dup->fetch()) {
                    $error = 'Username sudah digunakan.';
                    $editAkunTemp = compact('id','nama','username','role');
                } else {
                    $pdo->prepare("INSERT INTO akun(nama,username,password,role) VALUES(?,?,?,?)")->execute([$nama, $username, password_hash($password, PASSWORD_BCRYPT), $role]);
                    header('Location: akun.php?msg=' . urlencode('Akun berhasil ditambahkan.'));
                    exit;
                }
            }
        }
    }
}

$akunList = $pdo->query("SELECT * FROM akun WHERE aktif=1 ORDER BY role, nama")->fetchAll();

// Jika POST error, pakai data yang sudah diisi
$editAkun = $editAkunTemp ?? null;
// Jika GET edit, ambil dari database
if (!$editAkun && isset($_GET['edit'])) {
    $s = $pdo->prepare("SELECT * FROM akun WHERE id=? AND aktif=1");
    $s->execute([(int)$_GET['edit']]);
    $editAkun = $s->fetch() ?: null;
}
?>
<!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>Manajemen Akun — <?= 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">👥 Manajemen Akun</div>
      <a href="<?= BASE_URL ?>logout.php" class="topbar-btn" style="background:#ef4444" onclick="return confirm('Yakin ingin keluar?')">🚪 <span class="btn-text">Logout</span></a>
      <button class="topbar-btn" onclick="openModal()">+ <span class="btn-text">Tambah Akun</span></button>
    </div>
    <div class="page-body">
      <?php if ($msg):   ?><div class="alert alert-success"><?= htmlspecialchars($msg) ?></div><?php endif; ?>
      <?php if ($error): ?><div class="alert alert-error"><?= htmlspecialchars($error) ?></div><?php endif; ?>

      <div class="card">
        <div class="card-header"><h3>Daftar Akun (<?= count($akunList) ?>)</h3></div>
        <div class="table-wrap">
          <table class="akun-table">
            <thead><tr><th>Nama</th><th>Username</th><th>Role</th><th>Dibuat</th><th>Aksi</th></tr></thead>
            <tbody>
              <?php foreach ($akunList as $a): ?>
              <tr>
                <td><strong><?= htmlspecialchars($a['nama']) ?></strong></td>
                <td><code><?= htmlspecialchars($a['username']) ?></code></td>
                <td><span class="badge <?= $a['role']==='admin' ? 'badge-blue':'badge-green' ?>"><?= ucfirst($a['role']) ?></span></td>
                <td style="font-size:12px;color:var(--muted)"><?= date('d/m/Y', strtotime($a['dibuat'])) ?></td>
                <td>
                  <div style="display:flex;gap:6px">
                    <a href="?edit=<?= $a['id'] ?>" class="btn btn-primary btn-sm">Edit</a>
                    <?php if ($a['id'] != currentUser()['id']): ?>
                    <a href="?hapus=<?= $a['id'] ?>" class="btn btn-red btn-sm" onclick="return confirm('Nonaktifkan akun ini?')">Hapus</a>
                    <?php endif; ?>
                  </div>
                </td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Modal -->
<div class="modal-overlay <?= $editAkun ? 'open':'' ?>" id="modal">
  <div class="modal">
    <div class="modal-header">
      <h4><?= $editAkun ? 'Edit Akun' : 'Tambah Akun Baru' ?></h4>
      <button class="modal-close" onclick="closeModal()">×</button>
    </div>
    <form method="POST">
      <div class="modal-body">
        <input type="hidden" name="id" value="<?= htmlspecialchars($editAkun['id'] ?? '') ?>">
        <div class="form-group">
          <label>Nama Lengkap *</label>
          <input type="text" name="nama" class="form-control" required value="<?= htmlspecialchars($editAkun['nama'] ?? '') ?>">
        </div>
        <div class="form-row">
          <div class="form-group">
            <label>Username *</label>
            <input type="text" name="username" class="form-control" required value="<?= htmlspecialchars($editAkun['username'] ?? '') ?>">
          </div>
          <div class="form-group">
            <label>Role</label>
            <select name="role" class="form-control">
              <option value="kasir" <?= ($editAkun['role'] ?? '') === 'kasir' ? 'selected':'' ?>>Kasir</option>
              <option value="admin" <?= ($editAkun['role'] ?? '') === 'admin' ? 'selected':'' ?>>Admin</option>
            </select>
          </div>
        </div>
        <div class="form-group">
          <label>Password <?= $editAkun ? '(kosongkan jika tidak diubah)' : '*' ?></label>
          <input type="password" name="password" class="form-control" placeholder="Masukkan password..." <?= $editAkun ? '' : 'required' ?>>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-ghost" onclick="closeModal()">Batal</button>
        <button type="submit" class="btn btn-primary">Simpan</button>
      </div>
    </form>
  </div>
</div>
<script src="<?= BASE_URL ?>js/app.js"></script>
<script><?php if ($editAkun): ?>document.addEventListener('DOMContentLoaded',()=>openModal());<?php endif; ?></script>
</body>
</html>