<?php
require '../db.php';
require '../auth.php';
require_login();
require_admin();

$success = $_GET['success'] ?? '';
$error = $_GET['error'] ?? '';

// Get all users
$stmt = $db->query('SELECT * FROM users ORDER BY created_at DESC');
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!doctype html>
<html lang="id">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Manajemen Akun - DIPARKUM Digitalisasi Peminjaman Arsip Perkara Kepaniteraan Hukum</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
<style>
body { background: #f5f7fb; }
</style>
</head>
<body>

<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
  <div class="container-fluid">
    <a class="navbar-brand d-flex align-items-center" href="../index.php">
      <img src="../gambar/Logo_pnwtp.png" alt="Logo PN Watampone" width="70" height="70" class="me-3">
      <span><i class="fa fa-book me-1"></i> DIPARKUM Digitalisasi Peminjaman Arsip Perkara Kepaniteraan Hukum<br><small>Pengadilan Negeri Watampone</small></span>
    </a>
    <div class="d-flex gap-2">
      <a class="btn btn-outline-light btn-sm" href="../index.php"><i class="fa fa-home"></i> Dashboard</a>
      <a class="btn btn-outline-light btn-sm" href="../arsip.php"><i class="fa fa-archive"></i> Arsip SIPP</a>
      <a class="btn btn-outline-light btn-sm" href="../admin.php"><i class="fa fa-cog"></i> Pengaturan</a>
      <span class="navbar-text text-light">Hi, <?=htmlspecialchars(current_user()['nama_lengkap'] ?? current_user()['username'])?></span>
      <a class="btn btn-outline-light btn-sm" href="../logout.php"><i class="fa fa-sign-out-alt"></i> Logout</a>
    </div>
  </div>
</nav>

<div class="container py-4">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h3 class="mb-0"><i class="fa fa-users"></i> Manajemen Akun</h3>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalAdd">
      <i class="fa fa-plus"></i> Tambah Akun
    </button>
  </div>

  <?php if($success): ?>
    <div class="alert alert-success alert-dismissible fade show">
      <i class="fa fa-check-circle"></i> 
      <?php if($success === 'created'): ?>
        Akun berhasil dibuat!
      <?php elseif($success === 'updated'): ?>
        Akun berhasil diperbarui!
      <?php elseif($success === 'deleted'): ?>
        Akun berhasil dihapus!
      <?php endif; ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
  <?php endif; ?>

  <?php if($error): ?>
    <div class="alert alert-danger alert-dismissible fade show">
      <i class="fa fa-exclamation-triangle"></i> <?= htmlspecialchars($error) ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
  <?php endif; ?>

  <div class="card">
    <div class="card-body">
      <div class="table-responsive">
        <table class="table table-striped align-middle">
          <thead class="table-light">
            <tr>
              <th>#</th>
              <th>Username</th>
              <th>Nama Lengkap</th>
              <th>Role</th>
              <th>Dibuat</th>
              <th class="text-end">Aksi</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach($users as $user): ?>
              <tr>
                <td><?= $user['id'] ?></td>
                <td>
                  <strong><?= htmlspecialchars($user['username']) ?></strong>
                  <?php if($user['id'] == current_user()['id']): ?>
                    <span class="badge bg-info ms-1">Anda</span>
                  <?php endif; ?>
                </td>
                <td>
                  <strong><?= htmlspecialchars($user['nama_lengkap'] ?? $user['username']) ?></strong>
                </td>
                <td>
                  <span class="badge bg-<?= $user['role'] === 'admin' ? 'danger' : 'primary' ?>">
                    <?= ucfirst($user['role']) ?>
                  </span>
                </td>
                <td><?= date('d/m/Y H:i', strtotime($user['created_at'])) ?></td>
                <td class="text-end">
                  <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-warning" 
                            onclick="editUser(<?= $user['id'] ?>, '<?= htmlspecialchars($user['username'], ENT_QUOTES) ?>', '<?= htmlspecialchars($user['nama_lengkap'] ?? $user['username'], ENT_QUOTES) ?>', '<?= $user['role'] ?>')"
                            title="Edit">
                      <i class="fa fa-edit"></i>
                    </button>
                    
                    <?php if($user['id'] != current_user()['id']): ?>
                      <button class="btn btn-outline-danger" 
                              onclick="deleteUser(<?= $user['id'] ?>, '<?= htmlspecialchars($user['username'], ENT_QUOTES) ?>')"
                              title="Hapus">
                        <i class="fa fa-trash"></i>
                      </button>
                    <?php else: ?>
                      <button class="btn btn-outline-secondary" disabled title="Tidak bisa menghapus akun sendiri">
                        <i class="fa fa-lock"></i>
                      </button>
                    <?php endif; ?>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>
            
            <?php if(empty($users)): ?>
              <tr>
                <td colspan="5" class="text-center text-muted py-4">
                  <i class="fa fa-users fa-2x mb-2"></i><br>
                  Tidak ada akun yang ditemukan
                </td>
              </tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
      
      <div class="mt-3 text-muted">
        Total: <?= count($users) ?> akun
      </div>
    </div>
  </div>
</div>

<!-- Modal Add -->
<div class="modal fade" id="modalAdd" tabindex="-1">
  <div class="modal-dialog">
    <form class="modal-content" method="post" action="user_store.php">
      <div class="modal-header">
        <h5 class="modal-title"><i class="fa fa-plus"></i> Tambah Akun Baru</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="mb-3">
          <label class="form-label">Username *</label>
          <input type="text" name="username" class="form-control" required>
          <small class="form-text text-muted">Username harus unik</small>
        </div>
        <div class="mb-3">
          <label class="form-label">Nama Lengkap *</label>
          <input type="text" name="nama_lengkap" class="form-control" required>
          <small class="form-text text-muted">Nama lengkap yang akan ditampilkan</small>
        </div>
        <div class="mb-3">
          <label class="form-label">Password *</label>
          <input type="password" name="password" class="form-control" required minlength="6">
          <small class="form-text text-muted">Minimal 6 karakter</small>
        </div>
        <div class="mb-3">
          <label class="form-label">Role *</label>
          <select name="role" class="form-select" required>
            <option value="">-- Pilih Role --</option>
            <option value="admin">Admin</option>
            <option value="petugas">Petugas</option>
          </select>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
        <button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> Simpan</button>
      </div>
    </form>
  </div>
</div>

<!-- Modal Edit -->
<div class="modal fade" id="modalEdit" tabindex="-1">
  <div class="modal-dialog">
    <form class="modal-content" method="post" action="user_update.php">
      <input type="hidden" name="id" id="edit_id">
      <div class="modal-header">
        <h5 class="modal-title"><i class="fa fa-edit"></i> Edit Akun</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="mb-3">
          <label class="form-label">Username *</label>
          <input type="text" name="username" id="edit_username" class="form-control" required>
        </div>
        <div class="mb-3">
          <label class="form-label">Nama Lengkap *</label>
          <input type="text" name="nama_lengkap" id="edit_nama_lengkap" class="form-control" required>
        </div>
        <div class="mb-3">
          <label class="form-label">Password Baru</label>
          <input type="password" name="password" class="form-control" minlength="6">
          <small class="form-text text-muted">Kosongkan jika tidak ingin mengubah password</small>
        </div>
        <div class="mb-3">
          <label class="form-label">Role *</label>
          <select name="role" id="edit_role" class="form-select" required>
            <option value="admin">Admin</option>
            <option value="petugas">Petugas</option>
          </select>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
        <button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> Update</button>
      </div>
    </form>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
function editUser(id, username, nama_lengkap, role) {
  document.getElementById('edit_id').value = id;
  document.getElementById('edit_username').value = username;
  document.getElementById('edit_nama_lengkap').value = nama_lengkap;
  document.getElementById('edit_role').value = role;
  new bootstrap.Modal(document.getElementById('modalEdit')).show();
}

function deleteUser(id, username) {
  if (confirm(`Yakin ingin menghapus akun "${username}"?`)) {
    fetch('user_delete.php', {
      method: 'POST',
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      body: 'id=' + id
    })
    .then(response => response.json())
    .then(data => {
      if (data.success) {
        location.reload();
      } else {
        alert('Gagal menghapus: ' + data.message);
      }
    })
    .catch(error => {
      console.error('Error:', error);
      alert('Terjadi kesalahan');
    });
  }
}
</script>

<!-- Footer -->
<footer class="bg-primary text-white text-center py-3 mt-5">
  <div class="container">
    <p class="mb-0">©2025 by Pn Watampone, Dibuat oleh Fahrurrasyid, A.Md.T CPNS Mahkamah Agung RI Angkatan 2024</p>
  </div>
</footer>

</body>
</html>
