<?php
require_once __DIR__ . '/../config/secure_bootstrap.php';
include __DIR__ . '/includes/header.php';

// Ambil semua pengguna
$stmt = $pdo->query("SELECT * FROM users ORDER BY created_at DESC");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="container-fluid mt-4">
  <div class="card shadow border-0 rounded-4">
    <div class="card-body">

      <!-- Header -->
      <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center mb-4">
        <div class="mb-3 mb-md-0">
          <h4 class="fw-bold text-success mb-0">
            <i class="fa-solid fa-users me-2"></i>Manajemen Pengguna
          </h4>
          <small class="text-muted">Kelola akun pengguna sistem LPM di sini.</small>
        </div>

        <!-- Tombol Tambah -->
        <div>
          <button class="btn btn-success px-4" data-bs-toggle="modal" data-bs-target="#addModal">
            <i class="fa-solid fa-user-plus me-1"></i> Tambah Pengguna
          </button>
        </div>
      </div>

      <!-- Tabel Pengguna -->
      <div class="table-responsive">
        <table class="table table-bordered align-middle mb-0">
          <thead class="table-success text-center align-middle">
            <tr>
              <th style="width:5%;">No</th>
              <th>Username</th>
              <th>Nama Lengkap</th>
              <th>Email</th>
              <th style="width:10%;">Status</th>
              <th style="width:15%;">Dibuat</th>
              <th style="width:15%;">Aksi</th>
            </tr>
          </thead>
          <tbody>
            <?php if ($users): foreach ($users as $i => $u): ?>
            <tr>
              <td class="text-center"><?= $i + 1 ?></td>
              <td><?= htmlspecialchars($u['username']) ?></td>
              <td><?= htmlspecialchars($u['full_name']) ?></td>
              <td><?= htmlspecialchars($u['email']) ?></td>
              <td class="text-center">
                <?php if ($u['is_active']): ?>
                  <span class="badge rounded-pill bg-success">Aktif</span>
                <?php else: ?>
                  <span class="badge rounded-pill bg-secondary">Nonaktif</span>
                <?php endif; ?>
              </td>
              <td class="text-center"><?= date('d M Y', strtotime($u['created_at'])) ?></td>
              <td class="text-center">
                <div class="btn-group">
                  <button class="btn btn-sm btn-primary edit-btn"
                          data-id="<?= $u['id'] ?>"
                          data-username="<?= htmlspecialchars($u['username']) ?>"
                          data-fullname="<?= htmlspecialchars($u['full_name']) ?>"
                          data-email="<?= htmlspecialchars($u['email']) ?>"
                          data-active="<?= $u['is_active'] ?>"
                          title="Edit">
                    <i class="fa-solid fa-pen-to-square"></i>
                  </button>
                  <button class="btn btn-sm btn-danger delete-btn" 
                          data-id="<?= $u['id'] ?>" 
                          title="Hapus">
                    <i class="fa-solid fa-trash"></i>
                  </button>
                </div>
              </td>
            </tr>
            <?php endforeach; else: ?>
            <tr>
              <td colspan="7" class="text-center text-muted py-3">Belum ada pengguna yang terdaftar.</td>
            </tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>

    </div>
  </div>
</div>

<!-- Modal Tambah -->
<div class="modal fade" id="addModal" tabindex="-1">
  <div class="modal-dialog">
    <form method="post" class="modal-content">
      <div class="modal-header bg-success text-white">
        <h5 class="modal-title"><i class="fa-solid fa-user-plus me-2"></i>Tambah Pengguna</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <label class="form-label">Username</label>
        <input type="text" name="username" class="form-control" required>

        <label class="form-label mt-2">Nama Lengkap</label>
        <input type="text" name="full_name" class="form-control" required>

        <label class="form-label mt-2">Email</label>
        <input type="email" name="email" class="form-control">

        <label class="form-label mt-2">Password</label>
        <input type="password" name="password" class="form-control" required>

        <div class="form-check mt-3">
          <input class="form-check-input" type="checkbox" name="is_active" id="is_active" checked>
          <label class="form-check-label" for="is_active">Akun Aktif</label>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
        <button type="submit" name="add" class="btn btn-success">Simpan</button>
      </div>
    </form>
  </div>
