<?php
// whatsapp_config.php - Página completa de configuração do WhatsApp
require_once 'conexao.php';
session_start();

if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Verificação FLEXÍVEL de sessão - adaptada à sua estrutura do login.php
$isLogged = false;

// Verifica de múltiplas formas (compatível com seu login.php)
if (isset($_SESSION['logado']) && $_SESSION['logado'] === true) {
    $isLogged = true;
} elseif (isset($_SESSION['usuario_id']) && !empty($_SESSION['usuario_id'])) {
    $isLogged = true;
} elseif (isset($_SESSION['usuario']['id']) && !empty($_SESSION['usuario']['id'])) {
    $isLogged = true;
}

// Se não estiver logado, redirecionar para login
if (!$isLogged) {
    header('Location: login.php');
    exit;
}

// Configurações da sessão - compatível com SEU login.php
$tenant_id = 0;
$nome_usuario = 'Usuário';
$email_usuario = '';
$permissao = 'usuario';

if (isset($_SESSION['usuario']) && is_array($_SESSION['usuario'])) {
    $usuarioData = $_SESSION['usuario'];
    $tenant_id = $usuarioData['tenant_id'] ?? 0;
    $clienteId = $usuarioData['id'] ?? 0;
    $nome_usuario = $usuarioData['nome'] ?? 'Usuário';
    $email_usuario = $usuarioData['email'] ?? '';
    $permissao = $usuarioData['permissao'] ?? 'usuario';
} else {
    // Fallback para variáveis individuais
    $tenant_id = $_SESSION['tenant_id'] ?? $_SESSION['usuario_id'] ?? 0;
    $clienteId = $_SESSION['usuario_id'] ?? $tenant_id;
    $nome_usuario = $_SESSION['nome_usuario'] ?? $_SESSION['nome'] ?? 'Usuário';
    $email_usuario = $_SESSION['email_usuario'] ?? $_SESSION['email'] ?? '';
    $permissao = $_SESSION['permissao'] ?? $_SESSION['nivel'] ?? 'usuario';
}

// Buscar configuração atual do WhatsApp
$config = null;
$error = '';
$success = '';
$test_message = '';

