<?php
ob_start();
?>

<div class="row mb-4">
    <div class="col-md-6">
        <h2><i class="bi bi-building me-2"></i> Empresas</h2>
        <p class="text-muted">Gerencie as empresas do sistema</p>
    </div>
    <div class="col-md-6 text-end">
        <a href="<?= url('/empresas/criar') ?>" class="btn btn-primary">
            <i class="bi bi-plus-circle me-2"></i> Nova Empresa
        </a>
    </div>
</div>

<!-- Filtros -->
<div class="card mb-4">
    <div class="card-body">
        <form method="GET" class="row g-3">
            <div class="col-md-8">
                <input type="text" class="form-control" name="search" placeholder="Buscar por nome, CNPJ..." value="<?= htmlspecialchars($search ?? '') ?>">
            </div>
            <div class="col-md-2">
                <select class="form-select" name="status">
                    <option value="">Todos os Status</option>
                    <option value="1" <?= ($status ?? '') === '1' ? 'selected' : '' ?>>Ativas</option>
                    <option value="0" <?= ($status ?? '') === '0' ? 'selected' : '' ?>>Inativas</option>
                </select>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-secondary w-100">
                    <i class="bi bi-search"></i> Buscar
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Listagem -->
<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <span><i class="bi bi-list-ul me-2"></i> Lista de Empresas</span>
        <span class="badge bg-primary"><?= count($empresas ?? []) ?> registro(s)</span>
    </div>
    <div class="card-body p-0">
        <?php if (!empty($empresas)): ?>
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th width="60">ID</th>
                            <th>Nome/Razão Social</th>
                            <th>Nome Fantasia</th>
                            <th>CNPJ/CPF</th>
                            <th>Endereço</th>
                            <th>Cidade/UF</th>
                            <th width="100" class="text-center">Status</th>
                            <th width="120" class="text-center">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($empresas as $empresa): ?>
                            <tr>
                                <td><?= $empresa['id'] ?></td>
                                <td>
                                    <strong><?= htmlspecialchars($empresa['razao_social'] ?? '-') ?></strong>
                                    <?php if (($empresa['company_id'] ?? 0) == 1): ?>
                                        <span class="badge bg-success ms-2">Padrão</span>
                                    <?php endif; ?>
                                </td>
                                <td><?= htmlspecialchars($empresa['nome_fantasia'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($empresa['cnpj'] ?? '-') ?></td>
                                <td>
                                    <?php
                                    $endereco_parts = array_filter([
                                        $empresa['endereco'] ?? '',
                                        $empresa['numero'] ?? '',
                                        $empresa['bairro'] ?? ''
                                    ]);
                                    $endereco = implode(', ', $endereco_parts);
                                    ?>
                                    <small class="text-muted"><?= htmlspecialchars($endereco ?: '-') ?></small>
                                </td>
                                <td><?= htmlspecialchars($empresa['cidade'] ?? '-') ?>/<?= htmlspecialchars($empresa['uf'] ?? '-') ?></td>
                                <td class="text-center">
                                    <?php if (($empresa['ativo'] ?? 'Não') === 'Sim'): ?>
                                        <span class="badge bg-success">Ativa</span>
                                    <?php else: ?>
                                        <span class="badge bg-secondary">Inativa</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center">
                                    <div class="btn-group btn-group-sm">
                                        <a href="<?= url('/empresas/editar?id=' . $empresa['id']) ?>" class="btn btn-outline-primary" title="Editar">
                                            <i class="bi bi-pencil"></i>
                                        </a>
                                        <?php if (($empresa['company_id'] ?? 0) != 1): ?>
                                            <button class="btn btn-outline-danger" onclick="deletarEmpresa(<?= $empresa['id'] ?>)" title="Excluir">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="text-center py-5">
                <i class="bi bi-building-x" style="font-size: 4rem; color: var(--text-secondary);"></i>
                <p class="text-muted mt-3">Nenhuma empresa encontrada</p>
                <a href="<?= url('/empresas/criar') ?>" class="btn btn-primary mt-2">
                    <i class="bi bi-plus-circle me-2"></i> Cadastrar Primeira Empresa
                </a>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
async function deletarEmpresa(id) {
    const confirmed = await confirmDelete('Tem certeza que deseja excluir esta empresa?');
    if (confirmed) {
        $.ajax({
            url: appUrl('/empresas/deletar'),
            type: 'POST',
            data: { id: id },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Toast.success(response.message);
                    setTimeout(() => location.reload(), 1500);
                } else {
                    Toast.error(response.message);
                }
            }
        });
    }
}
</script>

<?php
$content = ob_get_clean();
$activeMenu = 'empresas';
include ROOT_PATH . '/views/layouts/app.php';
?>

