<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once 'includes/funcoes.php';
include 'includes/header.php';

$pdo = conectarBanco();

// Buscar empresas ativas
$empresas = $pdo->query("SELECT id, nome, token, ambiente FROM empresas WHERE ativo = 1 ORDER BY nome")->fetchAll(PDO::FETCH_ASSOC);

// Processar ações
$mensagem = '';
$tipoMensagem = '';

// Criar webhook
if (isset($_POST['acao']) && $_POST['acao'] == 'criar') {
    $empresa_id = $_POST['empresa_id'];
    $url = $_POST['url'];
    $event = 'nfsen';
    
    // Buscar token da empresa
    $stmt = $pdo->prepare("SELECT token, ambiente FROM empresas WHERE id = ?");
    $stmt->execute([$empresa_id]);
    $empresa = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($empresa) {
        $baseUrl = $empresa['ambiente'] == 'producao' ? 'https://api.focusnfe.com.br/v2' : 'https://homologacao.focusnfe.com.br/v2';
        
        $data = [
            'cnpj' => $empresa['cnpj'] ?? '',
            'event' => $event,
            'url' => $url
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $baseUrl . '/hooks');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Authorization: Basic ' . base64_encode($empresa['token'] . ':')
        ]);
        $resposta = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode == 200) {
            $dados = json_decode($resposta, true);
            
            // Salvar no banco
            $stmt = $pdo->prepare("INSERT INTO webhooks (empresa_id, hook_id, event, url) VALUES (?, ?, ?, ?)");
            $stmt->execute([$empresa_id, $dados['id'], $event, $url]);
            
            $mensagem = "Webhook criado com sucesso!";
            $tipoMensagem = "success";
        } else {
            $mensagem = "Erro ao criar webhook: " . $resposta;
            $tipoMensagem = "danger";
        }
    }
}

// Excluir webhook
if (isset($_GET['excluir']) && isset($_GET['hook_id'])) {
    $id = $_GET['excluir'];
    $hook_id = $_GET['hook_id'];
    
    // Buscar empresa
    $stmt = $pdo->prepare("SELECT w.*, e.token, e.ambiente FROM webhooks w JOIN empresas e ON w.empresa_id = e.id WHERE w.id = ?");
    $stmt->execute([$id]);
    $webhook = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($webhook) {
        $baseUrl = $webhook['ambiente'] == 'producao' ? 'https://api.focusnfe.com.br/v2' : 'https://homologacao.focusnfe.com.br/v2';
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $baseUrl . '/hooks/' . $hook_id);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Basic ' . base64_encode($webhook['token'] . ':')
        ]);
        $resposta = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode == 200) {
            $stmt = $pdo->prepare("DELETE FROM webhooks WHERE id = ?");
            $stmt->execute([$id]);
            $mensagem = "Webhook excluído com sucesso!";
            $tipoMensagem = "success";
        } else {
            $mensagem = "Erro ao excluir webhook: " . $resposta;
            $tipoMensagem = "danger";
        }
    }
}

