<?php
include 'verifica_login.php'; // Verificar se está logado
include 'conexao.php';
$baseUtils = __DIR__ . '/config/base_utils.php';
if (!is_file($baseUtils)) {
    die('Arquivo obrigatorio nao encontrado: config/base_utils.php');
}
require_once $baseUtils;

if (!function_exists('garantir_estrutura_bases')) {
    die('Funcao obrigatoria nao carregada: garantir_estrutura_bases');
}
$conn = conectar_banco();
garantir_estrutura_bases($conn);

// Salvar (INSERT ou UPDATE)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['acao']) && $_POST['acao'] === 'ativar_todas_empresas') {
        $sql_ativar_todas = "UPDATE empresas SET ATIVA = 'S'";
        $conn->query($sql_ativar_todas);
        header('Location: empresas.php?msg=sucesso');
        exit;
    }

    $id = !empty($_POST['id_emp']) ? (int)$_POST['id_emp'] : 0;

    $cnpj = $_POST['cnpj'] ?? '';
    $nome_fantasia = $_POST['nome_fantasia'] ?? '';
    $empresa = $_POST['empresa'] ?? '';
    $rua = $_POST['rua'] ?? '';
    $numero = $_POST['numero'] ?? '';
    $compl_num = $_POST['compl_num'] ?? '';
    $bairro = $_POST['bairro'] ?? '';
    $cidade = $_POST['cidade'] ?? '';
    $uf = $_POST['uf'] ?? '';
    $cep = $_POST['cep'] ?? '';
    $ddd = $_POST['ddd'] ?? '';
    $tel = $_POST['tel'] ?? '';
    $cnae = $_POST['cnae'] ?? '';
    $funcionarios = $_POST['funcionarios'] ?? '';
    $site = $_POST['site'] ?? '';
    $idbase = (int)($_POST['idbase'] ?? 0);
    $base = obter_nome_base_por_id($conn, $idbase);
    $porte = $_POST['porte'] ?? '';
    $ativa = $_POST['ativa'] ?? '';

    if ($idbase <= 0 || $base === '') {
        header('Location: empresas.php?msg=erro_importacao&detalhe=' . urlencode('Selecione uma base válida para a empresa.') . '&total=0');
        exit;
    }

    if ($id) {
        $sql = "UPDATE empresas SET CNPJ=?, NOME_FANTASIA=?, EMPRESA=?, RUA=?, NUMERO=?, COMPL_NUM=?, BAIRRO=?, CIDADE=?, UF=?, CEP=?, DDD=?, TEL=?, CNAE=?, FUNCIONARIOS=?, SITE=?, BASE=?, idbase=?, PORTE=?, ATIVA=? WHERE ID_EMPRESA=?";
        $stmt = $conn->prepare($sql);
        if ($stmt) {
            $types = str_repeat('s', 16) . 'i' . str_repeat('s', 2) . 'i';
            // build values in same order as SQL
            $values = [
                $cnpj, $nome_fantasia, $empresa, $rua, $numero, $compl_num, $bairro, $cidade, $uf, $cep, $ddd, $tel, $cnae,
                $funcionarios, $site, $base, $idbase, $porte, $ativa,
                $id
            ];
            $stmt->bind_param($types, ...$values);
            $stmt->execute();
            $stmt->close();
        }
    } else {
        $sql = "INSERT INTO empresas (CNPJ, NOME_FANTASIA, EMPRESA, RUA, NUMERO, COMPL_NUM, BAIRRO, CIDADE, UF, CEP, DDD, TEL, CNAE, FUNCIONARIOS, SITE, BASE, idbase, PORTE, ATIVA)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $conn->prepare($sql);
        if ($stmt) {
            $types = str_repeat('s', 16) . 'i' . str_repeat('s', 2);
            $values = [
                $cnpj, $nome_fantasia, $empresa, $rua, $numero, $compl_num, $bairro, $cidade, $uf, $cep, $ddd, $tel, $cnae,
                $funcionarios, $site, $base, $idbase, $porte, $ativa
            ];
            $stmt->bind_param($types, ...$values);
            $stmt->execute();
            $stmt->close();
        }
    }

    header('Location: empresas.php?msg=sucesso');
    exit;
}

// Se action=edit -> carregar registro (ou formulário em branco para novo)
$action = $_GET['action'] ?? '';
$id_edit = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$empresa_row = null;
if ($action === 'edit' && $id_edit) {
    $stmt = $conn->prepare("SELECT ID_EMPRESA, CNPJ, NOME_FANTASIA, EMPRESA, RUA, NUMERO, COMPL_NUM, BAIRRO, CIDADE, UF, CEP, DDD, TEL, CNAE, FUNCIONARIOS, SITE, BASE, idbase, PORTE, ATIVA FROM empresas WHERE ID_EMPRESA = ?");
    $stmt->bind_param('i', $id_edit);
    $stmt->execute();
    $empresa_row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
}

// Bases disponíveis para filtros e seleção
$bases_disponiveis = listar_bases($conn, true);
$bases_por_id = [];
foreach ($bases_disponiveis as $b) {
    $bases_por_id[(int)$b['idbase']] = $b['nome_base'];
}

// Listagem com filtros opcionais
$f_id      = isset($_GET['f_id']) ? (int)$_GET['f_id'] : null;
$f_emp     = trim($_GET['f_empresa'] ?? '');
$f_nome    = trim($_GET['f_nome_fantasia'] ?? '');
$f_cnpj    = trim($_GET['f_cnpj'] ?? '');
$f_cidade  = trim($_GET['f_cidade'] ?? '');
$f_uf      = trim($_GET['f_uf'] ?? '');
$f_func    = trim($_GET['f_funcionarios'] ?? '');
$f_idbase  = (int)($_GET['f_idbase'] ?? 0);

