<?php
require_once(dirname(__DIR__) . '/config/db.php');
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);

//
// =========================================================
// ✅ BLOCO DE RETORNO JSON PARA O BOTÃO EDITAR (AJAX FETCH)
// =========================================================
if (isset($_GET['getPerms'])) {
    header('Content-Type: application/json; charset=utf-8');
    try {
        $id = (int)$_GET['getPerms'];

        // Dados do grupo
        $grupo = $pdo->prepare("
            SELECT dsgrupopermissao, descricao 
            FROM back.grupopermissao 
            WHERE cdgrupopermissao = :id
        ");
        $grupo->execute([':id' => $id]);
        $info = $grupo->fetch(PDO::FETCH_ASSOC) ?: [];

        // Permissões do grupo (corrigido: campo menu)
        $menus = $pdo->prepare("
            SELECT md5(menu) AS hash 
            FROM back.grupomenu 
            WHERE cdgrupopermissao = :id AND flacesso = true
        ");
        $menus->execute([':id' => $id]);
        $menulist = $menus->fetchAll(PDO::FETCH_ASSOC);

        echo json_encode(['info' => $info, 'menus' => $menulist]);
    } catch (Exception $e) {
        echo json_encode(['erro' => $e->getMessage()]);
    }
    exit;
}

//
// =========================================================
// FILTRO DE STATUS
// =========================================================
$filtro = $_GET['status'] ?? 'ativas';
switch ($filtro) {
    case 'inativas': $where = "WHERE flativo = 1"; break;
    case 'todas': $where = ""; break;
    default: $where = "WHERE flativo = 0";
}

//
// =========================================================
// ORDENAÇÃO
// =========================================================
$colunasPermitidas = ['cdgrupopermissao', 'dsgrupopermissao', 'descricao'];
$order = $_GET['order'] ?? 'cdgrupopermissao';
$dir = $_GET['dir'] ?? 'asc';
if (!in_array($order, $colunasPermitidas)) $order = 'cdgrupopermissao';
$dir = strtolower($dir) === 'desc' ? 'desc' : 'asc';
$nextDir = $dir === 'asc' ? 'desc' : 'asc';

function iconeSeta($coluna, $order, $dir) {
    if ($coluna !== $order) return '';
    return $dir === 'asc' ? '▲' : '▼';
}

//
// =========================================================
// PAGINAÇÃO
// =========================================================
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 100;
$page = $_GET['page'] ?? 1;
$offset = ($page - 1) * $limit;
$limitSql = $limit == -1 ? "" : "LIMIT $limit OFFSET $offset";

//
// =========================================================
// BUSCA
// =========================================================
$busca = trim($_GET['busca'] ?? '');
$whereBusca = $where;
if ($busca) {
    $whereBusca .= ($where ? " AND " : "WHERE ") . "(dsgrupopermissao ILIKE :busca OR descricao ILIKE :busca)";
}

//
// =========================================================
// CONSULTA PRINCIPAL
// =========================================================
$sql = "SELECT * FROM back.grupopermissao $whereBusca ORDER BY $order $dir $limitSql";
$stmt = $pdo->prepare($sql);
if ($busca) $stmt->bindValue(':busca', "%$busca%");
$stmt->execute();
$grupos = $stmt->fetchAll(PDO::FETCH_ASSOC);

//
// =========================================================
// MENUS DINÂMICOS
// =========================================================
$menusSistema = [];
$menusDB = $pdo->query("
    SELECT modulo, menu, modulo_php 
    FROM back.menu 
    WHERE flativo = 0 
    ORDER BY modulo, menu
")->fetchAll(PDO::FETCH_ASSOC);

foreach ($menusDB as $m) {
    $menusSistema[$m['modulo']][] = $m;
}
?>

<h4 class="mb-3"><i class="bi bi-shield-lock"></i> Grupos de Permissão</h4>
<hr>

<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <a href="?m=permissoes&status=ativas" class="btn btn-outline-success btn-sm <?= $filtro=='ativas'?'active':'' ?>">Ativos</a>
    <a href="?m=permissoes&status=inativas" class="btn btn-outline-secondary btn-sm <?= $filtro=='inativas'?'active':'' ?>">Inativos</a>
    <a href="?m=permissoes&status=todas" class="btn btn-outline-dark btn-sm <?= $filtro=='todas'?'active':'' ?>">Todos</a>
  </div>

  <div class="d-flex align-items-center">
    <form class="d-flex me-3" method="get">
      <input type="hidden" name="m" value="permissoes">
      <div class="input-group input-group-sm">
        <input class="form-control" name="busca" placeholder="Pesquisar grupo..." value="<?= htmlspecialchars($busca) ?>">
        <button class="btn btn-outline-secondary"><i class="bi bi-search"></i></button>
      </div>
    </form>

    <select class="form-select form-select-sm w-auto me-3" onchange="location.href='?m=permissoes&limit='+this.value">
      <option value="50" <?= $limit==50?'selected':'' ?>>50</option>
      <option value="100" <?= $limit==100?'selected':'' ?>>100</option>
      <option value="200" <?= $limit==200?'selected':'' ?>>200</option>
      <option value="-1" <?= $limit==-1?'selected':'' ?>>Todos</option>
    </select>

    <button class="btn btn-outline-light btn-sm border-secondary text-dark bg-light"
            data-bs-toggle="modal" data-bs-target="#modalGrupo">
      <i class="bi bi-plus-circle"></i> Novo Grupo
    </button>
  </div>
</div>

<table class="table table-striped table-hover align-middle">
  <thead class="table-dark">
    <tr>
      <th><a href="?m=permissoes&order=cdgrupopermissao&dir=<?= $nextDir ?>" class="text-white text-decoration-none">Código <?= iconeSeta('cdgrupopermissao', $order, $dir) ?></a></th>
      <th><a href="?m=permissoes&order=dsgrupopermissao&dir=<?= $nextDir ?>" class="text-white text-decoration-none">Grupo <?= iconeSeta('dsgrupopermissao', $order, $dir) ?></a></th>
      <th><a href="?m=permissoes&order=descricao&dir=<?= $nextDir ?>" class="text-white text-decoration-none">Descrição <?= iconeSeta('descricao', $order, $dir) ?></a></th>
      <th>Status</th>
      <th class="text-center">Ações</th>
    </tr>
  </thead>
  <tbody>
    <?php if ($grupos): foreach ($grupos as $g): ?>
      <tr>
        <td><?= $g['cdgrupopermissao'] ?></td>
        <td><?= htmlspecialchars($g['dsgrupopermissao']) ?></td>
        <td><?= htmlspecialchars($g['descricao']) ?></td>
        <td><?= $g['flativo']==0 ? '<span class="badge bg-success">Ativo</span>' : '<span class="badge bg-secondary">Inativo</span>' ?></td>
        <td class="text-center">
          <button class="btn btn-sm btn-outline-secondary btnEditar" data-id="<?= $g['cdgrupopermissao'] ?>"><i class="bi bi-pencil"></i></button>
          <a href="?m=permissoes&toggle=<?= $g['cdgrupopermissao'] ?>&status=<?= $filtro ?>" 
             class="btn btn-sm btn-outline-<?= $g['flativo']==0?'danger':'success' ?>" 
             title="<?= $g['flativo']==0?'Inativar':'Ativar' ?>"
             onclick="return confirm('Deseja realmente <?= $g['flativo']==0?'inativar':'ativar' ?> este grupo?')">
            <i class="bi <?= $g['flativo']==0?'bi-x-circle':'bi-check-circle' ?>"></i>
          </a>
        </td>
      </tr>
    <?php endforeach; else: ?>
      <tr><td colspan="5" class="text-center text-muted">Nenhum grupo encontrado.</td></tr>
    <?php endif; ?>
  </tbody>
</table>

<div class="d-flex justify-content-center mt-3">
  <span class="text-muted small">Exibindo <?= count($grupos) ?> registros</span>
</div>

<!-- MODAL -->
<div class="modal fade" id="modalGrupo" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <form method="post" class="modal-content" id="formGrupo">
      <div class="modal-header">
        <h5 class="modal-title">Cadastrar Grupo</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="cdgrupopermissao" id="cdgrupopermissao">
        <div class="mb-3">
          <label>Nome do Grupo *</label>
          <input type="text" class="form-control" name="dsgrupopermissao" id="dsgrupopermissao" required>
        </div>
        <div class="mb-3">
          <label>Descrição</label>
          <textarea class="form-control" name="descricao" id="descricao" rows="2"></textarea>
        </div>

        <div class="accordion" id="accordionMenus">
          <?php foreach ($menusSistema as $modulo => $menus): ?>
            <div class="accordion-item">
              <h2 class="accordion-header">
                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#col<?= md5($modulo) ?>">
                  <?= htmlspecialchars($modulo) ?>
                </button>
              </h2>
              <div id="col<?= md5($modulo) ?>" class="accordion-collapse collapse">
                <div class="accordion-body">
                  <div class="mb-2">
                    <button type="button" class="btn btn-sm btn-outline-success me-1 marcar" data-target="<?= md5($modulo) ?>">Marcar tudo</button>
                    <button type="button" class="btn btn-sm btn-outline-danger me-1 desmarcar" data-target="<?= md5($modulo) ?>">Desmarcar tudo</button>
                    <button type="button" class="btn btn-sm btn-outline-secondary inverter" data-target="<?= md5($modulo) ?>">Inverter</button>
                  </div>
                  <?php foreach ($menus as $menu): ?>
                    <div class="form-check">
                      <input class="form-check-input chkPerm perm-<?= md5($modulo) ?>" type="checkbox"
                             name="permissoes[]" value="<?= htmlspecialchars($menu['menu']) ?>"
                             id="<?= md5($menu['menu']) ?>">
                      <label class="form-check-label" for="<?= md5($menu['menu']) ?>">
                        <?= htmlspecialchars($menu['menu']) ?>
                      </label>
                    </div>
                  <?php endforeach; ?>
                </div>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      </div>
      <div class="modal-footer">
        <button type="submit" name="salvar" class="btn btn-success">Salvar</button>
      </div>
    </form>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('.btnEditar').forEach(btn => {
    btn.onclick = async () => {
      console.log('Clicou em editar ID:', btn.dataset.id);
      const id = btn.dataset.id;
      const res = await fetch(`?m=permissoes&getPerms=${id}`);
      const perms = await res.json();

      if (perms.erro) {
        alert('Erro ao buscar grupo: ' + perms.erro);
        return;
      }

      document.getElementById('cdgrupopermissao').value = id;
      document.getElementById('dsgrupopermissao').value = perms.info.dsgrupopermissao || '';
      document.getElementById('descricao').value = perms.info.descricao || '';

      document.querySelectorAll('.chkPerm').forEach(c => c.checked = false);
      perms.menus.forEach(p => {
        const el = document.getElementById(p.hash);
        if (el) el.checked = true;
      });

      const modal = new bootstrap.Modal(document.getElementById('modalGrupo'));
      modal.show();
    };
  });

  // marcar/desmarcar/inverter
  document.querySelectorAll('.marcar, .desmarcar, .inverter').forEach(btn => {
    btn.onclick = () => {
      const target = btn.dataset.target;
      const checks = document.querySelectorAll('.perm-' + target);
      if (btn.classList.contains('marcar')) checks.forEach(c => c.checked = true);
      else if (btn.classList.contains('desmarcar')) checks.forEach(c => c.checked = false);
      else checks.forEach(c => c.checked = !c.checked);
    };
  });
});
</script>

<?php
//
// =========================================================
// TOGGLE ATIVAR/INATIVAR
// =========================================================
if (isset($_GET['toggle'])) {
    $id = (int)$_GET['toggle'];
    $pdo->prepare("
        UPDATE back.grupopermissao 
        SET flativo = CASE WHEN flativo = 0 THEN 1 ELSE 0 END 
        WHERE cdgrupopermissao = ?
    ")->execute([$id]);
    header("Location: ?m=permissoes&status=" . urlencode($filtro));
    exit;
}

//
// =========================================================
// SALVAR / ATUALIZAR GRUPO
// =========================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['salvar'])) {
    try {
        $nome = trim($_POST['dsgrupopermissao']);
        $desc = trim($_POST['descricao']);
        $id = isset($_POST['cdgrupopermissao']) && $_POST['cdgrupopermissao'] !== '' 
              ? (int)$_POST['cdgrupopermissao'] 
              : null;

        if ($id !== null) {
            $stmt = $pdo->prepare("
                UPDATE back.grupopermissao 
                SET dsgrupopermissao = :n, descricao = :d 
                WHERE cdgrupopermissao = :id
            ");
            $stmt->execute([':n' => $nome, ':d' => $desc, ':id' => $id]);
            $pdo->prepare("DELETE FROM back.grupomenu WHERE cdgrupopermissao = ?")->execute([$id]);
        } else {
            $stmt = $pdo->prepare("
                INSERT INTO back.grupopermissao (dsgrupopermissao, descricao, flativo) 
                VALUES (:n, :d, 0) RETURNING cdgrupopermissao
            ");
            $stmt->execute([':n' => $nome, ':d' => $desc]);
            $id = $stmt->fetchColumn();
        }

        $menus = $pdo->query("
            SELECT modulo, menu, modulo_php 
            FROM back.menu 
            WHERE flativo = 0 
            ORDER BY modulo, menu
        ")->fetchAll(PDO::FETCH_ASSOC);
        $permissoesMarcadas = $_POST['permissoes'] ?? [];

        $insert = $pdo->prepare("
            INSERT INTO back.grupomenu (cdgrupopermissao, modulo, menu, flacesso) 
            VALUES (:g, :m, :n, :a)
        ");
        foreach ($menus as $m) {
            $acesso = in_array($m['menu'], $permissoesMarcadas);
            $insert->bindValue(':g', $id, PDO::PARAM_INT);
            $insert->bindValue(':m', $m['modulo']);
            $insert->bindValue(':n', $m['menu']);
            $insert->bindValue(':a', $acesso, PDO::PARAM_BOOL);
            $insert->execute();
        }

        echo "<script>alert('✅ Grupo salvo com sucesso!'); window.location='?m=permissoes';</script>";
    } catch (Exception $e) {
        echo "<pre>Erro ao salvar: " . $e->getMessage() . "</pre>";
    }
}
?>
