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

/* Admin? (cobre role e/ou permissão) */
$isAdmin = (($_SESSION['user']['role'] ?? '') === 'admin');
if (function_exists('user_has_perm')) {
  $isAdmin = $isAdmin || user_has_perm('admin') || user_has_perm('admin.*');
}

/* CREATE / UPDATE / DELETE */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $act = $_POST['act'] ?? '';

  try {
    if ($act === 'create') {
      // criação permitida para qualquer usuário autenticado
      $name = trim($_POST['name'] ?? '');
      $parent = ($_POST['parent_id'] ?? '') !== '' ? (int)$_POST['parent_id'] : null;
      $type = trim($_POST['type'] ?? 'SITE');
      if ($name === '') throw new RuntimeException('Informe o nome do local.');
      $st = $pdo->prepare("INSERT INTO locations (name, parent_id, type) VALUES (?,?,?)");
      $st->execute([$name, $parent, $type]);
      $_SESSION['flash_ok'] = 'Local criado com sucesso.';

    } elseif ($act === 'update') {
      if (!$isAdmin) throw new RuntimeException('Apenas administradores podem editar locais.');
      $id = (int)($_POST['id'] ?? 0);
      $name = trim($_POST['name'] ?? '');
      $parent = ($_POST['parent_id'] ?? '') !== '' ? (int)$_POST['parent_id'] : null;
      $type = trim($_POST['type'] ?? 'SITE');
      if ($id <= 0) throw new RuntimeException('ID inválido.');
      if ($name === '') throw new RuntimeException('Informe o nome do local.');
      if ($parent === $id) throw new RuntimeException('O local pai não pode ser o próprio registro.');
      $st = $pdo->prepare("UPDATE locations SET name=?, parent_id=?, type=? WHERE id=?");
      $st->execute([$name, $parent, $type, $id]);
      $_SESSION['flash_ok'] = 'Local atualizado com sucesso.';

    } elseif ($act === 'delete') {
      if (!$isAdmin) throw new RuntimeException('Apenas administradores podem excluir locais.');
      $id = (int)($_POST['id'] ?? 0);
      if ($id <= 0) throw new RuntimeException('ID inválido.');
      $st = $pdo->prepare("DELETE FROM locations WHERE id=?");
      $st->execute([$id]);
      $_SESSION['flash_ok'] = 'Local excluído com sucesso.';
    }
  } catch (Throwable $e) {
    $_SESSION['flash_error'] = 'Erro: ' . $e->getMessage();
  }

  header('Location: ' . base_url('locations.php'));
  exit;
}

/* LISTA */
$locs = $pdo->query("SELECT * FROM locations ORDER BY (parent_id IS NOT NULL), parent_id, name")->fetchAll(PDO::FETCH_ASSOC);

