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

// =====================================
// CONFIGURAÇÕES GERAIS
// =====================================
$titulo = "Cadastro de Empresas";
$icone = "bi-building";

// =====================================
// FILTROS / ORDENAÇÃO / PAGINAÇÃO
// =====================================
$filtro = $_GET['status'] ?? 'ativas';
$order = $_GET['order'] ?? 'cdempresa';
$dir = strtolower($_GET['dir'] ?? 'asc');
$dir = $dir === 'desc' ? 'desc' : 'asc';
$nextDir = $dir === 'asc' ? 'desc' : 'asc';
$limit = (int)($_GET['limit'] ?? 100);
$page = (int)($_GET['page'] ?? 1);
$offset = ($page - 1) * $limit;
$busca = trim($_GET['busca'] ?? '');

// =====================================
// FILTROS
// =====================================
$where = [];
$params = [];

if ($filtro === 'ativas') $where[] = "e.flativo = 0";
elseif ($filtro === 'inativas') $where[] = "e.flativo = 1";

if ($busca) {
    $where[] = "(e.dsempresa ILIKE :busca OR e.dsapelido ILIKE :busca OR p.dspais ILIKE :busca OR e.cnpj ILIKE :busca)";
    $params[':busca'] = "%$busca%";
}

$whereSql = $where ? "WHERE " . implode(" AND ", $where) : "";
$limitSql = ($limit === -1) ? "" : "LIMIT $limit OFFSET $offset";

// =====================================
// CONSULTA PRINCIPAL
// =====================================
$sql = "SELECT e.*, p.dspais, m.dsmoeda
        FROM back.empresa e
        LEFT JOIN back.pais p ON p.cdpais = e.cdpais
        LEFT JOIN back.moeda m ON m.cdmoeda = e.cdmoeda
        $whereSql
        ORDER BY $order $dir
        $limitSql";

$stmt = $pdo->prepare($sql);
foreach ($params as $k => $v) $stmt->bindValue($k, $v);
$stmt->execute();
$empresas = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Contagem total (mantido para compatibilidade futura)
$sqlCount = "SELECT COUNT(*) FROM back.empresa e
             LEFT JOIN back.pais p ON p.cdpais = e.cdpais
             $whereSql";
$stmtCount = $pdo->prepare($sqlCount);
foreach ($params as $k => $v) $stmtCount->bindValue($k, $v);
$stmtCount->execute();
$total = $stmtCount->fetchColumn();

$paises = $pdo->query("SELECT * FROM back.pais ORDER BY dspais")->fetchAll(PDO::FETCH_ASSOC);
$moedas = $pdo->query("SELECT * FROM back.moeda WHERE flativo=0 ORDER BY dsmoeda")->fetchAll(PDO::FETCH_ASSOC);

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

<h4 class="mb-3"><i class="bi <?= $icone ?>"></i> <?= $titulo ?></h4>
<hr>

<!-- FILTROS E NOVO -->
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
  <div class="btn-group">
    <a href="?m=empresas&status=ativas" class="btn btn-outline-success btn-sm <?= $filtro=='ativas'?'active':'' ?>">Ativas</a>
    <a href="?m=empresas&status=inativas" class="btn btn-outline-secondary btn-sm <?= $filtro=='inativas'?'active':'' ?>">Inativas</a>
    <a href="?m=empresas&status=todas" class="btn btn-outline-dark btn-sm <?= $filtro=='todas'?'active':'' ?>">Todas</a>
  </div>

  <form method="get" class="d-flex align-items-center gap-2 flex-grow-1 justify-content-center" style="max-width:500px;">
    <input type="hidden" name="m" value="empresas">
    <input type="hidden" name="status" value="<?= $filtro ?>">
    <div class="input-group input-group-sm w-100">
      <span class="input-group-text bg-white"><i class="bi bi-search text-secondary"></i></span>
      <input type="text" name="busca" class="form-control"
             placeholder="Pesquisar empresa, apelido, país ou CNPJ..."
             value="<?= htmlspecialchars($busca) ?>">
      <button class="btn btn-outline-primary" type="submit">Buscar</button>
    </div>
  </form>

  <button class="btn btn-outline-light btn-sm border-secondary text-dark bg-light"
          data-bs-toggle="modal" data-bs-target="#modalEmpresa" id="novaEmpresaBtn">
      <i class="bi bi-plus-circle"></i> Nova Empresa
  </button>
