<?php
$title = 'Operações';
require_once __DIR__ . '/auth.php';
require_login();
check_csrf();

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

function is_admin_user(): bool {
  // tenta via role na sessão
  if (isset($_SESSION['user']['role']) && strtolower((string)$_SESSION['user']['role']) === 'admin') return true;
  // se existir um verificador de permissão no projeto, tenta também
  if (function_exists('has_perm')) {
    try {
      if (has_perm('admin') || has_perm('admin.*') || has_perm('operations.delete')) return true;
    } catch (Throwable $e) {}
  }
  return false;
}

/* ---------- POST: criar ---------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {
  $name = trim($_POST['name'] ?? '');

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

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

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

  // sanitiza para inteiros
  $ids = array_values(array_unique(array_map('intval', $ids)));
  $ids = array_filter($ids, fn($v)=>$v>0);

  if (!$ids) {
    header('Location: '.base_url('operations.php?err=noids')); exit;
  }

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

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

$msgErr = [
  'empty' => 'Informe o nome da operação.',
  'exists'=> 'Já existe uma operação 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 registros vinculados (ex.: colaboradores).',
];
$msgOk = [
  '1'       => 'Operação adicionada com sucesso.',
  'deleted' => 'Operações excluídas com sucesso.',
];

$isAdmin = is_admin_user();

/* ---------- lista ---------- */
$rows = $pdo->query('SELECT id, name FROM operations 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">Operações / Departamentos</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="Nova operação" 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>Operação</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($rows as $r): ?>
                <tr>
                  <?php if ($isAdmin): ?>
                    <td>
                      <input class="form-check-input op-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">Nenhuma operação cadastrada.</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('.op-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 as operações selecionadas?')) {
        e.preventDefault();
      }
    });
  }
})();
</script>

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