if ($f_idbase <= 0 && isset($_GET['f_base']) && ctype_digit((string)$_GET['f_base'])) {
    $f_idbase = (int)$_GET['f_base'];
}

$base_selecionada = $bases_por_id[$f_idbase] ?? '';
$modo_lista = ($action !== 'edit');
$base_foi_escolhida = ($f_idbase > 0 && $base_selecionada !== '');

// Paginação
$por_pagina = isset($_GET['por_pagina']) ? (int)$_GET['por_pagina'] : 10;
if (!in_array($por_pagina, [10, 50, 100])) {
    $por_pagina = 10;
}
$pagina_atual = isset($_GET['pagina']) ? max(1, (int)$_GET['pagina']) : 1;
$offset = ($pagina_atual - 1) * $por_pagina;

$where = [];
$types = '';
$bind  = [];

if ($f_id) {
    $where[] = 'ID_EMPRESA = ?';
    $types  .= 'i';
    $bind[]  = $f_id;
}
if ($f_emp !== '') {
    $where[] = 'EMPRESA LIKE ?';
    $types  .= 's';
    $bind[]  = '%' . $f_emp . '%';
}
if ($f_nome !== '') {
    $where[] = 'NOME_FANTASIA LIKE ?';
    $types  .= 's';
    $bind[]  = '%' . $f_nome . '%';
}
if ($f_cnpj !== '') {
    $where[] = 'CNPJ LIKE ?';
    $types  .= 's';
    $bind[]  = '%' . $f_cnpj . '%';
}
if ($f_cidade !== '') {
    $where[] = 'CIDADE LIKE ?';
    $types  .= 's';
    $bind[]  = '%' . $f_cidade . '%';
}
if ($f_uf !== '') {
    $where[] = 'UF = ?';
    $types  .= 's';
    $bind[]  = $f_uf;
}
if ($f_func !== '') {
    $where[] = 'FUNCIONARIOS = ?';
    $types  .= 's';
    $bind[]  = $f_func;
}
if ($f_idbase > 0) {
    $where[] = 'idbase = ?';
    $types  .= 'i';
    $bind[]  = $f_idbase;
}

// Contar total de registros
$sql_count = "SELECT COUNT(*) as total FROM empresas";
if ($where) {
    $sql_count .= ' WHERE ' . implode(' AND ', $where);
}
$total_registros = 0;
$total_paginas = 0;
$res = false;

if (!$modo_lista || $base_foi_escolhida) {
    if ($where && $types) {
        $stmt_count = $conn->prepare($sql_count);
        $stmt_count->bind_param($types, ...$bind);
        $stmt_count->execute();
        $total_registros = $stmt_count->get_result()->fetch_assoc()['total'];
        $stmt_count->close();
    } else {
        $total_registros = $conn->query($sql_count)->fetch_assoc()['total'];
    }

    $total_paginas = max(1, (int)ceil($total_registros / $por_pagina));

    $sql_list = "SELECT ID_EMPRESA, CNPJ, NOME_FANTASIA, EMPRESA, RUA, NUMERO, COMPL_NUM, BAIRRO, CIDADE, UF, CEP, DDD, TEL, CNAE, FUNCIONARIOS, SITE, BASE, idbase, PORTE, ATIVA FROM empresas";
    if ($where) {
        $sql_list .= ' WHERE ' . implode(' AND ', $where);
    }
    $sql_list .= ' ORDER BY EMPRESA ASC LIMIT ? OFFSET ?';

    if ($where && $types) {
        $stmt_list = $conn->prepare($sql_list);
        $types_with_limit = $types . 'ii';
        $bind_with_limit = array_merge($bind, [$por_pagina, $offset]);
        $stmt_list->bind_param($types_with_limit, ...$bind_with_limit);
        $stmt_list->execute();
        $res = $stmt_list->get_result();
    } else {
        $stmt_list = $conn->prepare($sql_list);
        $stmt_list->bind_param('ii', $por_pagina, $offset);
        $stmt_list->execute();
        $res = $stmt_list->get_result();
    }
}