</div>

<!-- TABELA -->
<div class="table-responsive">
<table class="table table-striped table-hover align-middle">
  <thead class="table-dark">
    <tr>
      <th><a href="?m=empresas&order=cdempresa&dir=<?= $nextDir ?>" class="text-white text-decoration-none"># <?= iconeSeta('cdempresa',$order,$dir)?></a></th>
      <th><a href="?m=empresas&order=dsempresa&dir=<?= $nextDir ?>" class="text-white text-decoration-none">Nome <?= iconeSeta('dsempresa',$order,$dir)?></a></th>
      <th>Apelido</th>
      <th><a href="?m=empresas&order=dspais&dir=<?= $nextDir ?>" class="text-white text-decoration-none">País <?= iconeSeta('dspais',$order,$dir)?></a></th>
      <th>Documento</th>
      <th>Telefone</th>
      <th>Moeda</th>
      <th>Integração</th>
      <th>Status</th>
      <th class="text-center">Ações</th>
    </tr>
  </thead>
  <tbody>
    <?php if ($empresas): foreach ($empresas as $e): ?>
    <tr>
      <td><?= $e['cdempresa'] ?></td>
      <td><?= htmlspecialchars($e['dsempresa']) ?></td>
      <td><?= htmlspecialchars($e['dsapelido']) ?></td>
      <td><?= htmlspecialchars($e['dspais']) ?></td>
      <td><?= htmlspecialchars($e['cnpj']) ?></td>
      <td><?= htmlspecialchars($e['telefone']) ?></td>
      <td><?= htmlspecialchars($e['dsmoeda']) ?></td>
      <td><?= htmlspecialchars($e['cdintegracao']) ?></td>
      <td><?= $e['flativo']==0 ? '<span class="badge bg-success">Ativa</span>' : '<span class="badge bg-secondary">Inativa</span>' ?></td>
      <td class="text-center">
        <button class="btn btn-sm btn-outline-secondary btnEditar"
                data-empresa='<?= json_encode($e, JSON_HEX_APOS|JSON_HEX_QUOT) ?>'>
            <i class="bi bi-pencil"></i>
        </button>
        <a href="?m=empresas_actions&inativar=<?= $e['cdempresa'] ?>&status=<?= $filtro ?>" 
           class="btn btn-sm <?= $e['flativo']==0 ? 'btn-outline-danger' : 'btn-outline-success' ?> "
           onclick="return confirm('Deseja realmente <?= $e['flativo']==0?'inativar':'reativar' ?> esta empresa?')">
           <i class="bi <?= $e['flativo']==0 ? 'bi-power' : 'bi-arrow-repeat' ?>"></i>
        </a>
      </td>
    </tr>
    <?php endforeach; else: ?>
      <tr><td colspan="10" class="text-center text-muted">Nenhuma empresa encontrada.</td></tr>
    <?php endif; ?>
  </tbody>
</table>
</div>

