<?php
// usuarios.php — Gerenciamento de usuários (ADMIN only)
$pageActive = 'usuarios';
$pageTitle  = 'Usuários';
require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/auth.php';
requirePerfil(['ADMIN']);

$erros   = [];
$sucesso = '';
$editUser = null;

// Carregar usuário para edição de forma limpa
$editId = (int)($_GET['edit'] ?? 0);
if ($editId) {
    $stmt = pdo()->prepare("SELECT * FROM usuarios WHERE id=?");
    $stmt->execute([$editId]);
    $editUser = $stmt->fetch();
}

// ── AÇÃO: Ativar / Desativar (Bloquear) ──────────────────
if (isset($_GET['toggle']) && isset($_GET['uid'])) {
    $uid = (int)$_GET['uid'];
    
    if ($uid === usuarioLogado()['id']) {
        header('Location: usuarios.php?erro=Voce+nao+pode+desativar+seu+proprio+usuario!'); exit;
    }
    
    $stmt = pdo()->prepare("SELECT ativo FROM usuarios WHERE id=?");
    $stmt->execute([$uid]);
    $ativo = (int)$stmt->fetchColumn();
    
    pdo()->prepare("UPDATE usuarios SET ativo=? WHERE id=?")->execute([$ativo ? 0 : 1, $uid]);
    header('Location: usuarios.php?msg=Status+do+usuario+alterado+com+sucesso!'); exit;
}

// ── AÇÃO: Excluir Usuário ────────────────────────────────
if (isset($_GET['delete']) && isset($_GET['uid'])) {
    $uid = (int)$_GET['uid'];
    
    if ($uid === usuarioLogado()['id']) {
        header('Location: usuarios.php?erro=Voce+nao+pode+excluir+seu+proprio+usuario!'); exit;
    }

    try {
        pdo()->prepare("DELETE FROM usuarios WHERE id=?")->execute([$uid]);
        header('Location: usuarios.php?msg=Usuario+removido+com+sucesso!'); exit;
    } catch (PDOException $e) {
        if ($e->getCode() == '23000') {
            header('Location: usuarios.php?erro=Nao+e+possivel+excluir.+Este+usuario+possui+vinculos+no+sistema+(OS+ou+Historico).'); exit;
        } else {
            header('Location: usuarios.php?erro=Erro+ao+excluir+registro.'); exit;
        }
    }
}

// ── AÇÃO: Salvar (POST) ──────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCsrf($_POST['csrf_token'] ?? '')) die('CSRF inválido');

    $nome   = trim($_POST['nome'] ?? '');
    $login  = trim($_POST['login'] ?? '');
    $perfil = trim($_POST['perfil'] ?? 'OPERADOR');
    $senha  = trim($_POST['senha'] ?? '');
    $uid    = (int)($_POST['id'] ?? 0);

    if (!$nome)  $erros[] = 'Nome obrigatório.';
    if (!$login) $erros[] = 'Login obrigatório.';
    if (!$uid && !$senha) $erros[] = 'Senha obrigatória para novo usuário.';

    if (empty($erros)) {
        try {
            if ($uid) {
                // Atualizar Existente
                if ($senha) {
                    $hash = password_hash($senha, PASSWORD_BCRYPT);
                    pdo()->prepare("UPDATE usuarios SET nome=?, login=?, perfil=?, senha_hash=? WHERE id=?")->execute([$nome, $login, $perfil, $hash, $uid]);
                } else {
                    pdo()->prepare("UPDATE usuarios SET nome=?, login=?, perfil=? WHERE id=?")->execute([$nome, $login, $perfil, $uid]);
                }
                $sucesso = 'Usuário updated!';
                $editUser = null;
            } else {
                // Inserir Novo
                $hash = password_hash($senha, PASSWORD_BCRYPT);
                pdo()->prepare("INSERT INTO usuarios (nome, login, senha_hash, perfil, ativo) VALUES (?, ?, ?, ?, 1)")->execute([$nome, $login, $hash, $perfil]);
                $sucesso = "Usuário '$nome' cadastrado com sucesso!";
            }
        } catch (PDOException $e) {
            $erros[] = 'Erro ao processar: ' . $e->getMessage();
        }
    }
}

// Carga da listagem
$usuarios = pdo()->query("SELECT * FROM usuarios ORDER BY nome")->fetchAll();
$msg  = $_GET['msg'] ?? '';
$erro = $_GET['erro'] ?? '';

