<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>

<div class="content-header">
  <div class="container-fluid">
    <div class="row mb-2">
      <div class="col-sm-6"><h1 class="m-0">Manajemen Pengguna</h1></div>
      <div class="col-sm-6">
        <ol class="breadcrumb float-sm-right">
          <li class="breadcrumb-item"><a href="<?= site_url('dashboard') ?>">Dashboard</a></li>
          <li class="breadcrumb-item active">Manajemen Pengguna</li>
        </ol>
      </div>
    </div>
  </div>
</div>

<section class="content">
  <div class="container-fluid">

    <?php if ($this->session->flashdata('success')): ?>
      <div class="alert alert-success alert-dismissible fade show">
        <button type="button" class="close" data-dismiss="alert">&times;</button>
        <?= $this->session->flashdata('success') ?>
      </div>
    <?php endif; ?>
    <?php if ($this->session->flashdata('error')): ?>
      <div class="alert alert-danger alert-dismissible fade show">
        <button type="button" class="close" data-dismiss="alert">&times;</button>
        <?= $this->session->flashdata('error') ?>
      </div>
    <?php endif; ?>

    <div class="card card-outline card-danger">
      <div class="card-header">
        <h3 class="card-title"><i class="fa fa-users mr-1"></i> Daftar Pengguna Sistem</h3>
        <div class="card-tools">
          <a href="<?= site_url('pengaturan/pengguna/tambah') ?>" class="btn btn-danger btn-sm">
            <i class="fa fa-plus"></i> Tambah Pengguna
          </a>
        </div>
      </div>
      <div class="card-body p-0">
        <table class="table table-striped table-hover table-sm" id="tblPengguna">
          <thead class="bg-danger text-white">
            <tr>
              <th>No</th>
              <th>Username</th>
              <th>Nama Lengkap</th>
              <th>Role</th>
              <th>Status</th>
              <th>Login Terakhir</th>
              <th class="text-center">Aksi</th>
            </tr>
          </thead>
          <tbody>
            <?php $no = 1; foreach ($users as $u): ?>
              <tr>
                <td><?= $no++ ?></td>
                <td><strong><?= htmlspecialchars($u->username) ?></strong></td>
                <td><?= htmlspecialchars($u->nama_lengkap) ?></td>
                <td>
                  <?php
                    $role_map = [
                      'SUPERADMIN'   => 'badge-danger',
                      'ADMIN_PAYROLL'=> 'badge-warning',
                      'VIEWER'       => 'badge-info',
                    ];
                    $badge = $role_map[$u->role] ?? 'badge-secondary';
                  ?>
                  <span class="badge <?= $badge ?>"><?= $u->role ?></span>
                </td>
                <td>
                  <?php if ($u->is_active): ?>
                    <span class="badge badge-success"><i class="fa fa-check"></i> Aktif</span>
                  <?php else: ?>
                    <span class="badge badge-secondary"><i class="fa fa-times"></i> Nonaktif</span>
                  <?php endif; ?>
                </td>
                <td><?= $u->last_login ? format_tanggal_waktu($u->last_login) : '<span class="text-muted">Belum pernah</span>' ?></td>
                <td class="text-center">
                  <a href="<?= site_url('pengaturan/pengguna/edit/' . $u->id_user) ?>"
                     class="btn btn-xs btn-outline-primary" title="Edit">
                    <i class="fa fa-pencil"></i>
                  </a>
                  <button type="button" class="btn btn-xs btn-outline-info btn-reset-pwd"
                    data-id="<?= $u->id_user ?>" data-nama="<?= htmlspecialchars($u->nama_lengkap) ?>"
                    title="Reset Password">
                    <i class="fa fa-key"></i>
                  </button>
                  <?php if ($u->id_user !== (int)$this->session->userdata('id_user')): ?>
                    <a href="<?= site_url('pengaturan/pengguna/toggle_active/' . $u->id_user) ?>"
                       class="btn btn-xs <?= $u->is_active ? 'btn-outline-warning' : 'btn-outline-success' ?>"
                       title="<?= $u->is_active ? 'Nonaktifkan' : 'Aktifkan' ?>"
                       onclick="return confirm('<?= $u->is_active ? 'Nonaktifkan' : 'Aktifkan' ?> pengguna ini?')">
                      <i class="fa fa-<?= $u->is_active ? 'ban' : 'check' ?>"></i>
                    </a>
                    <button type="button" class="btn btn-xs btn-outline-danger btn-hapus"
                      data-id="<?= $u->id_user ?>" data-nama="<?= htmlspecialchars($u->nama_lengkap) ?>"
                      title="Hapus">
                      <i class="fa fa-trash"></i>
                    </button>
                  <?php endif; ?>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>

  </div>
</section>

<!-- Modal Reset Password -->
<div class="modal fade" id="modalResetPwd" tabindex="-1">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header bg-info text-white">
        <h5 class="modal-title"><i class="fa fa-key mr-1"></i> Reset Password</h5>
        <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body">
        <p class="text-muted mb-2">Reset password untuk: <strong id="resetNama"></strong></p>
        <div class="form-group">
          <label>Password Baru <span class="text-danger">*</span></label>
          <input type="password" id="inputNewPwd" class="form-control" placeholder="Min. 6 karakter">
        </div>
        <div id="resetError" class="text-danger small" style="display:none;"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Batal</button>
        <button type="button" class="btn btn-info btn-sm" id="btnDoReset">
          <i class="fa fa-save"></i> Reset
        </button>
      </div>
    </div>
  </div>
</div>

<script>
$(function() {
  if ($.fn.DataTable) {
    $('#tblPengguna').DataTable({
      responsive: true,
      language: { url: '<?= base_url('assets/plugins/datatables/i18n/Indonesian.json') ?>' }
    });
  }

  let resetId = 0;

  // Reset password modal
  $(document).on('click', '.btn-reset-pwd', function() {
    resetId = $(this).data('id');
    $('#resetNama').text($(this).data('nama'));
    $('#inputNewPwd').val('');
    $('#resetError').hide();
    $('#modalResetPwd').modal('show');
  });

  $('#btnDoReset').on('click', function() {
    const pwd = $('#inputNewPwd').val().trim();
    if (pwd.length < 6) {
      $('#resetError').text('Password minimal 6 karakter.').show();
      return;
    }
    $.post('<?= site_url('pengaturan/pengguna/reset_password/') ?>' + resetId, {
      new_password: pwd,
      '<?= $this->security->get_csrf_token_name() ?>': '<?= $this->security->get_csrf_hash() ?>'
    }, function(res) {
      if (res.success) {
        $('#modalResetPwd').modal('hide');
        Swal.fire({ icon: 'success', title: 'Berhasil', text: res.message, timer: 2000, showConfirmButton: false });
      } else {
        $('#resetError').text(res.message).show();
      }
    }, 'json');
  });

  // Hapus pengguna
  $(document).on('click', '.btn-hapus', function() {
    const id   = $(this).data('id');
    const nama = $(this).data('nama');
    Swal.fire({
      title: 'Hapus pengguna?',
      text: 'Akun "' + nama + '" akan dihapus permanen.',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#E53935',
      cancelButtonText: 'Batal',
      confirmButtonText: 'Ya, Hapus'
    }).then(result => {
      if (result.isConfirmed) {
        window.location.href = '<?= site_url('pengaturan/pengguna/hapus/') ?>' + id;
      }
    });
  });
});
</script>
