<?php
$title = 'Usuários';
require_once __DIR__ . '/auth.php';
require_perm('users.view');

$q    = trim($_GET['q'] ?? '');
$role = $_GET['role'] ?? '';
$where=[]; $args=[];
if ($q!==''){ $where[]="(u.username LIKE ? OR u.name LIKE ?)"; $args[]="%$q%"; $args[]="%$q%"; }
if ($role!==''){ $where[]="u.role=?"; $args[]=$role; }

$sql = "SELECT u.id,u.name,u.username,u.role,u.is_active,u.password_changed_at
        FROM users u";
if ($where) $sql .= " WHERE ".implode(' AND ',$where);
$sql .= " ORDER BY u.name ASC";
$rows = $pdo->prepare($sql); $rows->execute($args); $rows=$rows->fetchAll();

include __DIR__ . '/header.php';
?>
<div class="container-fluid">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h2 class="h5 m-0">Usuários</h2>
    <?php if (user_has_perm('users.*')): ?>
      <button class="btn btn-primary" id="btnNewUser">
        <i class="bi bi-plus-lg me-1"></i>Novo usuário
      </button>
    <?php endif; ?>
  </div>

  <form class="row g-2 mb-3" method="get">
    <div class="col-md-5">
      <input class="form-control" name="q" placeholder="Nome ou usuário" value="<?= h($q) ?>">
    </div>
    <div class="col-md-3">
      <select name="role" class="form-select">
        <option value="">(todos os papéis)</option>
        <?php foreach (['ADMIN','TI','RH','AUDITOR','VIEWER'] as $r): ?>
          <option value="<?= $r ?>" <?= $role===$r?'selected':'' ?>><?= $r ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-md-4 d-flex gap-2">
      <button class="btn btn-outline-primary flex-fill">Filtrar</button>
      <a class="btn btn-outline-secondary" href="<?= base_url('users.php') ?>">Limpar</a>
    </div>
  </form>

  <div class="card border-0 shadow-sm">
    <div class="table-responsive">
      <table class="table table-striped align-middle mb-0">
        <thead>
          <tr>
            <th>Nome</th>
            <th>Usuário</th>
            <th>Papel</th>
            <th>Ativo</th>
            <th>Senha alterada</th>
            <th class="text-end">Ações</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($rows as $u): ?>
            <tr>
              <td class="fw-semibold"><?= h($u['name']) ?></td>
              <td class="text-muted"><?= h($u['username']) ?></td>
              <td>
                <span class="badge bg-secondary"><?= h($u['role']) ?></span>
              </td>
              <td>
                <?php if ($u['is_active']): ?>
                  <span class="badge bg-success">Sim</span>
                <?php else: ?>
                  <span class="badge bg-danger">Não</span>
                <?php endif; ?>
              </td>
              <td><?= br_datetime($u['password_changed_at']) ?></td>
              <td class="text-end">
                <?php if (user_has_perm('users.*')): ?>
                  <button class="btn btn-sm btn-outline-primary btnEditUser" data-id="<?= (int)$u['id'] ?>">
                    Editar
                  </button>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; if(!$rows): ?>
            <tr><td colspan="6" class="text-muted">Nenhum usuário encontrado.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- Modal “host” para carregar o conteúdo do user_form.php -->
<div class="modal fade" id="modalUserHost" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <!-- será preenchido via JS -->
      <div class="p-5 text-center text-muted">Carregando…</div>
    </div>
  </div>
</div>

<script>
(function(){
  const hostEl  = document.getElementById('modalUserHost');
  const content = hostEl.querySelector('.modal-content');
  let modal;

  function execInlineScripts(fromDoc){
    // reexecuta <script> do conteúdo carregado (para senhas, máscaras etc.)
    fromDoc.querySelectorAll('script').forEach(s=>{
      if (s.src) {
        const tag = document.createElement('script');
        tag.src = s.src; document.body.appendChild(tag);
      } else if (s.textContent.trim()) {
        try { (0,eval)(s.textContent); } catch(e) { console.error(e); }
      }
    });
  }

  async function loadUserForm(url){
    content.innerHTML = '<div class="p-5 text-center text-muted">Carregando…</div>';
    const res  = await fetch(url, {headers:{'X-Requested-With':'XMLHttpRequest'}});
    const html = await res.text();
    const doc  = new DOMParser().parseFromString(html,'text/html');
    const inner = doc.querySelector('#userModal .modal-content') || doc.querySelector('.modal-content');
    content.innerHTML = inner ? inner.innerHTML : html;
    execInlineScripts(doc);

    // abre modal
    modal = modal || new bootstrap.Modal(hostEl);
    modal.show();

    // intercepta submit do formulário para salvar via AJAX
    const form = content.querySelector('form');
    if (form) {
      form.addEventListener('submit', async function(ev){
        ev.preventDefault();
        const btn = form.querySelector('button[type="submit"], button.btn-primary');
        btn && (btn.disabled = true);
        const resp = await fetch(form.action, {method:'POST', body: new FormData(form)});
        const tx   = await resp.text();
        const nd   = new DOMParser().parseFromString(tx,'text/html');
        const ok   = nd.querySelector('.alert.alert-success');
        const inner2 = nd.querySelector('#userModal .modal-content') || nd.querySelector('.modal-content');
        content.innerHTML = inner2 ? inner2.innerHTML : tx;
        execInlineScripts(nd);

        if (ok) {
          // pequeno delay para feedback e atualiza a lista
          setTimeout(()=>{ window.location.reload(); }, 400);
        }
      });
    }

    // garante que os botões de fechar só fechem o host (sem redirecionar)
    content.querySelectorAll('[data-bs-dismiss="modal"]').forEach(b=>{
      b.addEventListener('click', ()=> bootstrap.Modal.getInstance(hostEl)?.hide());
    });
  }

  // Novo
  document.getElementById('btnNewUser')?.addEventListener('click', ()=>{
    loadUserForm('<?= base_url('user_form.php') ?>');
  });

  // Editar
  document.querySelectorAll('.btnEditUser').forEach(btn=>{
    btn.addEventListener('click', ()=>{
      const id = btn.getAttribute('data-id');
      loadUserForm('<?= base_url('user_form.php') ?>?id=' + encodeURIComponent(id));
    });
  });
})();
</script>

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

