<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>
<div class="container-fluid py-5">
  <div class="row justify-content-center">
    <div class="col-xl-6">

      <?php if (session()->getFlashdata('errors')): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
          <?php foreach (session()->getFlashdata('errors') as $error): ?>
            <p class="mb-0"><?= esc($error) ?></p>
          <?php endforeach; ?>
          <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
      <?php endif; ?>

      <?php if (session()->getFlashdata('error')): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
          <p class="mb-0"><?= esc(session()->getFlashdata('error')) ?></p>
          <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
      <?php endif; ?>

      <?php if (session()->getFlashdata('success')): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
          <p class="mb-0"><?= esc(session()->getFlashdata('success')) ?></p>
          <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
      <?php endif; ?>

      <div class="card shadow mb-4">
        <div class="card-header py-3">
          <h6 class="m-0 font-weight-bold text-primary">edit role</h6>
        </div>
        <div class="card-body">
          <form method="post" action="<?= site_url('roles/update/' . $role['id']) ?>">
            <?= csrf_field() ?>
            <!-- Role Name -->
            <div class="mb-3">
              <label for="roleName" class="form-label">role name</label>
              <input type="text"
                     class="form-control"
                     id="roleName"
                     name="name"
                     minlength="3"
                     maxlength="255"
                     required
                     value="<?= esc(old('name', $role['name'])) ?>">
              <div class="form-text">stored lowercase automatically.</div>
            </div>

            <!-- Slug -->
            <div class="mb-3">
              <label for="roleSlug" class="form-label">slug</label>
              <input type="text"
                     class="form-control"
                     id="roleSlug"
                     name="slug"
                     maxlength="64"
                     value="<?= esc(old('slug', $role['slug'])) ?>">
              <div class="form-text">lowercase, a–z, 0–9, underscores. auto-updated from name if left blank.</div>
            </div>

            <!-- Dashboard Route -->
            <div class="mb-3">
              <label for="dashboardRoute" class="form-label">dashboard route</label>
              <input type="text"
                     class="form-control"
                     id="dashboardRoute"
                     name="dashboard_route"
                     maxlength="255"
                     required
                     value="<?= esc(old('dashboard_route', $role['dashboard_route'])) ?>">
              <div class="form-text">example: <code>/teacher_dashboard</code> or <code>administrator/administratordashboard</code> (stored lowercase).</div>
            </div>

            <!-- Description -->
            <div class="mb-3">
              <label for="roleDescription" class="form-label">description</label>
              <textarea class="form-control"
                        id="roleDescription"
                        name="description"
                        rows="3"
                        maxlength="500"><?= esc(old('description', $role['description'])) ?></textarea>
            </div>

            <!-- Priority -->
            <div class="mb-3">
              <label for="rolePriority" class="form-label">priority</label>
              <input type="number"
                     class="form-control"
                     id="rolePriority"
                     name="priority"
                     min="0"
                     step="1"
                     required
                     value="<?= esc(old('priority', $role['priority'] ?? 100)) ?>">
              <div class="form-text">lower number = higher priority when user has multiple roles.</div>
            </div>

            <!-- Is Active -->
            <div class="mb-3 form-check">
              <?php $isActiveOld = old('is_active', (string) ($role['is_active'] ?? '1')); ?>
              <input class="form-check-input"
                     type="checkbox"
                     value="1"
                     id="roleActive"
                     <?= ($isActiveOld === '1') ? 'checked' : '' ?>>
              <label class="form-check-label" for="roleActive">active</label>
              <input type="hidden" name="is_active" id="isActiveHidden" value="<?= $isActiveOld === '1' ? '1' : '0' ?>">
            </div>

            <div class="d-flex justify-content-between">
              <a href="<?= site_url('rolepermission/roles') ?>" class="btn btn-secondary">cancel</a>
              <button type="submit" class="btn btn-primary">update role</button>
            </div>
          </form>
        </div>
      </div>

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

<script>
(function () {
  const nameEl = document.getElementById('roleName');
  const slugEl = document.getElementById('roleSlug');
  const routeEl = document.getElementById('dashboardRoute');
  const descEl  = document.getElementById('roleDescription');
  const activeCb = document.getElementById('roleActive');
  const activeHidden = document.getElementById('isActiveHidden');

  function toSlug(str) {
    return String(str || '')
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, '_')
      .replace(/^_+|_+$/g, '');
  }

  // If slug is empty, keep auto-filling from name
  let userEditedSlug = false;
  slugEl.addEventListener('input', () => { userEditedSlug = slugEl.value.trim() !== ''; });
  nameEl.addEventListener('input', () => {
    if (!userEditedSlug || slugEl.value.trim() === '') {
      slugEl.value = toSlug(nameEl.value);
    }
  });

  // Force lowercase on blur for route/description
  [routeEl, descEl].forEach(el => el && el.addEventListener('blur', () => {
    el.value = (el.value || '').toLowerCase();
  }));

  // Keep hidden is_active synced
  if (activeCb && activeHidden) {
    activeCb.addEventListener('change', () => {
      activeHidden.value = activeCb.checked ? '1' : '0';
    });
  }
})();
</script>
<?= $this->endSection() ?>
