<?php
/**
 * Selflix Vagas - Listagem de Empresas (Visão Administrador)
 * Versão: UI Premium com Botão WhatsApp e Botões Mobile Empilhados
 */

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once 'conexao.php'; 
require_once 'env.php';

// Verifica se o usuário é administrador
if (($_SESSION['role'] ?? '') !== 'Administradores' && ($_SESSION['role'] ?? '') !== 'Administrador') {
    header("Location: login.php");
    exit();
}

// Token CSRF
if (empty($_SESSION['csrf_token_lista_empresa'])) {
    $_SESSION['csrf_token_lista_empresa'] = bin2hex(random_bytes(32));
}
$csrf_token = $_SESSION['csrf_token_lista_empresa'];

$termo_busca = $_GET['q'] ?? '';
$itens_por_pagina = 12;
$pagina_atual = isset($_GET['pagina']) && is_numeric($_GET['pagina']) ? (int)$_GET['pagina'] : 1;
$offset = ($pagina_atual - 1) * $itens_por_pagina;

try {
    // 1. Contagem para Paginação
    $sql_count = "SELECT COUNT(*) FROM Empresas";
    if (!empty($termo_busca)) {
        $sql_count .= " WHERE nome_empresa LIKE :q OR email LIKE :q2 OR cnpj LIKE :q3";
    }
    $stmt_count = $pdo->prepare($sql_count);
    if (!empty($termo_busca)) {
        $stmt_count->bindValue(':q', "%$termo_busca%");
        $stmt_count->bindValue(':q2', "%$termo_busca%");
        $stmt_count->bindValue(':q3', "%$termo_busca%");
    }
    $stmt_count->execute();
    $total_empresas = $stmt_count->fetchColumn();
    $total_paginas = ceil($total_empresas / $itens_por_pagina);

    // 2. Consulta Principal
    $sql = "SELECT * FROM Empresas";
    if (!empty($termo_busca)) {
        $sql .= " WHERE nome_empresa LIKE :q OR email LIKE :q2 OR cnpj LIKE :q3";
    }
    $sql .= " ORDER BY nome_empresa ASC LIMIT :limit OFFSET :offset";

    $stmt = $pdo->prepare($sql);
    if (!empty($termo_busca)) {
        $stmt->bindValue(':q', "%$termo_busca%");
        $stmt->bindValue(':q2', "%$termo_busca%");
        $stmt->bindValue(':q3', "%$termo_busca%");
    }
    $stmt->bindValue(':limit', $itens_por_pagina, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $empresas = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    die("Erro ao carregar empresas: " . $e->getMessage());
}

/**
 * Função auxiliar para limpar o número do WhatsApp
 */
function limparNumero($numero) {
    return preg_replace('/[^0-9]/', '', $numero);
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Empresas Cadastradas - Self Lix Vagas</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        :root { --selflix-teal: #12929e; --whatsapp-green: #25D366; }
        body { font-family: Arial, sans-serif; background-color: #f8f9fa; color: #333; }
        .container-main { width: 100%; max-width: 1300px; margin: 30px auto; background-color: white; padding: 25px; border-radius: 12px; box-shadow: 0 0 20px rgba(0,0,0,0.08); }
        h2 { color: var(--selflix-teal); font-weight: 700; }
        
        .card-empresa { border: none; border-left: 5px solid var(--selflix-teal); border-radius: 10px; transition: 0.3s; }
        .card-empresa:hover { transform: translateY(-5px); box-shadow: 0 10px 25px rgba(0,0,0,0.1); }
        .card-empresa-logo { max-width: 80px; max-height: 50px; object-fit: contain; }
        .info-label { min-width: 95px; display: inline-block; font-weight: bold; color: var(--selflix-teal); }

        /* Estilo Botões de Ação no Card */
        .btn-service-icon { 
            padding: 8px 16px; 
            display: inline-flex; 
            align-items: center; 
            justify-content: center; 
            border-radius: 50px; 
            color: white; 
            text-decoration: none; 
            transition: 0.2s; 
            border: 1px solid rgba(0,0,0,0.1);
            font-size: 0.9rem;
            min-width: 45px;
        }
        .btn-service-icon:hover { opacity: 0.85; color: white; transform: scale(1.05); }
        
        .btn-view-whatsapp { background-color: var(--whatsapp-green); }
        .btn-view-data { background-color: #6c757d; }
        .btn-view-ads { background-color: var(--selflix-teal); }
        .btn-delete-item { background-color: #dc3545; }
        
        /* Ajuste de Botões Superiores Mobile */
        @media (max-width: 576px) {
            .header-actions { text-align: center; }
            .group-buttons-top { flex-direction: column; width: 100%; }
            .group-buttons-top .btn { width: 100%; border-radius: 50px !important; margin-bottom: 5px; }
            .input-group { flex-direction: column; }
            .input-group .form-control { border-radius: 50px !important; margin-bottom: 10px; text-align: center; }
            .input-group .btn { border-radius: 50px !important; width: 100%; }
        }

        .paginacao { display: flex; justify-content: center; gap: 8px; margin: 30px 0 50px; flex-wrap: wrap; }
        .paginacao a, .paginacao span { display: flex; justify-content: center; align-items: center; width: 40px; height: 40px; border-radius: 50%; text-decoration: none; color: #000; background-color: #e0e0e0; transition: 0.3s; }
        .paginacao a:hover { background-color: #d0d0d0; }
        .paginacao .ativo { background-color: var(--selflix-teal); color: #fff; font-weight: bold; }
        .paginacao .proximo { border-radius: 20px; width: auto; padding: 0 20px; }

        .form-check-input:checked { background-color: var(--selflix-teal); border-color: var(--selflix-teal); }
        .switch-container { background-color: #f8f9fa; padding: 10px; border-radius: 8px; margin-top: 10px; border: 1px solid #eee; }
    </style>
</head>
<body>

    <?php if (file_exists('menu.php')) include_once 'menu.php'; ?>

    <div class="container-main">
        <div class="header-actions d-flex justify-content-between align-items-center mb-4 flex-wrap gap-3">
            <h2 class="mb-0"><i class="fas fa-building-circle-check me-2"></i> Empresas</h2>
            <div class="d-flex group-buttons-top gap-2">
                <a href="cadastrar_empresa_admin.php" class="btn btn-primary" style="background: var(--selflix-teal); border:none; border-radius: 50px; padding: 10px 20px;">
                    <i class="fas fa-plus"></i> Nova Empresa
                </a>
                <a href="gerar-csv-empresas.php?q=<?= urlencode($termo_busca) ?>" class="btn btn-success" style="border-radius: 50px; padding: 10px 20px;">
                    <i class="fas fa-file-csv"></i> Baixar CSV
                </a>
                <a href="painel-adm.php" class="btn btn-outline-secondary" style="border-radius: 50px; padding: 10px 20px;">
                    Painel
                </a>
            </div>
        </div>

        <form action="" method="GET" class="mb-4">
            <div class="input-group">
                <input type="text" name="q" class="form-control" placeholder="Buscar por nome, email ou CNPJ..." value="<?= htmlspecialchars($termo_busca) ?>" style="border-radius: 50px 0 0 50px;">
                <button class="btn btn-dark" type="submit" style="border-radius: 0 50px 50px 0;"><i class="fas fa-search"></i> Buscar</button>
            </div>
        </form>

        <div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-4">
            <?php foreach ($empresas as $empresa): ?>
            <div class="col">
                <div class="card card-empresa h-100 shadow-sm">
                    <div class="card-body d-flex flex-column">
                        <div class="d-flex justify-content-between">
                            <h5 class="fw-bold mb-0 text-truncate" style="max-width: 70%;"><?= htmlspecialchars($empresa['nome_empresa']); ?></h5>
                            <?php if(!empty($empresa['logotipo'])): ?>
                                <img src="<?= htmlspecialchars($empresa['logotipo']); ?>" class="card-empresa-logo">
                            <?php endif; ?>
                        </div>
                        <p class="text-muted small mb-3">ID: #<?= $empresa['id']; ?></p>
                        
                        <div class="small">
                            <p class="mb-1"><span class="info-label">Responsável:</span> <?= htmlspecialchars($empresa['contato'] ?? 'Não informado'); ?></p>
                            <p class="mb-1"><span class="info-label">CNPJ:</span> <?= htmlspecialchars($empresa['cnpj']); ?></p>
                            <p class="mb-1"><span class="info-label">Email:</span> <?= htmlspecialchars($empresa['email']); ?></p>
                        </div>

                        <div class="switch-container d-flex justify-content-between align-items-center">
                            <span class="small fw-bold"><i class="fas fa-star text-warning me-1"></i> Plano Pago</span>
                            <div class="form-check form-switch">
                                <input class="form-check-input switch-plano" type="checkbox" role="switch" 
                                       data-id="<?= $empresa['id'] ?>" 
                                       <?= ($empresa['tipo_plano'] === 'pago') ? 'checked' : ''; ?>>
                            </div>
                        </div>

                        <div class="d-flex justify-content-end gap-2 mt-auto pt-3 border-top">
                            <?php if(!empty($empresa['celular'])): ?>
                                <a href="https://wa.me/55<?= limparNumero($empresa['celular']) ?>" target="_blank" class="btn-service-icon btn-view-whatsapp" title="WhatsApp">
                                    <i class="fab fa-whatsapp"></i>
                                </a>
                            <?php endif; ?>

                            <button class="btn-service-icon btn-view-data" title="Detalhes" 
                                    onclick='verDadosEmpresa(<?= json_encode($empresa); ?>)'>
                                <i class="fas fa-eye"></i>
                            </button>
                            
                            <a href="listar-anuncios-empresa.php?id=<?= $empresa['id']; ?>" class="btn-service-icon btn-view-ads" title="Vagas">
                                <i class="fas fa-bullhorn"></i>
                            </a>
                            
                            <button class="btn-service-icon btn-delete-item" onclick="abrirModalExclusao('excluir_empresa.php?id=<?= $empresa['id']; ?>&csrf_token=<?= $csrf_token ?>')">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

        <?php if ($total_paginas > 1): ?>
            <?php
                $paginas_mostradas = 5;
                $metade = floor($paginas_mostradas / 2);
                $start_page = max(1, $pagina_atual - $metade);
                $end_page = min($total_paginas, $pagina_atual + $metade);
                if ($end_page - $start_page < $paginas_mostradas - 1) $start_page = max(1, $end_page - $paginas_mostradas + 1);
                $query_param = !empty($termo_busca) ? '&q=' . urlencode($termo_busca) : '';
            ?>
            <div class="paginacao mt-5">
                <?php if ($pagina_atual > 1): ?>
                    <a href="?pagina=<?= ($pagina_atual - 1) . $query_param ?>"><i class="fas fa-arrow-left"></i></a>
                <?php endif; ?>
                <?php for ($i = $start_page; $i <= $end_page; $i++): ?>
                    <a href="?pagina=<?= $i . $query_param ?>" class="<?= ($i == $pagina_atual) ? 'ativo' : ''; ?>"><?= $i; ?></a>
                <?php endfor; ?>
                <?php if ($pagina_atual < $total_paginas): ?>
                    <a href="?pagina=<?= ($pagina_atual + 1) . $query_param ?>" class="proximo">Próximo</a>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>

    <div class="modal fade" id="modalDadosEmpresa" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header text-white" style="background: var(--selflix-teal);">
                    <h5 class="modal-title"><i class="fas fa-info-circle me-2"></i> Detalhes da Empresa</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6"><label class="form-label fw-bold">Razão Social</label><input type="text" id="view_nome" class="form-control" readonly></div>
                        <div class="col-md-6"><label class="form-label fw-bold">CNPJ</label><input type="text" id="view_cnpj" class="form-control" readonly></div>
                        <div class="col-md-6"><label class="form-label fw-bold">E-mail</label><input type="email" id="view_email" class="form-control" readonly></div>
                        <div class="col-md-6"><label class="form-label fw-bold">Telefone</label><input type="text" id="view_celular" class="form-control" readonly></div>
                        <div class="col-12"><label class="form-label fw-bold">Endereço</label><input type="text" id="view_endereco" class="form-control" readonly></div>
                    </div>
                </div>
                <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Fechar</button></div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="modalExclusao" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content border-0 shadow">
                <div class="modal-body text-center p-5">
                    <i class="fas fa-exclamation-triangle fa-4x text-danger mb-4"></i>
                    <h4 class="fw-bold">Atenção!</h4>
                    <p>Deseja apagar esta empresa e todos os seus anúncios?</p>
                    <div class="d-flex gap-2 justify-content-center mt-4">
                        <button type="button" class="btn btn-light px-4" data-bs-dismiss="modal" style="border-radius: 50px;">Cancelar</button>
                        <a href="#" id="btnConfirmarExclusao" class="btn btn-danger px-4" style="border-radius: 50px;">Confirmar e Excluir</a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Lógica do Switch AJAX
        document.querySelectorAll('.switch-plano').forEach(function(el) {
            el.addEventListener('change', function() {
                const idEmpresa = this.getAttribute('data-id');
                const novoStatus = this.checked ? 'pago' : 'gratuito';
                const csrfToken = '<?= $csrf_token ?>';
                this.disabled = true;
                fetch('atualizar_plano_empresa.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: `id=${idEmpresa}&plano=${novoStatus}&csrf_token=${csrfToken}`
                })
                .then(response => response.json())
                .then(data => {
                    if (!data.success) {
                        alert('Erro ao atualizar: ' + data.error);
                        this.checked = !this.checked;
                    }
                })
                .catch(() => {
                    alert('Erro na requisição.');
                    this.checked = !this.checked;
                })
                .finally(() => { this.disabled = false; });
            });
        });

        function verDadosEmpresa(empresa) {
            document.getElementById('view_nome').value = empresa.nome_empresa || '';
            document.getElementById('view_cnpj').value = empresa.cnpj || '';
            document.getElementById('view_email').value = empresa.email || '';
            document.getElementById('view_celular').value = empresa.celular || '';
            document.getElementById('view_endereco').value = (empresa.rua || '') + ', ' + (empresa.numero || '') + ' - ' + (empresa.cidade || '');
            new bootstrap.Modal(document.getElementById('modalDadosEmpresa')).show();
        }

        function abrirModalExclusao(url) {
            document.getElementById('btnConfirmarExclusao').href = url;
            new bootstrap.Modal(document.getElementById('modalExclusao')).show();
        }
    </script>
</body>
</html>