<?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"><?= $action === 'tambah' ? 'Tambah Pengguna' : 'Edit 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"><a href="<?= site_url('pengaturan/pengguna') ?>">Manajemen Pengguna</a></li>
          <li class="breadcrumb-item active"><?= $action === 'tambah' ? 'Tambah' : 'Edit' ?></li>
        </ol>
      </div>
    </div>
  </div>
</div>

<section class="content">
  <div class="container-fluid">
    <div class="row justify-content-center">
      <div class="col-md-7">
        <div class="card card-outline card-danger">
          <div class="card-header">
            <h3 class="card-title">
              <i class="fa fa-<?= $action === 'tambah' ? 'user-plus' : 'user' ?> mr-1"></i>
              Form <?= $action === 'tambah' ? 'Pengguna Baru' : 'Edit: ' . htmlspecialchars($user->nama_lengkap ?? '') ?>
            </h3>
          </div>
          <div class="card-body">

            <div id="alertMsg" class="alert d-none"></div>

            <div class="form-group row">
              <label class="col-sm-3 col-form-label">Username <span class="text-danger">*</span></label>
              <div class="col-sm-9">
                <input type="text" id="inputUsername" class="form-control"
                       value="<?= htmlspecialchars($user->username ?? '') ?>"
                       placeholder="Contoh: admin_hr" autocomplete="off">
              </div>
            </div>

            <div class="form-group row">
              <label class="col-sm-3 col-form-label">Nama Lengkap <span class="text-danger">*</span></label>
              <div class="col-sm-9">
                <input type="text" id="inputNama" class="form-control"
                       value="<?= htmlspecialchars($user->nama_lengkap ?? '') ?>"
                       placeholder="Nama lengkap pengguna">
              </div>
            </div>

            <div class="form-group row">
              <label class="col-sm-3 col-form-label">Role <span class="text-danger">*</span></label>
              <div class="col-sm-9">
                <select id="inputRole" class="form-control">
                  <option value="ADMIN_PAYROLL" <?= (isset($user->role) && $user->role === 'ADMIN_PAYROLL') ? 'selected' : '' ?>>Admin Payroll</option>
                  <option value="VIEWER"        <?= (isset($user->role) && $user->role === 'VIEWER')        ? 'selected' : '' ?>>Viewer / Auditor</option>
                  <option value="SUPERADMIN"    <?= (isset($user->role) && $user->role === 'SUPERADMIN')    ? 'selected' : '' ?>>Superadmin</option>
                </select>
                <small class="text-muted">Superadmin memiliki akses penuh termasuk kelola pengguna dan lock payroll.</small>
              </div>
            </div>

            <div class="form-group row">
              <label class="col-sm-3 col-form-label">
                Password <?= $action === 'tambah' ? '<span class="text-danger">*</span>' : '' ?>
              </label>
              <div class="col-sm-9">
                <input type="password" id="inputPwd" class="form-control"
                       placeholder="<?= $action === 'tambah' ? 'Min. 6 karakter' : 'Kosongkan jika tidak ingin mengubah password' ?>"
                       autocomplete="new-password">
                <?php if ($action !== 'tambah'): ?>
                  <small class="text-muted">Kosongkan jika tidak ingin mengubah password.</small>
                <?php endif; ?>
              </div>
            </div>

          </div>
          <div class="card-footer">
            <button type="button" id="btnSimpan" class="btn btn-danger">
              <i class="fa fa-save mr-1"></i> Simpan
            </button>
            <a href="<?= site_url('pengaturan/pengguna') ?>" class="btn btn-secondary ml-2">
              <i class="fa fa-arrow-left mr-1"></i> Kembali
            </a>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

<script>
$(function() {
  $('#btnSimpan').on('click', function() {
    const $btn = $(this);
    $btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin mr-1"></i> Menyimpan...');
    $('#alertMsg').addClass('d-none');

    $.post('<?= site_url('pengaturan/pengguna/simpan') ?>', {
      id_user:      <?= isset($user->id_user) ? (int)$user->id_user : 0 ?>,
      username:     $('#inputUsername').val().trim(),
      nama_lengkap: $('#inputNama').val().trim(),
      role:         $('#inputRole').val(),
      password:     $('#inputPwd').val(),
      '<?= $this->security->get_csrf_token_name() ?>': '<?= $this->security->get_csrf_hash() ?>'
    }, function(res) {
      $btn.prop('disabled', false).html('<i class="fa fa-save mr-1"></i> Simpan');
      if (res.success) {
        Swal.fire({ icon: 'success', title: 'Berhasil', text: res.message, timer: 1800, showConfirmButton: false })
          .then(() => { window.location.href = '<?= site_url('pengaturan/pengguna') ?>'; });
      } else {
        $('#alertMsg').removeClass('d-none').removeClass('alert-success')
          .addClass('alert-danger').text(res.message);
      }
    }, 'json').fail(function() {
      $btn.prop('disabled', false).html('<i class="fa fa-save mr-1"></i> Simpan');
      $('#alertMsg').removeClass('d-none').addClass('alert-danger').text('Terjadi kesalahan server.');
    });
  });
});
</script>