</div>

<!-- Modal Edit -->
<div class="modal fade" id="editModal" tabindex="-1">
  <div class="modal-dialog">
    <form method="post" class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title"><i class="fa-solid fa-pen-to-square me-2"></i>Edit Pengguna</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="edit_id" id="edit_id">

        <label class="form-label">Username</label>
        <input type="text" name="edit_username" id="edit_username" class="form-control" readonly>

        <label class="form-label mt-2">Nama Lengkap</label>
        <input type="text" name="edit_full_name" id="edit_full_name" class="form-control" required>

        <label class="form-label mt-2">Email</label>
        <input type="email" name="edit_email" id="edit_email" class="form-control">

        <label class="form-label mt-2">Password Baru (opsional)</label>
        <input type="password" name="edit_password" class="form-control" placeholder="Kosongkan jika tidak diganti">

        <div class="form-check mt-3">
          <input class="form-check-input" type="checkbox" name="edit_active" id="edit_active">
          <label class="form-check-label" for="edit_active">Akun Aktif</label>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
        <button type="submit" name="update" class="btn btn-primary">Perbarui</button>
      </div>
    </form>
  </div>
</div>

<?php
// ===== CRUD =====

// Tambah user
if (isset($_POST['add'])) {
    $password_hash = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $is_active = isset($_POST['is_active']) ? 1 : 0;

    $stmt = $pdo->prepare("INSERT INTO users (username, password_hash, full_name, email, is_active)
                           VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([
        $_POST['username'], $password_hash, $_POST['full_name'], $_POST['email'], $is_active
    ]);

    echo "<script>Swal.fire('Berhasil', 'Pengguna berhasil ditambahkan', 'success').then(()=>location.href='users.php');</script>";
}

// Update user
if (isset($_POST['update'])) {
    $id = $_POST['edit_id'];
    $is_active = isset($_POST['edit_active']) ? 1 : 0;

    if (!empty($_POST['edit_password'])) {
        $password_hash = password_hash($_POST['edit_password'], PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("UPDATE users SET full_name=?, email=?, password_hash=?, is_active=? WHERE id=?");
        $stmt->execute([
            $_POST['edit_full_name'], $_POST['edit_email'], $password_hash, $is_active, $id
        ]);
    } else {
        $stmt = $pdo->prepare("UPDATE users SET full_name=?, email=?, is_active=? WHERE id=?");
        $stmt->execute([
            $_POST['edit_full_name'], $_POST['edit_email'], $is_active, $id
        ]);
    }

    echo "<script>Swal.fire('Berhasil', 'Data pengguna diperbarui', 'success').then(()=>location.href='users.php');</script>";
}

// Hapus user
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $stmt = $pdo->prepare("DELETE FROM users WHERE id=?");
    $stmt->execute([$id]);
    echo "<script>Swal.fire('Dihapus', 'Pengguna berhasil dihapus', 'success').then(()=>location.href='users.php');</script>";
}
?>

<script>
document.addEventListener('DOMContentLoaded', () => {
  // Edit data
  document.querySelectorAll('.edit-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      document.getElementById('edit_id').value = btn.dataset.id;
      document.getElementById('edit_username').value = btn.dataset.username;
      document.getElementById('edit_full_name').value = btn.dataset.fullname;
      document.getElementById('edit_email').value = btn.dataset.email;
      document.getElementById('edit_active').checked = btn.dataset.active == 1;
      new bootstrap.Modal(document.getElementById('editModal')).show();
    });
  });

  // Hapus data
  document.querySelectorAll('.delete-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      Swal.fire({
        title: 'Hapus Pengguna?',
        text: 'Data akun akan dihapus permanen!',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Ya, hapus!',
        cancelButtonText: 'Batal'
      }).then(result => {
        if (result.isConfirmed) {
          window.location = 'users.php?delete=' + btn.dataset.id;
        }
      });
    });
  });
});
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>