// Listar webhooks
$webhooks = $pdo->query("
    SELECT w.*, e.nome as empresa_nome, e.ambiente 
    FROM webhooks w 
    JOIN empresas e ON w.empresa_id = e.id 
    ORDER BY w.created_at DESC
")->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gerenciar Webhooks - Focus NFe</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        .card-shadow { box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .webhook-card { transition: transform 0.2s; }
        .webhook-card:hover { transform: translateY(-5px); }
        .event-badge { background-color: #17a2b8; color: white; padding: 5px 10px; border-radius: 20px; font-size: 12px; }
    </style>
</head>
<body>

<div class="container-fluid mt-3">
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <h1><i class="bi bi-webhook"></i> Gerenciar Webhooks</h1>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalCriarWebhook">
            <i class="bi bi-plus-circle"></i> Novo Webhook
        </button>
    </div>

    <?php if ($mensagem): ?>
        <div class="alert alert-<?php echo $tipoMensagem; ?> alert-dismissible fade show" role="alert">
            <?php echo $mensagem; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- Cards de Informação -->
    <div class="row mb-4">
        <div class="col-md-4 mb-3">
            <div class="card bg-info text-white card-shadow">
                <div class="card-body">
                    <h6><i class="bi bi-question-circle"></i> O que é Webhook?</h6>
                    <p class="small mb-0">Webhooks são notificações automáticas que a Focus NFe envia para sua URL quando o status da nota muda.</p>
                </div>
            </div>
        </div>
        <div class="col-md-4 mb-3">
            <div class="card bg-success text-white card-shadow">
                <div class="card-body">
                    <h6><i class="bi bi-lightning"></i> Eventos disponíveis</h6>
                    <p class="small mb-0">Para NFSe Nacional, use o evento <strong>nfsen</strong> - notifica quando a nota é autorizada ou rejeitada.</p>
                </div>
            </div>
        </div>
        <div class="col-md-4 mb-3">
            <div class="card bg-warning text-dark card-shadow">
                <div class="card-body">
                    <h6><i class="bi bi-arrow-repeat"></i> Tentativas</h6>
                    <p class="small mb-0">Se falhar, reenvia após: 1min, 30min, 1h, 3h, 24h (máximo 5 tentativas).</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Lista de Webhooks -->
    <div class="card card-shadow">
        <div class="card-header bg-primary text-white">
            <strong><i class="bi bi-list-ul"></i> Webhooks Cadastrados</strong>
        </div>
        <div class="card-body">
            <?php if (count($webhooks) > 0): ?>
                <div class="row">
                    <?php foreach ($webhooks as $webhook): ?>
                    <div class="col-md-6 mb-3">
                        <div class="card webhook-card h-100">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <span class="event-badge"><?php echo strtoupper($webhook['event']); ?></span>
                                        <span class="badge <?php echo $webhook['ambiente'] == 'producao' ? 'bg-danger' : 'bg-warning'; ?> ms-2">
                                            <?php echo $webhook['ambiente']; ?>
                                        </span>
                                    </div>
                                    <a href="?excluir=<?php echo $webhook['id']; ?>&hook_id=<?php echo $webhook['hook_id']; ?>" 
                                       class="btn btn-sm btn-danger" 
                                       onclick="return confirm('Tem certeza que deseja excluir este webhook?')">
                                        <i class="bi bi-trash"></i>
                                    </a>
                                </div>
                                <hr>
                                <div><strong><i class="bi bi-building"></i> Empresa:</strong> <?php echo htmlspecialchars($webhook['empresa_nome']); ?></div>
                                <div class="mt-2"><strong><i class="bi bi-link"></i> URL:</strong></div>
                                <code class="small"><?php echo htmlspecialchars($webhook['url']); ?></code>
                                <div class="mt-2"><strong><i class="bi bi-calendar"></i> Criado em:</strong> <?php echo date('d/m/Y H:i', strtotime($webhook['created_at'])); ?></div>
                                <div class="mt-2"><strong><i class="bi bi-hash"></i> ID Focus:</strong> <code><?php echo $webhook['hook_id']; ?></code></div>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="text-center text-muted py-4">
                    <i class="bi bi-inbox fs-1"></i>
                    <p>Nenhum webhook cadastrado. Clique em "Novo Webhook" para criar um.</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Modal Criar Webhook -->
    <div class="modal fade" id="modalCriarWebhook" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST">
                    <div class="modal-header bg-primary text-white">
                        <h5 class="modal-title"><i class="bi bi-plus-circle"></i> Criar Webhook</h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="acao" value="criar">
                        
                        <div class="mb-3">
                            <label class="form-label"><i class="bi bi-building"></i> Empresa *</label>
                            <select class="form-select" name="empresa_id" required>
                                <option value="">Selecione a empresa</option>
                                <?php foreach ($empresas as $emp): ?>
                                <option value="<?php echo $emp['id']; ?>">
                                    <?php echo htmlspecialchars($emp['nome']); ?>
                                    <span class="badge <?php echo $emp['ambiente'] == 'producao' ? 'bg-danger' : 'bg-warning'; ?>">
                                        <?php echo $emp['ambiente']; ?>
                                    </span>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label"><i class="bi bi-tag"></i> Evento</label>
                            <input type="text" class="form-control" value="nfsen" readonly>
                            <small class="text-muted">Evento para NFSe Nacional (Padrão Nacional)</small>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label"><i class="bi bi-link"></i> URL para notificação *</label>
                            <input type="url" class="form-control" name="url" required 
                                   placeholder="https://seudominio.com/webhook_receiver.php">
                            <small class="text-muted">URL que receberá as notificações POST quando a nota mudar de status</small>
                        </div>
                        
                        <div class="alert alert-info small">
                            <i class="bi bi-info-circle"></i> 
                            Quando a nota for autorizada ou rejeitada, a Focus enviará uma notificação POST para esta URL.
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                        <button type="submit" class="btn btn-primary">Criar Webhook</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

<?php include 'includes/footer.php'; ?>