<?php
$title = 'Tipos de equipamento';
require_once __DIR__ . '/auth.php';
require_login();
check_csrf();

/* ---------- helpers ---------- */
function type_exists(PDO $pdo, string $name): bool {
  $st = $pdo->prepare("SELECT 1 FROM equipment_types WHERE LOWER(name)=LOWER(?) LIMIT 1");
  $st->execute([$name]);
  return (bool)$st->fetchColumn();
}

function is_admin_user(): bool {
  if (isset($_SESSION['user']['role']) && strtolower((string)$_SESSION['user']['role']) === 'admin') return true;
  if (function_exists('has_perm')) {
    try {
      if (has_perm('admin') || has_perm('admin.*') || has_perm('types.delete')) return true;
    } catch (Throwable $e) {}
  }
  return false;
}

/* ---------- POST: criar ---------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {
  $name = trim($_POST['name'] ?? '');
  // normaliza espaços internos
  $name = preg_replace('~\s+~',' ', $name);

  if ($name === '') {
    header('Location: '.base_url('types.php?err=empty')); exit;
  }

  if (type_exists($pdo, $name)) {
    header('Location: '.base_url('types.php?err=exists&name='.urlencode($name))); exit;
  }

  try {
    $st = $pdo->prepare('INSERT INTO equipment_types (name) VALUES (?)');
    $st->execute([$name]);
    header('Location: '.base_url('types.php?ok=1')); exit;
  } catch (PDOException $e) {
    // 23000 = violação de constraint (ex.: UNIQUE no banco)
    if ($e->getCode() === '23000') {
      header('Location: '.base_url('types.php?err=exists&name='.urlencode($name))); exit;
    }
    header('Location: '.base_url('types.php?err=db')); exit;
  }
}

/* ---------- POST: excluir selecionados (somente admin) ---------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete') {
  if (!is_admin_user()) { http_response_code(403); exit('Acesso negado'); }

  $ids = $_POST['ids'] ?? [];
  if (!is_array($ids) || count($ids) === 0) {
    header('Location: '.base_url('types.php?err=noids')); exit;
  }

  $ids = array_values(array_unique(array_map('intval', $ids)));
  $ids = array_filter($ids, fn($v)=>$v>0);
  if (!$ids) {
    header('Location: '.base_url('types.php?err=noids')); exit;
  }

  try {
    $ph = implode(',', array_fill(0, count($ids), '?'));
    $st = $pdo->prepare("DELETE FROM equipment_types WHERE id IN ($ph)");
    $st->execute($ids);
    header('Location: '.base_url('types.php?ok=deleted')); exit;
  } catch (PDOException $e) {
    // Se houver FK (ex.: equipment.type_id), MySQL lança 23000
    if ($e->getCode() === '23000') {
      header('Location: '.base_url('types.php?err=fk')); exit;
    }
    header('Location: '.base_url('types.php?err=db')); exit;
  }
}

/* ---------- mensagens ---------- */
$err = $_GET['err'] ?? '';
$ok  = $_GET['ok']  ?? '';
$nameQS = $_GET['name'] ?? '';

$msgErr = [
  'empty' => 'Informe o nome do tipo.',
  'exists'=> 'Já existe um tipo com esse nome'.($nameQS ? ': "'.h($nameQS).'"' : '').'.',
  'db'    => 'Erro no banco de dados. Tente novamente.',
  'noids' => 'Nenhum item selecionado para exclusão.',
  'fk'    => 'Não foi possível excluir: existem equipamentos vinculados a este tipo.',
];
$msgOk = [
  '1'       => 'Tipo adicionado com sucesso.',
  'deleted' => 'Tipos excluídos com sucesso.',
];

$isAdmin = is_admin_user();

/* ---------- lista ---------- */
$rows = $pdo->query('SELECT id, name FROM equipment_types ORDER BY name')->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">Tipos de equipamento</h2>

    <form method="post" class="d-flex gap-2">
      <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
      <input type="hidden" name="action" value="create">
      <input name="name" class="form-control" placeholder="Novo tipo" required>
      <button class="btn btn-primary">Adicionar</button>
    </form>
  </div>

  <?php if ($err && isset($msgErr[$err])): ?>
    <div class="alert alert-warning"><?= $msgErr[$err] ?></div>
  <?php endif; ?>
  <?php if ($ok && isset($msgOk[$ok])): ?>
    <div class="alert alert-success"><?= $msgOk[$ok] ?></div>
  <?php endif; ?>

  <div class="card border-0 shadow-sm">
    <div class="card-body p-0">
      <form method="post" id="formBulkDelete">
        <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
        <input type="hidden" name="action" value="delete">

        <div class="d-flex justify-content-between align-items-center p-3">
          <div class="text-muted small">Total: <?= count($rows) ?></div>
          <?php if ($isAdmin): ?>
            <button type="submit" class="btn btn-outline-danger btn-sm" id="btnDelete" disabled>
              Excluir selecionados
            </button>
          <?php endif; ?>
        </div>

        <div class="table-responsive">
          <table class="table table-hover table-striped align-middle mb-0">
            <thead>
              <tr>
                <?php if ($isAdmin): ?>
                  <th style="width:40px">
                    <input class="form-check-input" type="checkbox" id="chkAll">
                  </th>
                <?php endif; ?>
                <th>Tipo</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($rows as $r): ?>
                <tr>
                  <?php if ($isAdmin): ?>
                    <td>
                      <input class="form-check-input type-check" type="checkbox" name="ids[]" value="<?= (int)$r['id'] ?>">
                    </td>
                  <?php endif; ?>
                  <td><?= h($r['name']) ?></td>
                </tr>
              <?php endforeach; ?>
              <?php if (!$rows): ?>
                <tr>
                  <td <?= $isAdmin ? 'colspan="2"' : 'colspan="1"' ?> class="text-muted">Nenhum tipo cadastrado.</td>
                </tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
(()=> {
  const isAdmin = <?= $isAdmin ? 'true' : 'false' ?>;
  if (!isAdmin) return;

  const chkAll   = document.getElementById('chkAll');
  const checks   = Array.from(document.querySelectorAll('.type-check'));
  const btnDel   = document.getElementById('btnDelete');
  const formDel  = document.getElementById('formBulkDelete');

  function refreshBtn() {
    const any = checks.some(c => c.checked);
    if (btnDel) btnDel.disabled = !any;
  }

  if (chkAll) {
    chkAll.addEventListener('change', () => {
      checks.forEach(c => c.checked = chkAll.checked);
      refreshBtn();
    });
  }
  checks.forEach(c => c.addEventListener('change', refreshBtn));

  if (formDel) {
    formDel.addEventListener('submit', (e) => {
      const any = checks.some(c => c.checked);
      if (!any) { e.preventDefault(); return; }
      if (!confirm('Tem certeza que deseja excluir os tipos selecionados?')) {
        e.preventDefault();
      }
    });
  }
})();
</script>

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