/* Mapa id => nome para resolver “Pai” sem custo O(n²) */
$mapNames = [];
foreach ($locs as $L) $mapNames[(int)$L['id']] = $L['name'] ?? '';

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">Locais</h2>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#novo">
      <i class="bi bi-plus-lg me-1"></i>Novo
    </button>
  </div>

  <?php if (!empty($_SESSION['flash_error'])): ?>
    <div class="alert alert-danger py-2"><?= h($_SESSION['flash_error']) ?></div>
    <?php unset($_SESSION['flash_error']); ?>
  <?php endif; ?>
  <?php if (!empty($_SESSION['flash_ok'])): ?>
    <div class="alert alert-success py-2"><?= h($_SESSION['flash_ok']) ?></div>
    <?php unset($_SESSION['flash_ok']); ?>
  <?php endif; ?>

  <div class="table-responsive">
    <table class="table table-hover table-striped align-middle">
      <thead>
        <tr>
          <!-- ID oculto na UI -->
          <th>Nome</th>
          <th>Tipo</th>
          <th>Pai</th>
          <th class="text-end">Ações</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($locs as $l): ?>
          <tr>
            <td><?= h($l['name']) ?></td>
            <td><?= h($l['type']) ?></td>
            <td><?= h($l['parent_id'] ? ($mapNames[(int)$l['parent_id']] ?? '—') : '—') ?></td>
            <td class="text-end">
              <?php if ($isAdmin): ?>
                <button class="btn btn-sm btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#edit<?= (int)$l['id'] ?>">Editar</button>
                <form method="post" class="d-inline" onsubmit="return confirm('Excluir este local?');">
                  <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
                  <input type="hidden" name="act" value="delete">
                  <input type="hidden" name="id" value="<?= (int)$l['id'] ?>">
                  <button class="btn btn-sm btn-outline-danger">Excluir</button>
                </form>
              <?php else: ?>
                <button class="btn btn-sm btn-outline-secondary" disabled title="Apenas administradores podem editar">Editar</button>
                <button class="btn btn-sm btn-outline-danger" disabled title="Apenas administradores podem excluir">Excluir</button>
              <?php endif; ?>
            </td>
          </tr>

          <!-- Modal Editar (apenas abre para admin) -->
          <?php if ($isAdmin): ?>
          <div class="modal fade" id="edit<?= (int)$l['id'] ?>" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog">
              <form class="modal-content" method="post">
                <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
                <input type="hidden" name="act" value="update">
                <input type="hidden" name="id" value="<?= (int)$l['id'] ?>">
                <div class="modal-header">
                  <h5 class="modal-title">Editar local</h5>
                  <button class="btn-close" data-bs-dismiss="modal" aria-label="Fechar"></button>
                </div>
                <div class="modal-body">
                  <div class="mb-3">
                    <label class="form-label">Nome</label>
                    <input name="name" class="form-control" value="<?= h($l['name']) ?>" required>
                  </div>
                  <div class="mb-3">
                    <label class="form-label">Tipo</label>
                    <select name="type" class="form-select">
                      <?php foreach (['SITE','SALA','ARMARIO','PRATELEIRA','TRANSITO'] as $t): ?>
                        <option <?= ($l['type'] === $t ? 'selected' : '') ?>><?= h($t) ?></option>
                      <?php endforeach; ?>
                    </select>
                  </div>
                  <div class="mb-3">
                    <label class="form-label">Local pai</label>
                    <select name="parent_id" class="form-select">
                      <option value="">—</option>
                      <?php foreach ($locs as $p): if ($p['id'] != $l['id']): ?>
                        <option value="<?= (int)$p['id'] ?>" <?= ((int)$l['parent_id'] === (int)$p['id'] ? 'selected' : '') ?>>
                          <?= h($p['name']) ?>
                        </option>
                      <?php endif; endforeach; ?>
                    </select>
                  </div>
                </div>
                <div class="modal-footer">
                  <button class="btn btn-primary">Salvar</button>
                </div>
              </form>
            </div>
          </div>
          <?php endif; ?>
        <?php endforeach; ?>
        <?php if (!$locs): ?>
          <tr><td colspan="4" class="text-muted">Nenhum local cadastrado.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- Modal Novo -->
<div class="modal fade" id="novo" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <form class="modal-content" method="post">
      <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
      <input type="hidden" name="act" value="create">
      <div class="modal-header">
        <h5 class="modal-title">Novo local</h5>
        <button class="btn-close" data-bs-dismiss="modal" aria-label="Fechar"></button>
      </div>
      <div class="modal-body">
        <div class="mb-3">
          <label class="form-label">Nome</label>
          <input name="name" class="form-control" required>
        </div>
        <div class="mb-3">
          <label class="form-label">Tipo</label>
          <select name="type" class="form-select">
            <?php foreach (['SITE','SALA','ARMARIO','PRATELEIRA','TRANSITO'] as $t): ?>
              <option><?= h($t) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="mb-3">
          <label class="form-label">Local pai</label>
          <select name="parent_id" class="form-select">
            <option value="">—</option>
            <?php foreach ($locs as $p): ?>
              <option value="<?= (int)$p['id'] ?>"><?= h($p['name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary">Salvar</button>
      </div>
    </form>
  </div>
</div>

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