<!-- MODAL CADASTRO -->
<div class="modal fade" id="modalEmpresa" tabindex="-1" aria-labelledby="modalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <form method="post" action="?m=empresas_actions" class="modal-content" id="formEmpresa">

      <div class="modal-header">
        <h5 class="modal-title" id="modalLabel">Cadastrar Empresa</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body">

        <!-- name corrigido, id mantido -->
        <input type="hidden" name="empresa_id" id="cdempresa">

        <div class="row g-3">
          <div class="col-md-6">
            <label>Nome *</label>
            <input type="text" class="form-control" name="dsempresa" id="dsempresa" required>
          </div>
          <div class="col-md-6">
            <label>Apelido</label>
            <input type="text" class="form-control" name="dsapelido" id="dsapelido" maxlength="4" pattern="[A-Za-z0-9]{1,4}">
          </div>
          <div class="col-md-3">
            <label>País *</label>
            <div class="input-group">
              <select class="form-select" name="cdpais" id="cdpais" required>
                <option value="">Selecione</option>
                <?php foreach ($paises as $p): ?>
                  <option value="<?= $p['cdpais'] ?>"><?= htmlspecialchars($p['dspais']) ?></option>
                <?php endforeach; ?>
              </select>
              <button class="btn btn-outline-secondary" type="button" id="btnAddPais"><i class="bi bi-plus"></i></button>
            </div>
          </div>
          <div class="col-md-3">
            <label>Moeda *</label>
            <select class="form-select" name="cdmoeda" id="cdmoeda" required>
              <option value="">Selecione</option>
              <?php foreach ($moedas as $m): ?>
                <option value="<?= $m['cdmoeda'] ?>"><?= htmlspecialchars($m['dsmoeda']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-4">
            <label>Documento</label>
            <input type="text" class="form-control" name="cnpj" id="cnpj">
          </div>
          <div class="col-md-4">
            <label>Telefone</label>
            <input type="text" class="form-control" name="telefone" id="telefone">
          </div>
          <div class="col-md-4">
            <label>Código Integração</label>
            <input type="text" class="form-control" name="cdintegracao" id="cdintegracao">
          </div>
          <div class="col-md-3">
            <label>CEP</label>
            <div class="input-group">
              <input type="text" class="form-control" name="cep" id="cep">
              <button class="btn btn-outline-secondary" type="button" id="buscarCEP"><i class="bi bi-search"></i></button>
            </div>
          </div>
          <div class="col-md-3">
            <label>Inscrição Estadual (Brasil)</label>
            <input type="text" class="form-control" name="inscricao_estadual" id="inscricao_estadual">
          </div>
          <div class="col-md-5">
            <label>Logradouro</label>
            <input type="text" class="form-control" name="logradouro" id="logradouro">
          </div>
          <div class="col-md-2">
            <label>Número</label>
            <input type="text" class="form-control" name="numero" id="numero">
          </div>
          <div class="col-md-5">
            <label>Bairro</label>
            <input type="text" class="form-control" name="bairro" id="bairro">
          </div>
          <div class="col-md-4">
            <label>Cidade</label>
            <input type="text" class="form-control" name="cidade" id="cidade">
          </div>
          <div class="col-md-2">
            <label>Estado</label>
            <input type="text" maxlength="2" class="form-control" name="estado" id="estado">
          </div>
          <div class="col-md-4">
            <label>E-mail</label>
            <input type="email" class="form-control" name="email" id="email">
          </div>
        </div>
      </div>

      <div class="modal-footer">
        <button type="submit" name="salvar" class="btn btn-success">Salvar</button>
      </div>

    </form>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<script>
$('#buscarCEP').on('click', function() {
  const cep = $('#cep').val().replace(/\D/g, '');
  if (cep.length !== 8) return alert('CEP inválido!');
  fetch(`https://viacep.com.br/ws/${cep}/json/`)
    .then(r => r.json())
    .then(d => {
      if (d.erro) return alert('CEP não encontrado!');
      $('#logradouro').val(d.logradouro);
      $('#bairro').val(d.bairro);
      $('#cidade').val(d.localidade);
      $('#estado').val(d.uf);
    });
});

$('.btnEditar').on('click', function() {
  const e = $(this).data('empresa');
  for (const k in e) $('#' + k).val(e[k]);
  $('#modalLabel').text('Editar Empresa');
  $('#modalEmpresa').modal('show');
});

$('#novaEmpresaBtn').on('click', function() {
  $('#formEmpresa')[0].reset();
  $('#cdempresa').val('');
  $('#modalLabel').text('Cadastrar Empresa');
});
</script>