try {
    // Verificar se a tabela existe
    $checkTable = $conn->query("SHOW TABLES LIKE 'whatsapp_config'");
    if ($checkTable->num_rows == 0) {
        // Criar tabela se não existir
        $createTable = $conn->query("CREATE TABLE IF NOT EXISTS whatsapp_config (
            id INT PRIMARY KEY AUTO_INCREMENT,
            tenant_id INT NOT NULL,
            access_token TEXT NOT NULL,
            phone_number_id VARCHAR(50) NOT NULL,
            business_account_id VARCHAR(50) NOT NULL,
            webhook_verify_token VARCHAR(100) DEFAULT 'whatsapp_webhook_token',
            ativo TINYINT DEFAULT 1,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_tenant (tenant_id),
            INDEX idx_ativo (ativo)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
    }
    
    // Buscar configuração
    $stmt = $conn->prepare("SELECT * FROM whatsapp_config WHERE tenant_id = ? AND ativo = 1");
    $stmt->bind_param("i", $tenant_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $config = $result->fetch_assoc();
    $stmt->close();
    
} catch (Exception $e) {
    $error = "Erro ao buscar configuração: " . $e->getMessage();
}

// Processar formulário POST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_config'])) {
    $access_token = $_POST['access_token'] ?? '';
    $phone_number_id = $_POST['phone_number_id'] ?? '';
    $business_account_id = $_POST['business_account_id'] ?? '';
    $webhook_verify_token = $_POST['webhook_verify_token'] ?? 'whatsapp_webhook_token';
    
    // Validação básica
    if (empty($access_token) || empty($phone_number_id) || empty($business_account_id)) {
        $error = "Por favor, preencha todos os campos obrigatórios.";
    } else {
        try {
            if ($config) {
                // Atualizar configuração existente
                $stmt = $conn->prepare("UPDATE whatsapp_config SET 
                    access_token = ?, 
                    phone_number_id = ?,
                    business_account_id = ?,
                    webhook_verify_token = ?,
                    updated_at = NOW(),
                    ativo = 1
                    WHERE tenant_id = ?");
                
                $stmt->bind_param("ssssi", 
                    $access_token,
                    $phone_number_id,
                    $business_account_id,
                    $webhook_verify_token,
                    $tenant_id
                );
                
                $stmt->execute();
                $success = "Configuração atualizada com sucesso!";
                $stmt->close();
            } else {
                // Inserir nova configuração
                $stmt = $conn->prepare("INSERT INTO whatsapp_config 
                    (tenant_id, access_token, phone_number_id, business_account_id, webhook_verify_token, ativo, created_at) 
                    VALUES (?, ?, ?, ?, ?, 1, NOW())");
                
                $stmt->bind_param("issss",
                    $tenant_id,
                    $access_token,
                    $phone_number_id,
                    $business_account_id,
                    $webhook_verify_token
                );
                
                $stmt->execute();
                $success = "Configuração salva com sucesso!";
                $stmt->close();
            }
            
            // Recarregar configuração
            $stmt = $conn->prepare("SELECT * FROM whatsapp_config WHERE tenant_id = ? AND ativo = 1");
            $stmt->bind_param("i", $tenant_id);
            $stmt->execute();
            $result = $stmt->get_result();
            $config = $result->fetch_assoc();
            $stmt->close();
            
        } catch (Exception $e) {
            $error = "Erro ao salvar configuração: " . $e->getMessage();
        }
    }
}

// Processar desconexão
if (isset($_GET['action']) && $_GET['action'] === 'disconnect') {
    try {
        $stmt = $conn->prepare("UPDATE whatsapp_config SET ativo = 0, updated_at = NOW() WHERE tenant_id = ?");
        $stmt->bind_param("i", $tenant_id);
        $stmt->execute();
        $success = "WhatsApp desconectado com sucesso!";
        $config = null;
        $stmt->close();
    } catch (Exception $e) {
        $error = "Erro ao desconectar: " . $e->getMessage();
    }
}

// Testar conexão
if (isset($_GET['action']) && $_GET['action'] === 'test') {
    if ($config && !empty($config['access_token']) && !empty($config['phone_number_id'])) {
        try {
            $url = "https://graph.facebook.com/v17.0/{$config['phone_number_id']}";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Authorization: Bearer ' . $config['access_token']
            ]);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Para testes
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // Para testes
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $curlError = curl_error($ch);
            curl_close($ch);
            
            if ($curlError) {
                $test_message = "❌ Erro de cURL: " . htmlspecialchars($curlError);
            } elseif ($httpCode === 200) {
                $data = json_decode($response, true);
                $test_message = "✅ Conexão bem-sucedida!";
                if (isset($data['verified_name'])) {
                    $test_message .= " Nome verificado: " . htmlspecialchars($data['verified_name']);
                }
            } else {
                $test_message = "❌ Falha na conexão. Código HTTP: $httpCode";
                if ($response) {
                    $test_message .= " Resposta: " . htmlspecialchars(substr($response, 0, 200));
                }
            }
        } catch (Exception $e) {
            $test_message = "❌ Erro ao testar conexão: " . $e->getMessage();
        }
    } else {
        $test_message = "❌ Configure o WhatsApp primeiro para testar a conexão";
    }
}
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <link rel="icon" type="image/png" sizes="16x16" href="/favicon_io/favicon-16x16.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/favicon_io/favicon-32x32.png">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SON - Configuração WhatsApp</title>
    <meta name="csrf-token" content="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        /* Estilos Gerais */
        body {
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
            color: #333;
        }
        
        /* Conteúdo Principal */
        .content-wrapper {
            margin-top: 80px;
            padding: 20px;
            margin-right: 60px;
            transition: margin-right 0.3s ease;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            padding: 25px;
            border-radius: 8px;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.05);
        }
        
        h1 {
            color: #2c3e50;
            border-bottom: 2px solid #f1f1f1;
            padding-bottom: 12px;
            margin-bottom: 20px;
            font-size: 1.8rem;
        }
        
        /* Botões */
        .btn {
            padding: 8px 14px;
            border: none;
            border-radius: 4px;
            color: white;
            cursor: pointer;
            font-size: 0.9rem;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 5px;
            text-decoration: none;
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        
        .btn:active {
            transform: translateY(0);
        }
        
        .btn-whatsapp {
            background-color: #25D366;
        }
        
        .btn-whatsapp:hover {
            background-color: #128C7E;
        }
        
        .btn-test {
            background-color: #17a2b8;
        }
        
        .btn-test:hover {
            background-color: #138496;
        }
        
        .btn-secondary {
            background-color: #6c757d;
        }
        
        .btn-secondary:hover {
            background-color: #5a6268;
        }
        
        .btn-danger {
            background-color: #e74c3c;
        }
        
        .btn-danger:hover {
            background-color: #c0392b;
        }
        
        .btn-success {
            background-color: #27ae60;
        }
        
        .btn-success:hover {
            background-color: #219a52;
        }
        
        /* Formulário */
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #2c3e50;
        }
        
        .form-control {
            width: 100%;
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 0.95rem;
            transition: all 0.3s;
        }
        
        .form-control:focus {
            border-color: #25D366;
            outline: none;
            box-shadow: 0 0 0 2px rgba(37, 211, 102, 0.2);
        }
        
        .form-text {
            font-size: 0.85rem;
            color: #6c757d;
            margin-top: 5px;
        }
        
        /* Status da Conexão */
        .status-card {
            border: 2px solid #dee2e6;
            border-radius: 10px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            background: white;
        }
        
        .status-connected {
            border-color: #25D366;
            background-color: rgba(37, 211, 102, 0.1);
        }
        
        .status-disconnected {
            border-color: #e74c3c;
            background-color: rgba(231, 76, 60, 0.1);
        }
        
        .status-indicator {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 6px 12px;
            border-radius: 20px;
            font-weight: 600;
            color: white;
        }
        
        .status-connected .status-indicator {
            background-color: #25D366;
        }
        
        .status-disconnected .status-indicator {
            background-color: #6c757d;
        }
        
        .status-dot {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background-color: white;
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }
        
        .phone-masked {
            font-family: 'Courier New', monospace;
            background: #f8f9fa;
            padding: 5px 10px;
            border-radius: 4px;
            border: 1px solid #dee2e6;
        }
        
        /* Cartões de Informação */
        .card {
            border: 1px solid #dee2e6;
            border-radius: 8px;
            margin-bottom: 20px;
            background: white;
            overflow: hidden;
        }
        
        .card-header {
            background-color: #2c3e50;
            color: white;
            padding: 15px 20px;
            border-bottom: 1px solid #dee2e6;
        }
        
        .card-body {
            padding: 20px;
        }
        
        .step-card {
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            background: #f8f9fa;
        }
        
        .step-number {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 30px;
            height: 30px;
            background-color: #128C7E;
            color: white;
            border-radius: 50%;
            font-weight: bold;
            margin-right: 10px;
        }
        
        /* Alertas */
        .alert {
            border-radius: 8px;
            border: none;
            margin-bottom: 20px;
            padding: 15px 20px;
        }
        
        .alert-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .alert-danger {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .alert-info {
            background-color: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        
        .alert-warning {
            background-color: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
        
        /* Grid */
        .row {
            display: flex;
            flex-wrap: wrap;
            margin-right: -15px;
            margin-left: -15px;
        }
        
        .col-lg-5, .col-lg-7 {
            position: relative;
            width: 100%;
            padding-right: 15px;
            padding-left: 15px;
        }
        
        @media (min-width: 992px) {
            .col-lg-5 {
                flex: 0 0 41.666667%;
                max-width: 41.666667%;
            }
            
            .col-lg-7 {
                flex: 0 0 58.333333%;
                max-width: 58.333333%;
            }
        }
        
        /* Ações Rápidas */
        .acoes-rapidas {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }
        
        /* Mensagem Flutuante */
        .mensagem-flutuante {
            position: fixed;
            top: 90px;
            right: 25px;
            padding: 14px 24px;
            background: #2ecc71;
            color: white;
            border-radius: 4px;
            z-index: 2000;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.15);
            font-weight: 500;
            animation: slideIn 0.3s ease-out;
        }
        
        @keyframes slideIn {
            from {
                transform: translateY(-20px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }
        
        /* Input Group */
        .input-group {
            display: flex;
            align-items: center;
        }
        
        .input-group .form-control {
            flex: 1;
            border-top-right-radius: 0;
            border-bottom-right-radius: 0;
        }
        
        .input-group .btn-outline-secondary {
            border: 1px solid #ddd;
            border-left: 0;
            border-radius: 0 4px 4px 0;
            background: #f8f9fa;
            color: #495057;
            padding: 10px 15px;
        }
        
        /* Responsividade */
        @media (max-width: 768px) {
            .content-wrapper {
                margin-top: 80px;
                padding: 15px;
                margin-right: 0;
            }
            
            .container {
                padding: 18px;
            }
            
            .row {
                flex-direction: column;
            }
            
            .col-lg-5, .col-lg-7 {
                width: 100%;
                margin-bottom: 20px;
            }
            
            .acoes-rapidas {
                grid-template-columns: 1fr;
            }
            
            .btn {
                width: 100%;
                justify-content: center;
            }
        }
        
        /* Cabeçalho WhatsApp */
        .whatsapp-header {
            background: linear-gradient(135deg, #25D366, #128C7E);
            color: white;
            padding: 2rem;
            border-radius: 10px;
            margin-bottom: 2rem;
        }
        
        /* Barra Superior */
        .top-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        /* API Info */
        .api-info {
            background-color: #f8f9fa;
            border-left: 4px solid #25D366;
            padding: 1rem;
            margin: 1rem 0;
        }
        
        .api-info ul {
            margin: 0;
            padding-left: 20px;
        }
        
        .api-info li {
            margin-bottom: 5px;
        }
    </style>
</head>
<body>

<?php include 'menu_lateral.php'; ?>

    <!-- Conteúdo Principal -->
    <div class="content-wrapper">
        <div class="container">
            <!-- Cabeçalho WhatsApp -->
            <div class="whatsapp-header">
                <h1 style="color: white; border-bottom: none; margin-bottom: 10px;">
                    <i class="fab fa-whatsapp"></i> Configuração do WhatsApp Business
                </h1>
                <p style="margin: 0; font-size: 1.1rem;">Configure sua conexão com a API oficial do WhatsApp Business</p>
            </div>

            <!-- Alertas -->
            <?php if (!empty($success)): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success); ?>
                    <button type="button" class="btn-close" onclick="this.parentElement.style.display='none'" style="background: none; border: none; float: right; font-size: 1.5rem; cursor: pointer;">&times;</button>
                </div>
            <?php endif; ?>
            
            <?php if (!empty($error)): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($error); ?>
                    <button type="button" class="btn-close" onclick="this.parentElement.style.display='none'" style="background: none; border: none; float: right; font-size: 1.5rem; cursor: pointer;">&times;</button>
                </div>
            <?php endif; ?>
            
            <?php if (!empty($test_message)): ?>
                <div class="alert alert-info alert-dismissible fade show" role="alert">
                    <i class="fas fa-info-circle"></i> <?php echo htmlspecialchars($test_message); ?>
                    <button type="button" class="btn-close" onclick="this.parentElement.style.display='none'" style="background: none; border: none; float: right; font-size: 1.5rem; cursor: pointer;">&times;</button>
                </div>
            <?php endif; ?>

            <!-- Status da Conexão -->
            <div class="status-card <?php echo $config ? 'status-connected' : 'status-disconnected'; ?>">
                <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap;">
                    <div>
                        <h3 style="margin: 0 0 10px 0;">
                            <span class="status-indicator">
                                <span class="status-dot"></span>
                                <?php echo $config ? 'CONECTADO' : 'DESCONECTADO'; ?>
                            </span>
                        </h3>
                        <?php if ($config): ?>
                            <p style="margin: 5px 0;">
                                <strong>Phone Number ID:</strong> 
                                <span class="phone-masked"><?php echo htmlspecialchars($config['phone_number_id']); ?></span>
                            </p>
                            <p style="margin: 5px 0;">
                                <strong>Business Account ID:</strong> 
                                <span class="phone-masked"><?php echo htmlspecialchars($config['business_account_id']); ?></span>
                            </p>
                            <p style="margin: 5px 0 0 0;">
                                <strong>Configurado em:</strong> 
                                <?php echo date('d/m/Y H:i', strtotime($config['created_at'])); ?>
                            </p>
                        <?php else: ?>
                            <p style="margin: 5px 0 0 0;">Configure o WhatsApp Business para começar a enviar mensagens automatizadas.</p>
                        <?php endif; ?>
                    </div>
                    <div>
                        <?php if ($config): ?>
                            <a href="?action=test" class="btn btn-test">
                                <i class="fas fa-plug"></i> Testar Conexão
                            </a>
                            <a href="?action=disconnect" class="btn btn-danger" 
                               onclick="return confirm('Tem certeza que deseja desconectar o WhatsApp?')">
                                <i class="fas fa-power-off"></i> Desconectar
                            </a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <div class="row">
                <!-- Guia de Configuração -->
                <div class="col-lg-5">
                    <div class="card">
                        <div class="card-header">
                            <h4 style="margin: 0; font-size: 1.2rem;"><i class="fas fa-list-ol"></i> Como Configurar</h4>
                        </div>
                        <div class="card-body">
                            <div class="step-card">
                                <h5 style="margin: 0 0 8px 0;"><span class="step-number">1</span> Acesse o Facebook Developer</h5>
                                <p style="margin: 0 0 8px 0;">Vá para <a href="https://developers.facebook.com/apps/" target="_blank">developers.facebook.com/apps</a></p>
                                <a href="https://developers.facebook.com/apps/" target="_blank" class="btn" style="background-color: #3b5998; padding: 6px 12px; font-size: 0.85rem;">
                                    <i class="fab fa-facebook"></i> Abrir Facebook Developer
                                </a>
                            </div>
                            
                            <div class="step-card">
                                <h5 style="margin: 0 0 8px 0;"><span class="step-number">2</span> Crie um Aplicativo Business</h5>
                                <p style="margin: 0;">Clique em "Create App" e selecione "Business" como tipo.</p>
                            </div>
                            
                            <div class="step-card">
                                <h5 style="margin: 0 0 8px 0;"><span class="step-number">3</span> Adicione o WhatsApp</h5>
                                <p style="margin: 0;">No painel do aplicativo, adicione o produto "WhatsApp".</p>
                            </div>
                            
                            <div class="step-card">
                                <h5 style="margin: 0 0 8px 0;"><span class="step-number">4</span> Obtenha as Credenciais</h5>
                                <p style="margin: 0;">Você precisará de:
                                    <ul style="margin: 8px 0 0 20px; padding: 0;">
                                        <li><strong>Access Token</strong> (Token de acesso)</li>
                                        <li><strong>Phone Number ID</strong></li>
                                        <li><strong>Business Account ID</strong></li>
                                    </ul>
                                </p>
                            </div>
                            
                            <div class="step-card">
                                <h5 style="margin: 0 0 8px 0;"><span class="step-number">5</span> Configure o Webhook (Opcional)</h5>
                                <p style="margin: 0;">Configure o webhook para receber mensagens dos clientes.</p>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Informações Importantes -->
                    <div class="api-info mt-4">
                        <h5 style="margin: 0 0 10px 0;"><i class="fas fa-info-circle"></i> Informações Importantes</h5>
                        <ul class="mb-0">
                            <li>O Access Token é sensível - mantenha-o em segredo</li>
                            <li>Use tokens permanentes para ambiente de produção</li>
                            <li>Verifique as permissões do aplicativo no Facebook</li>
                            <li>Teste a conexão após configurar</li>
                        </ul>
                    </div>
                </div>

                <!-- Formulário de Configuração -->
                <div class="col-lg-7">
                    <div class="card">
                        <div class="card-header" style="background-color: #25D366;">
                            <h4 style="margin: 0; font-size: 1.2rem; color: white;">
                                <i class="fas fa-cog"></i> 
                                <?php echo $config ? 'Atualizar Configuração' : 'Configurar WhatsApp Business'; ?>
                            </h4>
                        </div>
                        <div class="card-body">
                            <form method="POST" action="" id="whatsappForm">
                                <input type="hidden" name="save_config" value="1">
                                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
                                
                                <div class="form-group">
                                    <label for="access_token" class="form-label">
                                        <strong>Access Token *</strong>
                                    </label>
                                    <div class="input-group">
                                        <input type="password" 
                                               class="form-control" 
                                               id="access_token" 
                                               name="access_token"
                                               value="<?php echo $config ? '•••••••••••••••' : ''; ?>"
                                               placeholder="EAA... (Token começa com EAA)"
                                               required
                                               autocomplete="off">
                                        <button class="btn-outline-secondary" 
                                                type="button" 
                                                onclick="togglePassword('access_token')">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                    </div>
                                    <div class="form-text">
                                        Token de acesso permanente da API do WhatsApp Business
                                    </div>
                                </div>
                                
                                <div style="display: flex; gap: 15px; margin-bottom: 20px;">
                                    <div style="flex: 1;">
                                        <label for="phone_number_id" class="form-label">
                                            <strong>Phone Number ID *</strong>
                                        </label>
                                        <input type="text" 
                                               class="form-control" 
                                               id="phone_number_id" 
                                               name="phone_number_id"
                                               value="<?php echo htmlspecialchars($config['phone_number_id'] ?? ''); ?>"
                                               placeholder="Ex: 123456789012345"
                                               required>
                                        <div class="form-text">
                                            ID do número de telefone do WhatsApp
                                        </div>
                                    </div>
                                    
                                    <div style="flex: 1;">
                                        <label for="business_account_id" class="form-label">
                                            <strong>Business Account ID *</strong>
                                        </label>
                                        <input type="text" 
                                               class="form-control" 
                                               id="business_account_id" 
                                               name="business_account_id"
                                               value="<?php echo htmlspecialchars($config['business_account_id'] ?? ''); ?>"
                                               placeholder="Ex: 987654321098765"
                                               required>
                                        <div class="form-text">
                                            ID da conta de negócios do Facebook
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="form-group">
                                    <label for="webhook_verify_token" class="form-label">
                                        <strong>Webhook Verify Token</strong>
                                    </label>
                                    <input type="text" 
                                           class="form-control" 
                                           id="webhook_verify_token" 
                                           name="webhook_verify_token"
                                           value="<?php echo htmlspecialchars($config['webhook_verify_token'] ?? 'whatsapp_webhook_token'); ?>"
                                           placeholder="Token para verificar webhook">
                                    <div class="form-text">
                                        Token usado para verificar o webhook (opcional)
                                    </div>
                                </div>
                                
                                <div class="alert alert-warning">
                                    <h5 style="margin: 0 0 10px 0;"><i class="fas fa-exclamation-triangle"></i> Atenção!</h5>
                                    <ul style="margin: 0; padding-left: 20px;">
                                        <li>Estas credenciais são sensíveis e devem ser protegidas</li>
                                        <li>Nunca compartilhe seu Access Token</li>
                                        <li>Use HTTPS em produção</li>
                                        <li>Configure as permissões corretas no Facebook App</li>
                                    </ul>
                                </div>
                                
                                <div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
                                    <a href="index.php" class="btn btn-secondary">
                                        <i class="fas fa-arrow-left"></i> Voltar
                                    </a>
                                    <button type="submit" class="btn btn-whatsapp">
                                        <i class="fas fa-save"></i> 
                                        <?php echo $config ? 'Atualizar Configuração' : 'Salvar Configuração'; ?>
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                    
                    <!-- Teste de Conexão -->
                    <?php if ($config): ?>
                        <div class="card mt-4">
                            <div class="card-header" style="background-color: #17a2b8;">
                                <h4 style="margin: 0; font-size: 1.2rem; color: white;"><i class="fas fa-vial"></i> Teste de Conexão</h4>
                            </div>
                            <div class="card-body">
                                <p>Verifique se sua configuração está funcionando corretamente:</p>
                                <div style="display: grid;">
                                    <a href="?action=test" class="btn btn-test" style="padding: 12px; font-size: 1rem;">
                                        <i class="fas fa-plug"></i> Testar Conexão com WhatsApp API
                                    </a>
                                </div>
                                <div style="margin-top: 15px;">
                                    <small class="text-muted">
                                        Este teste verifica se as credenciais estão corretas e se a API está acessível.
                                        Se falhar, verifique o Access Token e o Phone Number ID.
                                    </small>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Ações Rápidas -->
                    <div class="card mt-4">
                        <div class="card-header">
                            <h4 style="margin: 0; font-size: 1.2rem;"><i class="fas fa-bolt"></i> Ações Rápidas</h4>
                        </div>
                        <div class="card-body">
                            <div class="acoes-rapidas">
                                <a href="enviar_mensagem.php" class="btn" style="background-color: #3498db;">
                                    <i class="fas fa-paper-plane"></i> Enviar Mensagem
                                </a>
                                <a href="templates_whatsapp.php" class="btn" style="background-color: #27ae60;">
                                    <i class="fas fa-file-alt"></i> Templates
                                </a>
                                <a href="relatorios_whatsapp.php" class="btn" style="background-color: #17a2b8;">
                                    <i class="fas fa-chart-bar"></i> Relatórios
                                </a>
                                <a href="webhook_config.php" class="btn" style="background-color: #f39c12;">
                                    <i class="fas fa-link"></i> Configurar Webhook
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Rodapé -->
            <footer class="pt-3 mt-4 text-muted border-top" style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #dee2e6;">
                <div style="display: flex; justify-content: space-between; flex-wrap: wrap;">
                    <div>
                        <p style="margin: 0;">
                            <i class="fab fa-whatsapp" style="color: #25D366;"></i> 
                            WhatsApp Business API - SON CRM
                        </p>
                    </div>
                    <div style="text-align: right;">
                        <p style="margin: 0;">
                            Tenant ID: <?php echo htmlspecialchars($tenant_id); ?> | 
                            Usuário: <?php echo htmlspecialchars($nome_usuario); ?>
                        </p>
                    </div>
                </div>
            </footer>
        </div>
    </div>

    <script>
        // Função para mostrar/esconder senha
        function togglePassword(inputId) {
            const input = document.getElementById(inputId);
            const button = input.nextElementSibling;
            const icon = button.querySelector('i');
            
            if (input.type === 'password') {
                input.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                input.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        }
        
        // Mostrar senha ao focar no campo
        document.getElementById('access_token').addEventListener('focus', function() {
            if (this.value === '•••••••••••••••') {
                this.value = '';
            }
        });
        
        // Esconder senha ao sair do campo (se não foi alterada)
        document.getElementById('access_token').addEventListener('blur', function() {
            if (this.value === '' && <?php echo $config ? 'true' : 'false'; ?>) {
                this.value = '•••••••••••••••';
            }
        });
        
        // Validação do formulário
        document.getElementById('whatsappForm').addEventListener('submit', function(e) {
            const accessToken = document.getElementById('access_token').value;
            const phoneNumberId = document.getElementById('phone_number_id').value;
            const businessAccountId = document.getElementById('business_account_id').value;
            
            if (!accessToken || accessToken === '•••••••••••••••') {
                e.preventDefault();
                Swal.fire({
                    title: 'Atenção!',
                    text: 'Por favor, insira o Access Token',
                    icon: 'warning',
                    confirmButtonText: 'OK'
                });
                document.getElementById('access_token').focus();
                return false;
            }
            
            if (!phoneNumberId) {
                e.preventDefault();
                Swal.fire({
                    title: 'Atenção!',
                    text: 'Por favor, insira o Phone Number ID',
                    icon: 'warning',
                    confirmButtonText: 'OK'
                });
                document.getElementById('phone_number_id').focus();
                return false;
            }
            
            if (!businessAccountId) {
                e.preventDefault();
                Swal.fire({
                    title: 'Atenção!',
                    text: 'Por favor, insira o Business Account ID',
                    icon: 'warning',
                    confirmButtonText: 'OK'
                });
                document.getElementById('business_account_id').focus();
                return false;
            }
            
            return true;
        });
        
        // Confirmação para desconectar
        document.querySelectorAll('a[href*="action=disconnect"]').forEach(link => {
            link.addEventListener('click', function(e) {
                if (!confirm('Tem certeza que deseja desconectar o WhatsApp?')) {
                    e.preventDefault();
                }
            });
        });
        
        // Auto-focus no campo de pesquisa ao carregar a página
        document.addEventListener('DOMContentLoaded', function() {
            // Foca no primeiro campo se não há configuração
            if (!<?php echo $config ? 'true' : 'false'; ?>) {
                setTimeout(() => {
                    const accessTokenField = document.getElementById('access_token');
                    if (accessTokenField) {
                        accessTokenField.focus();
                    }
                }, 300);
            }
        });
    </script>
    
    <?php include 'sino_notificacoes.php'; ?>
</body>
</html>