// Buscar lista de status de contato (fallback seguro caso a tabela ainda nao exista)
$contato_status_opcoes = [];
$stmt_contato_status = $conn->prepare("SELECT idcontato_status, contato_status FROM contato_status ORDER BY contato_status");
if ($stmt_contato_status) {
    $stmt_contato_status->execute();
    $res_contato_status = $stmt_contato_status->get_result();
    while ($row_cs = $res_contato_status->fetch_assoc()) {
        $contato_status_opcoes[] = $row_cs;
    }
    $stmt_contato_status->close();
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<title>Empresas - Listagem e Edição</title>
<style>
    body{ font-family: Arial, sans-serif; background:#f4f4f4; padding:20px; }
    .container{ max-width:1100px; margin:0 auto; background:white; padding:20px; border-radius:6px; box-shadow:0 2px 6px rgba(0,0,0,0.08); }
    table{ width:100%; border-collapse:collapse; }
    th,td{ padding:8px 10px; border-bottom:1px solid #eee; }
    th{ background:#004d99; color:white; text-align:left; }
    .actions a{ margin-right:6px; text-decoration:none; padding:6px 10px; border-radius:4px; color:white; }
    .btn-edit{ background:#f57c00; }
    .btn-new{ background:#2e7d32; color:white; padding:8px 12px; border-radius:4px; text-decoration:none; }
    .btn-activate-all{ background:#00897b; color:white; padding:8px 12px; border-radius:4px; border:none; cursor:pointer; }
    .form-row{ display:flex; gap:10px; }
    .form-row > div{ flex:1; }
    label{ display:block; font-weight:bold; margin-bottom:4px; }
    input[type=text], input[type=number], select{ width:100%; padding:6px 8px; border:1px solid #ccc; border-radius:4px; }
    .msg{ padding:8px; background:#e8f5e9; color:#1b5e20; border-radius:4px; margin-bottom:10px; }
</style>
</head>
<body>
<div class="container">
    <h1>Empresas</h1>
    <div style="margin-bottom:12px; display: flex; gap: 10px; flex-wrap: wrap;">
        <a href="principal.php" style="display:inline-block; background:#0288d1; color:#fff; padding:8px 12px; border-radius:4px; text-decoration:none;">← Voltar para Principal</a>
        <a href="bases.php" style="display:inline-block; background:#5e35b1; color:#fff; padding:8px 12px; border-radius:4px; text-decoration:none;">🗂️ Cadastro de Bases</a>
        <a href="importar_empresas.php" style="display:inline-block; background:#2e7d32; color:#fff; padding:8px 12px; border-radius:4px; text-decoration:none;">📥 Importar Empresas (CSV)</a>
        <a href="importar_contatos_empresa.php" style="display:inline-block; background:#6d4c41; color:#fff; padding:8px 12px; border-radius:4px; text-decoration:none;">📥 Importar Contatos de Empresas (CSV)</a>
    </div>
    <?php if ($modo_lista && $base_foi_escolhida): ?>
        <div style="margin-bottom:10px; padding:8px 10px; background:#e3f2fd; color:#0d47a1; border-radius:4px; border-left:4px solid #1976d2;">
            <strong>Base ativa:</strong> <?= htmlspecialchars($base_selecionada) ?>
        </div>
    <?php endif; ?>
    <?php if (isset($_GET['msg']) && $_GET['msg']=='sucesso'): ?>
        <div class="msg">✓ Operação concluída com sucesso.</div>
    <?php endif; ?>
    <?php if (isset($_GET['msg']) && $_GET['msg']=='importacao_sucesso'): ?>
        <div class="msg">
            <strong>✓ Importação concluída com sucesso!</strong>
            <?php if (isset($_GET['total'])): ?>
                <br>Total de registros importados: <strong><?= (int)$_GET['total'] ?></strong>
            <?php endif; ?>
            <?php if (!empty($_GET['base'])): ?>
                <br>Base importada: <strong><?= htmlspecialchars($_GET['base']) ?></strong>
            <?php endif; ?>
        </div>
    <?php endif; ?>
    <?php if (isset($_GET['msg']) && $_GET['msg']=='erro_importacao'): ?>
        <div style="padding:8px; background:#f8d7da; color:#721c24; border-radius:4px; margin-bottom:10px;">
            <strong>✗ Erro na importação:</strong>
            <?php if (isset($_GET['detalhe'])): ?>
                <br><?= htmlspecialchars($_GET['detalhe']) ?>
            <?php endif; ?>
            <?php if (isset($_GET['total']) && $_GET['total'] > 0): ?>
                <br>Registros importados antes do erro: <strong><?= (int)$_GET['total'] ?></strong>
            <?php endif; ?>
            <?php if (!empty($_GET['base'])): ?>
                <br>Base de destino: <strong><?= htmlspecialchars($_GET['base']) ?></strong>
            <?php endif; ?>
        </div>
    <?php endif; ?>
    <?php if (isset($_GET['msg']) && $_GET['msg']=='importacao_contatos_sucesso'): ?>
        <div class="msg">
            <strong>✓ Importação de contatos concluída com sucesso!</strong>
            <?php if (isset($_GET['total'])): ?>
                <br>Total de contatos importados: <strong><?= (int)$_GET['total'] ?></strong>
            <?php endif; ?>
            <?php if (!empty($_GET['base'])): ?>
                <br>Base importada: <strong><?= htmlspecialchars($_GET['base']) ?></strong>
            <?php endif; ?>
        </div>
    <?php endif; ?>
    <?php if (isset($_GET['msg']) && $_GET['msg']=='erro_importacao_contatos'): ?>
        <div style="padding:8px; background:#f8d7da; color:#721c24; border-radius:4px; margin-bottom:10px;">
            <strong>✗ Erro na importação de contatos:</strong>
            <?php if (isset($_GET['detalhe'])): ?>
                <br><?= htmlspecialchars($_GET['detalhe']) ?>
            <?php endif; ?>
            <?php if (isset($_GET['total']) && $_GET['total'] > 0): ?>
                <br>Contatos importados antes do erro: <strong><?= (int)$_GET['total'] ?></strong>
            <?php endif; ?>
            <?php if (!empty($_GET['base'])): ?>
                <br>Base de destino: <strong><?= htmlspecialchars($_GET['base']) ?></strong>
            <?php endif; ?>
        </div>
    <?php endif; ?>

    <?php if ($action === 'edit'): ?>
        <a href="empresas.php" class="btn-new">← Voltar à lista</a>
        <h2><?= $id_edit ? 'Editar empresa #' . $id_edit : 'Nova empresa' ?></h2>
        <form method="POST" action="empresas.php">
            <input type="hidden" name="id_emp" value="<?= $empresa_row['ID_EMPRESA'] ?? 0 ?>">

            <div class="form-row">
                <div>
                    <label>CNPJ</label>
                    <input type="text" name="cnpj" value="<?= htmlspecialchars($empresa_row['CNPJ'] ?? '') ?>">
                </div>
                <div>
                    <label>Nome Fantasia</label>
                    <input type="text" name="nome_fantasia" value="<?= htmlspecialchars($empresa_row['NOME_FANTASIA'] ?? '') ?>">
                </div>
                <div>
                    <label>Empresa (Razão)</label>
                    <input type="text" name="empresa" value="<?= htmlspecialchars($empresa_row['EMPRESA'] ?? '') ?>">
                </div>
            </div>

            <div class="form-row" style="margin-top:10px;">
                <div><label>Rua</label><input type="text" name="rua" value="<?= htmlspecialchars($empresa_row['RUA'] ?? '') ?>"></div>
                <div><label>Número</label><input type="text" name="numero" value="<?= htmlspecialchars($empresa_row['NUMERO'] ?? '') ?>"></div>
                <div><label>Compl.</label><input type="text" name="compl_num" value="<?= htmlspecialchars($empresa_row['COMPL_NUM'] ?? '') ?>"></div>
            </div>

            <div class="form-row" style="margin-top:10px;">
                <div><label>Bairro</label><input type="text" name="bairro" value="<?= htmlspecialchars($empresa_row['BAIRRO'] ?? '') ?>"></div>
                <div><label>Cidade</label><input type="text" name="cidade" value="<?= htmlspecialchars($empresa_row['CIDADE'] ?? '') ?>"></div>
                <div><label>UF</label><input type="text" name="uf" maxlength="2" value="<?= htmlspecialchars($empresa_row['UF'] ?? '') ?>"></div>
            </div>

            <div class="form-row" style="margin-top:10px;">
                <div><label>CEP</label><input type="text" name="cep" value="<?= htmlspecialchars($empresa_row['CEP'] ?? '') ?>"></div>
                <div><label>DDD</label><input type="text" name="ddd" value="<?= htmlspecialchars($empresa_row['DDD'] ?? '') ?>"></div>
                <div><label>Telefone</label><input type="text" name="tel" value="<?= htmlspecialchars($empresa_row['TEL'] ?? '') ?>"></div>
            </div>

            <div class="form-row" style="margin-top:10px;">
                <div><label>CNAE</label><input type="text" name="cnae" value="<?= htmlspecialchars($empresa_row['CNAE'] ?? '') ?>"></div>
                <div><label>Funcionários</label><input type="text" name="funcionarios" value="<?= htmlspecialchars($empresa_row['FUNCIONARIOS'] ?? '') ?>"></div>
                <div><label>Site</label><input type="text" name="site" value="<?= htmlspecialchars($empresa_row['SITE'] ?? '') ?>"></div>
            </div>

            <div class="form-row" style="margin-top:10px;">
                <div>
                    <label>Base</label>
                    <select name="idbase" required>
                        <option value="">Selecione...</option>
                        <?php foreach ($bases_disponiveis as $base_item): ?>
                            <option value="<?= (int)$base_item['idbase'] ?>" <?= ((int)($empresa_row['idbase'] ?? 0) === (int)$base_item['idbase']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($base_item['nome_base']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label>Porte</label>
                    <select name="porte">
                        <option value="">Selecione...</option>
                        <option value="MICRO" <?= (isset($empresa_row['PORTE']) && $empresa_row['PORTE'] === 'MICRO') ? 'selected' : '' ?>>MICRO</option>
                        <option value="PEQUENA" <?= (isset($empresa_row['PORTE']) && $empresa_row['PORTE'] === 'PEQUENA') ? 'selected' : '' ?>>PEQUENA</option>
                        <option value="MÉDIA" <?= (isset($empresa_row['PORTE']) && $empresa_row['PORTE'] === 'MÉDIA') ? 'selected' : '' ?>>MÉDIA</option>
                        <option value="GRANDE" <?= (isset($empresa_row['PORTE']) && $empresa_row['PORTE'] === 'GRANDE') ? 'selected' : '' ?>>GRANDE</option>
                    </select>
                </div>
                <div>
                    <label>Ativa</label>
                    <select name="ativa">
                        <option value="S" <?= (isset($empresa_row['ATIVA']) && $empresa_row['ATIVA'] == 'S') ? 'selected' : '' ?>>Sim</option>
                        <option value="N" <?= (isset($empresa_row['ATIVA']) && $empresa_row['ATIVA'] == 'N') ? 'selected' : '' ?>>Não</option>
                    </select>
                </div>
            </div>

            <div style="margin-top:12px;">
                <button type="submit" style="background:#004d99;color:white;padding:8px 12px;border:none;border-radius:4px;">Salvar</button>
                <a href="empresas.php" style="margin-left:8px;">Cancelar</a>
            </div>
        </form>

        <hr style="margin:20px 0;">
        <h2>Contatos da Empresa</h2>
        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:10px;">
            <button type="button" id="btn-novo-contato-emp" style="background:#2e7d32;color:white;padding:8px 12px;border:none;border-radius:4px;">+ Novo Contato</button>
            <span style="color:#666;">Empresa #<?= (int)$id_edit ?></span>
        </div>
        <table id="grid-contatos-emp" style="width:100%; border-collapse:collapse; font-size:0.95em;">
            <thead>
                <tr style="background:#004d99;color:#fff;">
                    <th style="padding:6px; text-align:left;">Depto</th>
                    <th style="padding:6px; text-align:left;">Nome</th>
                    <th style="padding:6px; text-align:left;">Sobrenome</th>
                    <th style="padding:6px; text-align:left;">Cargo</th>
                    <th style="padding:6px; text-align:left;">Sexo</th>
                    <th style="padding:6px; text-align:left;">Email</th>
                    <th style="padding:6px; text-align:left;">DDD</th>
                    <th style="padding:6px; text-align:left;">Tel</th>
                    <th style="padding:6px; text-align:left;">Celular</th>
                    <th style="padding:6px; text-align:left;">Ramal</th>
                    <th style="padding:6px; text-align:left;">LinkedIn</th>
                    <th style="padding:6px; text-align:left;">Status Contato</th>
                    <th style="padding:6px; text-align:left;">Ações</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>

        <!-- Modal Contato Empresa -->
        <div id="modalContatoEmp" style="display:none; position:fixed; z-index:1000; left:0; top:0; width:100%; height:100%; background:rgba(0,0,0,0.4);">
            <div style="background:#fff; width:720px; max-width:95%; margin:60px auto; border-radius:8px; box-shadow:0 4px 12px rgba(0,0,0,0.2);">
                <div style="padding:12px 16px; background:#004d99; color:#fff; border-top-left-radius:8px; border-top-right-radius:8px; display:flex; justify-content:space-between; align-items:center;">
                    <strong id="modalContatoEmpTitle">Novo Contato</strong>
                    <button type="button" id="modalContatoEmpClose" style="background:transparent; color:#fff; border:none; font-size:18px; cursor:pointer;">×</button>
                </div>
                <div style="padding:16px;">
                    <form id="formContatoEmp">
                        <input type="hidden" name="idcontatos_empresa" value="">
                        <input type="hidden" name="id_empresa" value="<?= (int)$id_edit ?>">
                        <div class="form-row">
                            <div><label>Depto</label><input type="text" name="depto"></div>
                            <div><label>Nome</label><input type="text" name="nome"></div>
                            <div><label>Sobrenome</label><input type="text" name="sobrenome"></div>
                        </div>
                        <div class="form-row" style="margin-top:10px;">
                            <div><label>Cargo</label><input type="text" name="cargo"></div>
                            <div><label>Sexo</label>
                                <select name="sexo">
                                    <option value="">Selecione...</option>
                                    <option value="M">Masculino</option>
                                    <option value="F">Feminino</option>
                                </select>
                            </div>
                            <div><label>Email</label><input type="text" name="email"></div>
                        </div>
                        <div class="form-row" style="margin-top:10px;">
                            <div><label>DDD</label><input type="text" name="ddd"></div>
                            <div><label>Telefone</label><input type="text" name="tel"></div>
                            <div><label>Celular</label><input type="text" name="celular"></div>
                        </div>
                        <div class="form-row" style="margin-top:10px;">
                            <div><label>Ramal</label><input type="text" name="ramal"></div>
                            <div><label>LinkedIn</label><input type="text" name="linkedin"></div>
                            <div>
                                <label>Status Contato</label>
                                <select name="idcontato_status">
                                    <option value="">-- Nenhum --</option>
                                    <?php foreach ($contato_status_opcoes as $cs): ?>
                                        <option value="<?= $cs['idcontato_status'] ?>"><?= htmlspecialchars($cs['contato_status']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </form>
                    <div style="margin-top:12px; display:flex; gap:10px;">
                        <button type="button" id="btnSalvarContatoEmp" style="background:#004d99;color:#fff;padding:8px 12px;border:none;border-radius:4px;">Salvar</button>
                        <button type="button" id="btnExcluirContatoEmp" style="background:#b71c1c;color:#fff;padding:8px 12px;border:none;border-radius:4px; display:none;">Excluir</button>
                        <button type="button" id="btnCancelarContatoEmp" style="padding:8px 12px;">Cancelar</button>
                    </div>
                </div>
            </div>
        </div>

        <script>
        (function(){
            const empresaId = <?= (int)$id_edit ?>;
            const grid = document.getElementById('grid-contatos-emp');
            const tbody = grid ? grid.querySelector('tbody') : null;
            const btnNovo = document.getElementById('btn-novo-contato-emp');
            const modal = document.getElementById('modalContatoEmp');
            const form = document.getElementById('formContatoEmp');
            const title = document.getElementById('modalContatoEmpTitle');
            const btnClose = document.getElementById('modalContatoEmpClose');
            const btnCancel = document.getElementById('btnCancelarContatoEmp');
            const btnSalvar = document.getElementById('btnSalvarContatoEmp');
            const btnExcluir = document.getElementById('btnExcluirContatoEmp');

            function openModal(data){
                title.textContent = (data && data.idcontatos_empresa) ? 'Editar Contato' : 'Novo Contato';
                btnExcluir.style.display = (data && data.idcontatos_empresa) ? 'inline-block' : 'none';
                btnExcluir.dataset.idcontato = data ? (data.idcontatos_empresa || '') : '';
                Array.from(form.elements).forEach(el => { if(el.name){ el.value = ''; } });
                if(data){ Object.keys(data).forEach(k => { if(form[k] !== undefined){ form[k].value = data[k] ?? ''; } }); }
                modal.style.display = 'block';
            }
            function closeModal(){ modal.style.display = 'none'; }
            if(btnClose) btnClose.addEventListener('click', closeModal);
            if(btnCancel) btnCancel.addEventListener('click', closeModal);
            window.addEventListener('click', (e)=>{ if(e.target === modal) closeModal(); });

            async function carregar(){
                if(!tbody) return;
                tbody.innerHTML = '<tr><td colspan="13" style="color:#666;">Carregando...</td></tr>';
                try{
                    const res = await fetch(`contatos_empresa.php?action=list&id_empresa=${empresaId}`);
                    const json = await res.json();
                    tbody.innerHTML = '';
                    if(json.success){
                        if(json.data.length === 0){
                            tbody.innerHTML = '<tr><td colspan="13" style="color:#999; text-align:center;">Nenhum contato cadastrado.</td></tr>';
                        } else {
                            json.data.forEach(row => {
                                const tr = document.createElement('tr');
                                tr.innerHTML = `
                                    <td style="padding:6px;">${row.depto || '-'}</td>
                                    <td style="padding:6px;">${row.nome || '-'}</td>
                                    <td style="padding:6px;">${row.sobrenome || '-'}</td>
                                    <td style="padding:6px;">${row.cargo || '-'}</td>
                                    <td style="padding:6px;">${row.sexo || '-'}</td>
                                    <td style="padding:6px;">${row.email || '-'}</td>
                                    <td style="padding:6px;">${row.ddd || '-'}</td>
                                    <td style="padding:6px;">${row.tel || '-'}</td>
                                    <td style="padding:6px;">${row.celular || '-'}</td>
                                    <td style="padding:6px;">${row.ramal || '-'}</td>
                                    <td style="padding:6px;">${row.linkedin || '-'}</td>
                                    <td style="padding:6px;">${row.status_contato_nome || '-'}</td>
                                    <td style="padding:6px;">
                                        <button type="button" class="btn-edit" data-id="${row.idcontatos_empresa}">Editar</button>
                                        <button type="button" class="btn-delete" data-id="${row.idcontatos_empresa}" style="margin-left:6px;">Excluir</button>
                                    </td>`;
                                tbody.appendChild(tr);
                            });
                        }
                    } else {
                        tbody.innerHTML = '<tr><td colspan="13" style="color:#b71c1c;">Erro ao carregar contatos.</td></tr>';
                    }
                }catch(err){
                    tbody.innerHTML = '<tr><td colspan="13" style="color:#b71c1c;">Falha de rede ao carregar.</td></tr>';
                }
            }

            if(btnNovo){ btnNovo.addEventListener('click', ()=> openModal(null)); }
            if(tbody){
                tbody.addEventListener('click', async (e)=>{
                    const btn = e.target.closest('button');
                    if(!btn) return;
                    const idce = btn.dataset.id;
                    if(btn.classList.contains('btn-edit')){
                        const res = await fetch(`contatos_empresa.php?action=get&idce=${encodeURIComponent(idce)}`);
                        const json = await res.json();
                        if(json.success){ openModal(json.data); }
                        else alert('Erro ao carregar contato');
                    } else if(btn.classList.contains('btn-delete')){
                        if(!confirm('Excluir este contato?')) return;
                        const fd = new FormData();
                        fd.append('idcontatos_empresa', idce);
                        const res = await fetch('contatos_empresa.php?action=delete', { method:'POST', body: fd });
                        const json = await res.json();
                        if(json.success){ carregar(); }
                        else alert('Erro ao excluir.');
                    }
                });
            }

            if(btnSalvar){
                btnSalvar.addEventListener('click', async ()=>{
                    const fd = new FormData(form);
                    const res = await fetch('contatos_empresa.php?action=save', { method:'POST', body: fd });
                    const json = await res.json();
                    if(json.success){ closeModal(); carregar(); }
                    else alert('Erro ao salvar contato.');
                });
            }

            if(btnExcluir){
                btnExcluir.addEventListener('click', async ()=>{
                    if(!btnExcluir.dataset.idcontato) return;
                    if(!confirm('Tem certeza que deseja excluir este contato?')) return;
                    const fd = new FormData();
                    fd.append('idcontatos_empresa', btnExcluir.dataset.idcontato);
                    const res = await fetch('contatos_empresa.php?action=delete', { method:'POST', body: fd });
                    const json = await res.json();
                    if(json.success){ closeModal(); carregar(); }
                    else alert('Erro ao excluir.');
                });
            }

            // Inicializar grid
            carregar();
        })();
        </script>

    <?php else: ?>
        <?php if (!$base_foi_escolhida): ?>
            <div style="background:#f8f9fa; border:1px solid #e0e0e0; border-radius:6px; padding:16px; margin-bottom:14px;">
                <h2 style="margin:0 0 10px 0; color:#004d99; font-size:1.1em;">Selecione a base para visualizar empresas</h2>
                <form method="get" action="empresas.php" style="display:grid; grid-template-columns: minmax(220px, 420px) auto; gap:8px; align-items:end;">
                    <div>
                        <label style="font-weight:bold; font-size:0.9em;">Base</label>
                        <select name="f_idbase" required>
                            <option value="">Selecione...</option>
                            <?php foreach ($bases_disponiveis as $base_item): ?>
                                <option value="<?= (int)$base_item['idbase'] ?>"><?= htmlspecialchars($base_item['nome_base']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <button type="submit" style="background:#004d99; color:#fff; padding:8px 12px; border:none; border-radius:4px;">Abrir base</button>
                    </div>
                </form>
            </div>
        <?php else: ?>
        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:10px;">
            <div>
                <a href="empresas.php?action=edit" class="btn-new">+ Nova Empresa</a>
                <form method="post" action="empresas.php" style="display:inline-block; margin-left:8px;" onsubmit="return confirm('Tem certeza que deseja ativar todas as empresas?');">
                    <input type="hidden" name="acao" value="ativar_todas_empresas">
                    <button type="submit" class="btn-activate-all">Ativar Todas</button>
                </form>
            </div>
            <div style="color:#666;">Registros: <?= $res ? $res->num_rows : 0 ?></div>
        </div>

        <form method="get" action="empresas.php" style="background:#f8f9fa; padding:10px; border:1px solid #e0e0e0; border-radius:6px; margin-bottom:12px; display:grid; grid-template-columns: repeat(auto-fit, minmax(180px,1fr)); gap:8px;">
            <div>
                <label style="font-weight:bold; font-size:0.9em;">ID</label>
                <input type="text" name="f_id" value="<?= htmlspecialchars($_GET['f_id'] ?? '') ?>">
            </div>
            <div>
                <label style="font-weight:bold; font-size:0.9em;">Empresa</label>
                <input type="text" name="f_empresa" value="<?= htmlspecialchars($_GET['f_empresa'] ?? '') ?>">
            </div>
            <div>
                <label style="font-weight:bold; font-size:0.9em;">Nome Fantasia</label>
                <input type="text" name="f_nome_fantasia" value="<?= htmlspecialchars($_GET['f_nome_fantasia'] ?? '') ?>">
            </div>
            <div>
                <label style="font-weight:bold; font-size:0.9em;">CNPJ</label>
                <input type="text" name="f_cnpj" value="<?= htmlspecialchars($_GET['f_cnpj'] ?? '') ?>">
            </div>
            <div>
                <label style="font-weight:bold; font-size:0.9em;">Cidade</label>
                <input type="text" name="f_cidade" value="<?= htmlspecialchars($_GET['f_cidade'] ?? '') ?>">
            </div>
            <div>
                <label style="font-weight:bold; font-size:0.9em;">UF</label>
                <input type="text" name="f_uf" maxlength="2" value="<?= htmlspecialchars($_GET['f_uf'] ?? '') ?>">
            </div>
            <div>
                <label style="font-weight:bold; font-size:0.9em;">Nº Funcionários</label>
                <input type="text" name="f_funcionarios" value="<?= htmlspecialchars($_GET['f_funcionarios'] ?? '') ?>">
            </div>
            <div>
                <label style="font-weight:bold; font-size:0.9em;">Base</label>
                <select name="f_idbase">
                    <option value="">Selecione...</option>
                    <?php foreach ($bases_disponiveis as $base_item): ?>
                        <option value="<?= (int)$base_item['idbase'] ?>" <?= $f_idbase === (int)$base_item['idbase'] ? 'selected' : '' ?>><?= htmlspecialchars($base_item['nome_base']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div style="display:flex; align-items:flex-end; gap:6px;">
                <button type="submit" style="background:#004d99; color:#fff; padding:8px 12px; border:none; border-radius:4px;">Filtrar</button>
                <a href="empresas.php" style="color:#004d99; text-decoration:none;">Trocar base</a>
            </div>
        </form>

        <!-- Controle de paginação -->
        <div style="display: flex; justify-content: space-between; align-items: center; margin: 20px 0; padding: 10px; background: #f8f9fa; border-radius: 4px;">
            <div>
                <strong>Registros por página:</strong>
                <select onchange="window.location.href='empresas.php?por_pagina=' + this.value + '<?= isset($_GET['f_id']) ? '&f_id=' . urlencode($_GET['f_id']) : '' ?><?= isset($_GET['f_empresa']) ? '&f_empresa=' . urlencode($_GET['f_empresa']) : '' ?><?= isset($_GET['f_nome_fantasia']) ? '&f_nome_fantasia=' . urlencode($_GET['f_nome_fantasia']) : '' ?><?= isset($_GET['f_cnpj']) ? '&f_cnpj=' . urlencode($_GET['f_cnpj']) : '' ?><?= isset($_GET['f_cidade']) ? '&f_cidade=' . urlencode($_GET['f_cidade']) : '' ?><?= isset($_GET['f_uf']) ? '&f_uf=' . urlencode($_GET['f_uf']) : '' ?><?= isset($_GET['f_funcionarios']) ? '&f_funcionarios=' . urlencode($_GET['f_funcionarios']) : '' ?><?= isset($_GET['f_idbase']) ? '&f_idbase=' . urlencode($_GET['f_idbase']) : '' ?>'" style="padding: 5px 10px; border: 1px solid #ddd; border-radius: 4px; margin-left: 10px;">
                    <option value="10" <?= $por_pagina == 10 ? 'selected' : '' ?>>10</option>
                    <option value="50" <?= $por_pagina == 50 ? 'selected' : '' ?>>50</option>
                    <option value="100" <?= $por_pagina == 100 ? 'selected' : '' ?>>100</option>
                </select>
            </div>
            <div>
                <strong>Mostrando <?= min($offset + 1, $total_registros) ?> a <?= min($offset + $por_pagina, $total_registros) ?> de <?= $total_registros ?> registros</strong>
            </div>
            <div style="display: flex; gap: 5px;">
                <?php if ($pagina_atual > 1): ?>
                    <a href="empresas.php?pagina=<?= $pagina_atual - 1 ?>&por_pagina=<?= $por_pagina ?><?= isset($_GET['f_id']) ? '&f_id=' . urlencode($_GET['f_id']) : '' ?><?= isset($_GET['f_empresa']) ? '&f_empresa=' . urlencode($_GET['f_empresa']) : '' ?><?= isset($_GET['f_nome_fantasia']) ? '&f_nome_fantasia=' . urlencode($_GET['f_nome_fantasia']) : '' ?><?= isset($_GET['f_cnpj']) ? '&f_cnpj=' . urlencode($_GET['f_cnpj']) : '' ?><?= isset($_GET['f_cidade']) ? '&f_cidade=' . urlencode($_GET['f_cidade']) : '' ?><?= isset($_GET['f_uf']) ? '&f_uf=' . urlencode($_GET['f_uf']) : '' ?><?= isset($_GET['f_funcionarios']) ? '&f_funcionarios=' . urlencode($_GET['f_funcionarios']) : '' ?><?= isset($_GET['f_idbase']) ? '&f_idbase=' . urlencode($_GET['f_idbase']) : '' ?>" style="padding: 5px 10px; background: #004d99; color: white; text-decoration: none; border-radius: 4px;">← Anterior</a>
                <?php endif; ?>
                
                <?php
                $inicio = max(1, $pagina_atual - 2);
                $fim = min($total_paginas, $pagina_atual + 2);
                
                for ($i = $inicio; $i <= $fim; $i++):
                ?>
                    <a href="empresas.php?pagina=<?= $i ?>&por_pagina=<?= $por_pagina ?><?= isset($_GET['f_id']) ? '&f_id=' . urlencode($_GET['f_id']) : '' ?><?= isset($_GET['f_empresa']) ? '&f_empresa=' . urlencode($_GET['f_empresa']) : '' ?><?= isset($_GET['f_nome_fantasia']) ? '&f_nome_fantasia=' . urlencode($_GET['f_nome_fantasia']) : '' ?><?= isset($_GET['f_cnpj']) ? '&f_cnpj=' . urlencode($_GET['f_cnpj']) : '' ?><?= isset($_GET['f_cidade']) ? '&f_cidade=' . urlencode($_GET['f_cidade']) : '' ?><?= isset($_GET['f_uf']) ? '&f_uf=' . urlencode($_GET['f_uf']) : '' ?><?= isset($_GET['f_funcionarios']) ? '&f_funcionarios=' . urlencode($_GET['f_funcionarios']) : '' ?><?= isset($_GET['f_idbase']) ? '&f_idbase=' . urlencode($_GET['f_idbase']) : '' ?>" style="padding: 5px 10px; background: <?= $i == $pagina_atual ? '#004d99' : '#6c757d' ?>; color: white; text-decoration: none; border-radius: 4px;"><?= $i ?></a>
                <?php endfor; ?>
                
                <?php if ($pagina_atual < $total_paginas): ?>
                    <a href="empresas.php?pagina=<?= $pagina_atual + 1 ?>&por_pagina=<?= $por_pagina ?><?= isset($_GET['f_id']) ? '&f_id=' . urlencode($_GET['f_id']) : '' ?><?= isset($_GET['f_empresa']) ? '&f_empresa=' . urlencode($_GET['f_empresa']) : '' ?><?= isset($_GET['f_nome_fantasia']) ? '&f_nome_fantasia=' . urlencode($_GET['f_nome_fantasia']) : '' ?><?= isset($_GET['f_cnpj']) ? '&f_cnpj=' . urlencode($_GET['f_cnpj']) : '' ?><?= isset($_GET['f_cidade']) ? '&f_cidade=' . urlencode($_GET['f_cidade']) : '' ?><?= isset($_GET['f_uf']) ? '&f_uf=' . urlencode($_GET['f_uf']) : '' ?><?= isset($_GET['f_funcionarios']) ? '&f_funcionarios=' . urlencode($_GET['f_funcionarios']) : '' ?><?= isset($_GET['f_idbase']) ? '&f_idbase=' . urlencode($_GET['f_idbase']) : '' ?>" style="padding: 5px 10px; background: #004d99; color: white; text-decoration: none; border-radius: 4px;">Próxima →</a>
                <?php endif; ?>
            </div>
        </div>

        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Empresa</th>
                    <th>Nome Fantasia</th>
                    <th>CNPJ</th>
                    <th>Cidade/UF</th>
                    <th>Base</th>
                    <th>Funcionários</th>
                    <th>Ativa</th>
                    <th>Ações</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($res && $res->num_rows): while($row = $res->fetch_assoc()): ?>
                <tr>
                    <td><?= $row['ID_EMPRESA'] ?></td>
                    <td><?= htmlspecialchars($row['EMPRESA']) ?></td>
                    <td><?= htmlspecialchars($row['NOME_FANTASIA']) ?></td>
                    <td><?= htmlspecialchars($row['CNPJ']) ?></td>
                    <td><?= htmlspecialchars($row['CIDADE']) ?> / <?= htmlspecialchars($row['UF']) ?></td>
                    <td><?= htmlspecialchars($row['BASE'] ?? '') ?></td>
                    <td><?= htmlspecialchars($row['FUNCIONARIOS']) ?></td>
                    <td><?= ($row['ATIVA'] === 'S') ? 'Sim' : 'Não' ?></td>
                    <td class="actions">
                        <a class="btn-edit" href="empresas.php?action=edit&id=<?= $row['ID_EMPRESA'] ?>">Editar</a>
                    </td>
                </tr>
                <?php endwhile; else: ?>
                <tr><td colspan="9">Nenhuma empresa cadastrada.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
        <?php endif; ?>
    <?php endif; ?>

</div>
</body>
</html>