require_once __DIR__ . '/includes/header.php';
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css"/>
<style>
  :root {
    --border-premium: #1a2e50;
    --border-premium-focus: #1e3f72;
    --font-mono: 'Share Tech Mono', monospace;
  }
  
  /* Grid Layout Adaptável */
  .usuarios-grid {
    display: grid;
    grid-template-columns: 1fr 1.6fr;
    gap: 16px;
    margin-top: 5px;
  }
  @media (max-width: 992px) {
    .usuarios-grid { grid-template-columns: 1fr; }
  }

  /* Painéis de Interface */
  .panel-premium {
    background: var(--card);
    border: 1px solid var(--border-premium);
    border-radius: 12px;
    padding: 14px;
    height: fit-content;
    overflow: hidden;
  }
  .panel-header-title {
    font-size: 11px;
    font-family: var(--font-mono);
    color: var(--green);
    letter-spacing: 1.5px;
    margin-bottom: 12px;
    text-transform: uppercase;
    display: flex;
    align-items: center;
    gap: 6px;
  }

  /* Barra de Abas / Menu Superior */
  .action-tabs-bar {
    display: flex;
    background: var(--card2);
    border: 1px solid var(--border-premium);
    border-radius: 8px;
    padding: 4px;
    margin-bottom: 15px;
    gap: 4px;
  }
  .tab-item {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 10px 14px;
    font-family: var(--font-mono);
    font-size: 11px;
    letter-spacing: 1px;
    color: #4a6a8a;
    border-radius: 6px;
    text-decoration: none;
    text-transform: uppercase;
    transition: all 0.2s ease;
    border: 1px solid transparent;
  }
  .tab-item:hover { background: rgba(255, 255, 255, 0.02); color: #dde8f5; }
  .tab-item.active-add { background: rgba(16, 185, 129, 0.08); color: var(--green); border: 1px solid rgba(16, 185, 129, 0.2); }
  .tab-item.active-edit { background: rgba(0, 212, 255, 0.08); color: var(--cyan); border: 1px solid rgba(0, 212, 255, 0.2); }
  .tab-item.disabled { opacity: 0.3; cursor: not-allowed; pointer-events: none; }
  .tab-item.danger-action { color: #ef4444; }
  .tab-item.danger-action:hover { background: rgba(239, 68, 68, 0.08); border: 1px solid rgba(239, 68, 68, 0.2); }

  @media (max-width: 600px) {
    .action-tabs-bar { flex-direction: column; padding: 4px; }
    .tab-item { padding: 10px; justify-content: flex-start; }
  }

  /* Componentes de Formulário */
  .form-group-premium { margin-bottom: 12px; }
  .label-premium {
    font-size: 9px;
    font-family: var(--font-mono);
    color: #4a6a8a;
    letter-spacing: 1px;
    margin-bottom: 4px;
    display: block;
  }
  .input-premium {
    width: 100%;
    background: var(--card2);
    border: 1px solid var(--border-premium);
    border-radius: 8px;
    padding: 8px 12px;
    color: #dde8f5;
    font-family: 'Exo 2', sans-serif;
    font-size: 13px;
    outline: none;
  }
  .input-premium:focus { border-color: var(--cyan); }

  /* COMPACTAÇÃO DA TABELA HORIZONTAL */
  .table-responsive-container {
    width: 100%;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
  }
  .table-premium { 
    width: 100%; 
    border-collapse: collapse; 
    text-align: left;
  }
  .table-premium th {
    font-family: var(--font-mono);
    font-size: 10px;
    color: #4a6a8a;
    letter-spacing: 0.5px;
    padding: 8px 6px; /* Padding Reduzido */
    border-bottom: 2px solid var(--border-premium);
    text-transform: uppercase;
  }
  .table-premium td {
    padding: 8px 6px; /* Linhas mais estreitas horizontalmente */
    border-bottom: 1px solid var(--border-premium);
    font-size: 12.5px;
    vertical-align: middle;
  }
  .table-premium tr:hover td { background: rgba(255, 255, 255, 0.01); }

  /* Badges menores */
  .badge-premium {
    font-family: var(--font-mono);
    font-size: 9px;
    padding: 2px 5px;
    border-radius: 4px;
    font-weight: 600;
    display: inline-block;
  }
  .badge-premium.admin   { background: rgba(0, 212, 255, 0.08); color: var(--cyan); border: 1px solid rgba(0, 212, 255, 0.15); }
  .badge-premium.tecnico { background: rgba(168, 85, 247, 0.08); color: #a855f7; border: 1px solid rgba(168, 85, 247, 0.15); }
  .badge-premium.op      { background: rgba(245, 158, 11, 0.08); color: #f59e0b; border: 1px solid rgba(245, 158, 11, 0.15); }

  /* REGRAS DE MEDIA QUERY PARA MAXIMA COMPACTAÇÃO EM CELULARES */
  @media (max-width: 576px) {
    .table-premium th:nth-child(2), /* Oculta Coluna Login no Mobile */
    .table-premium td:nth-child(2) { 
      display: none; 
    }
    .table-premium th, .table-premium td {
      padding: 8px 4px; /* Contração máxima de área lateral */
      font-size: 12px;
    }
    .btn-text-mobile {
      display: none; /* Esconde o texto 'Selecionar' para virar apenas ícone */
    }
    .btn-action-mobile {
      padding: 6px 8px !important;
    }
  }

  /* Alertas */
  .alert-premium { padding: 10px 14px; border-radius: 8px; margin-bottom: 12px; font-size: 12.5px; }
  .alert-premium.success { background: rgba(16, 185, 129, 0.1); color: var(--green); border: 1px solid rgba(16, 185, 129, 0.2); }
  .alert-premium.danger  { background: rgba(239, 68, 68, 0.1); color: #ef4444; border: 1px solid rgba(239, 68, 68, 0.2); }
</style>

<div class="topbar">
  <button class="btn-hamburger" onclick="abrirDrawer()" aria-label="Menu">&#9776;</button>
  <div>
    <div class="page-title">◫ Usuários do Sistema</div>
    <div class="page-sub">Controle de acesso: ADMIN · OPERADOR · TÉCNICO</div>
  </div>
</div>

<div class="content">

  <?php if ($msg): ?><div class="alert-premium success"><i class="fas fa-check-circle me-2"></i> <?= e($msg) ?></div><?php endif; ?>
  <?php if ($erro): ?><div class="alert-premium danger"><i class="fas fa-exclamation-triangle me-2"></i> <?= e($erro) ?></div><?php endif; ?>
  <?php if (!empty($erros)): ?>
    <div class="alert-premium danger">
      <i class="fas fa-exclamation-triangle me-2"></i> <?= implode('<br><i class="fas fa-exclamation-triangle me-2"></i> ', array_map('e', $erros)) ?>
    </div>
  <?php endif; ?>
  <?php if ($sucesso): ?><div class="alert-premium success"><i class="fas fa-check-circle me-2"></i> <?= e($sucesso) ?></div><?php endif; ?>

  <div class="action-tabs-bar">
    <a href="usuarios.php" class="tab-item <?= !$editUser ? 'active-add' : '' ?>">
      <i class="fas fa-user-plus"></i> Incluir Novo
    </a>
    <a href="#" class="tab-item <?= $editUser ? 'active-edit' : 'disabled' ?>">
      <i class="fas fa-edit"></i> Alterar <?= $editUser ? "({$editUser['login']})" : '' ?>
    </a>
    <?php if ($editUser && $editUser['id'] != usuarioLogado()['id']): ?>
      <a href="usuarios.php?delete=1&uid=<?= (int)$editUser['id'] ?>" 
         onclick="return confirm('Deseja deletar o operador permanentemente?')" class="tab-item danger-action">
        <i class="fas fa-trash-can"></i> Excluir
      </a>
    <?php else: ?>
      <a href="#" class="tab-item disabled"><i class="fas fa-trash-can"></i> Excluir</a>
    <?php endif; ?>
  </div>

  <div class="usuarios-grid">

    <div class="panel-premium">
      <div class="panel-header-title">
        <i class="fas <?= $editUser ? 'fa-user-pen' : 'fa-user-plus' ?>"></i>
        <?= $editUser ? 'Modo de Alteração' : 'Formulário de Inclusão' ?>
      </div>
      
      <form method="post" autocomplete="off">
        <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>"/>
        <input type="hidden" name="id" value="<?= $editUser ? (int)$editUser['id'] : 0 ?>"/>
        
        <div class="form-group-premium">
          <label class="label-premium">NOME COMPLETO *</label>
          <input class="input-premium" type="text" name="nome" required value="<?= e($editUser['nome'] ?? '') ?>" placeholder="Nome"/>
        </div>
        
        <div class="form-group-premium">
          <label class="label-premium">LOGIN *</label>
          <input class="input-premium" type="text" name="login" required value="<?= e($editUser['login'] ?? '') ?>" placeholder="login" <?= $editUser ? 'readonly style="opacity: 0.5;"' : '' ?>/>
        </div>
        
        <div class="form-group-premium">
          <label class="label-premium">PERFIL</label>
          <select class="input-premium" name="perfil">
            <option value="ADMIN"    <?= ($editUser['perfil'] ?? '') === 'ADMIN' ? 'selected' : '' ?>>ADMIN</option>
            <option value="OPERADOR" <?= ($editUser['perfil'] ?? '') === 'OPERADOR' ? 'selected' : '' ?>>OPERADOR</option>
            <option value="TECNICO"  <?= ($editUser['perfil'] ?? '') === 'TECNICO' ? 'selected' : '' ?>>TÉCNICO</option>
          </select>
        </div>
        
        <div class="form-group-premium" style="margin-bottom: 16px;">
          <label class="label-premium">SENHA <?= $editUser ? '(OPCIONAL)' : '*' ?></label>
          <input class="input-premium" type="password" name="senha" <?= !$editUser ? 'required' : '' ?> placeholder="Senha"/>
        </div>
        
        <div style="display:flex; gap:6px">
          <button type="submit" class="btn btn-primary btn-sm" style="flex: 1; justify-content: center; font-weight: 700;">
            <?= $editUser ? 'Confirmar' : 'Gravar' ?>
          </button>
          <?php if ($editUser): ?>
            <a href="usuarios.php" class="btn btn-ghost btn-sm" style="border: 1px solid var(--border-premium)">Sair</a>
          <?php endif; ?>
        </div>
      </form>
    </div>

    <div class="panel-premium">
      <div class="panel-header-title"><i class="fas fa-users-gear"></i> Operadores</div>
      
      <div class="table-responsive-container">
        <table class="table-premium">
          <thead>
            <tr>
              <th>Nome</th>
              <th>Login</th>
              <th>Perfil</th>
              <th>Status</th>
              <th style="text-align: right;">Ações</th>
            </tr>
          </thead>
          <tbody>
          <?php foreach ($usuarios as $u): ?>
            <tr style="<?= ($editUser && $editUser['id'] == $u['id']) ? 'background: rgba(0, 212, 255, 0.03);' : '' ?>">
              <td><b style="color: var(--text); font-weight: 600;"><?= e($u['nome']) ?></b></td>
              <td class="mono" style="color: var(--cyan);"><?= e($u['login']) ?></td>
              <td>
                <?php
                  if ($u['perfil'] === 'ADMIN') { $badgeCls = 'admin'; $labelPf = 'ADM'; }
                  elseif ($u['perfil'] === 'TECNICO') { $badgeCls = 'tecnico'; $labelPf = 'TEC'; }
                  else { $badgeCls = 'op'; $labelPf = 'OPE'; }
                ?>
                <span class="badge-premium <?= $badgeCls ?>"><?= $labelPf ?></span>
              </td>
              <td>
                <?= $u['ativo'] 
                  ? '<span class="badge-premium" style="background:rgba(16,185,129,0.05); color:var(--green);">OK</span>' 
                  : '<span class="badge-premium" style="background:rgba(239,68,68,0.05); color:#ef4444;">BLQ</span>' 
                ?>
              </td>
              <td style="white-space:nowrap; text-align: right;">
                <a href="usuarios.php?edit=<?= (int)$u['id'] ?>" class="btn btn-ghost btn-xs btn-action-mobile" title="Editar" style="border: 1px solid var(--border-premium); margin-right: 2px; <?= ($editUser && $editUser['id'] == $u['id']) ? 'border-color: var(--cyan); color: var(--cyan);' : '' ?>">
                  <i class="fas fa-edit"></i> <span class="btn-text-mobile">Selecionar</span>
                </a>
                
                <?php if ($u['id'] != usuarioLogado()['id']): ?>
                  <a href="usuarios.php?toggle=1&uid=<?= (int)$u['id'] ?>" 
                     onclick="return confirm('Alterar status do operador?')" 
                     class="btn btn-xs btn-action-mobile" 
                     style="border: 1px solid var(--border-premium); background: none; color: <?= $u['ativo'] ? '#f59e0b' : 'var(--green)' ?>;"
                     title="Mudar Status">
                    <i class="fas <?= $u['ativo'] ? 'fa-ban' : 'fa-unlock' ?>"></i>
                  </a>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>

  </div>
</div>

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

