<?php
/**
 * WhatsApp Integration - MontaLoja SaaS
 * Sistema de Notificações com Evolution API
 */
require_once __DIR__ . '/../../../includes/config.php';
require_once __DIR__ . '/../../../includes/check-access.php';
require_once __DIR__ . '/../../../includes/whatsapp/EvolutionAPI.php';
require_once __DIR__ . '/../../../includes/whatsapp/WhatsAppNotification.php';

$pdo = getDB();
$userId = $_SESSION['user_id'] ?? null;
$storeId = $_SESSION['store_id'] ?? null;

// Verificar se é requisição AJAX
$isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
$isAjax = $isAjax || (isset($_POST['action']) && in_array($_POST['action'], ['get_qrcode', 'check_status', 'send_test']));

if (!$userId || !$storeId) {
    if ($isAjax) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'error' => 'Sessão expirada. Faça login novamente.']);
        exit;
    }
    header('Location: /pages/login.php');
    exit;
}

$userStmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$userStmt->execute([$userId]);
$user = $userStmt->fetch(PDO::FETCH_ASSOC);

$storeStmt = $pdo->prepare("SELECT * FROM stores WHERE id = ?");
$storeStmt->execute([$storeId]);
$store = $storeStmt->fetch(PDO::FETCH_ASSOC);

// Carregar configuração do WhatsApp global
$globalConfigStmt = $pdo->prepare("SELECT * FROM whatsapp_config WHERE store_id = 0");
$globalConfigStmt->execute();
$globalConfig = $globalConfigStmt->fetch(PDO::FETCH_ASSOC);

// Carregar configuração da loja
$configStmt = $pdo->prepare("SELECT * FROM whatsapp_config WHERE store_id = ?");
$configStmt->execute([$storeId]);
$whatsappConfig = $configStmt->fetch(PDO::FETCH_ASSOC);

if ($whatsappConfig) {
    // Forçar o uso do tipo de integração global, mas permitir número próprio
    $whatsappConfig['integration_type'] = $globalConfig['integration_type'] ?? 'evolution';
} else {
    if ($globalConfig) {
        // Criar config baseada na global com nome da instância da loja
        $instanceName = $store['slug'] ?? $store['subdomain'] ?? 'loja-' . $storeId;
        $whatsappConfig = [
            'api_url' => $globalConfig['api_url'],
            'api_key' => $globalConfig['api_key'],
            'instance_name' => $instanceName,
            'notify_new_order' => $globalConfig['notify_new_order'] ?? 1,
            'notify_status_change' => $globalConfig['notify_status_change'] ?? 1,
            'notify_payment' => $globalConfig['notify_payment'] ?? 1,
            'notify_shipping' => $globalConfig['notify_shipping'] ?? 1,
            'is_connected' => 0,
            'is_global' => true,
            'integration_type' => $globalConfig['integration_type'] ?? 'evolution',
            'whatsapp_number' => ''
        ];
    }
}

// Carregar templates
$templatesStmt = $pdo->prepare("SELECT * FROM whatsapp_templates WHERE store_id = ? ORDER BY template_type");
$templatesStmt->execute([$storeId]);
$templates = $templatesStmt->fetchAll(PDO::FETCH_ASSOC);

// Carregar histórico de notificações
$logsStmt = $pdo->prepare("
    SELECT wl.*, o.id as order_number 
    FROM whatsapp_notifications_log wl
    LEFT JOIN orders o ON wl.order_id = o.id
    WHERE wl.store_id = ? 
    ORDER BY wl.created_at DESC 
    LIMIT 20
");
$logsStmt->execute([$storeId]);
$notificationLogs = $logsStmt->fetchAll(PDO::FETCH_ASSOC);

// Processar formulário
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'save_config') {
        $integrationType = $globalConfig['integration_type'] ?? 'evolution';
        $whatsappNumber = preg_replace('/[^0-9]/', '', $_POST['whatsapp_number'] ?? '');
        $apiUrl = trim($_POST['api_url'] ?? '');
        $apiKey = trim($_POST['api_key'] ?? '');
        $instanceName = trim($_POST['instance_name'] ?? '');
        $notifyNewOrder = isset($_POST['notify_new_order']) ? 1 : 0;
        $notifyStatusChange = isset($_POST['notify_status_change']) ? 1 : 0;
        $notifyPayment = isset($_POST['notify_payment']) ? 1 : 0;
        $notifyShipping = isset($_POST['notify_shipping']) ? 1 : 0;
        
        if ($integrationType === 'evolution' && (empty($apiUrl) || empty($apiKey) || empty($instanceName))) {
            $message = 'Preencha todos os campos obrigatórios para Evolution API.';
            $messageType = 'error';
        } elseif ($integrationType === 'api_send' && empty($whatsappNumber)) {
            $message = 'Preencha o Número do WhatsApp para o Link Direto.';
            $messageType = 'error';
        } else {
            try {
                if ($whatsappConfig && empty($whatsappConfig['is_global'])) {
                    $stmt = $pdo->prepare("
                        UPDATE whatsapp_config 
                        SET integration_type = ?, whatsapp_number = ?, api_url = ?, api_key = ?, instance_name = ?,
                            notify_new_order = ?, notify_status_change = ?,
                            notify_payment = ?, notify_shipping = ?, updated_at = NOW()
                        WHERE store_id = ?
                    ");
                    $stmt->execute([$integrationType, $whatsappNumber, $apiUrl, $apiKey, $instanceName, $notifyNewOrder, $notifyStatusChange, $notifyPayment, $notifyShipping, $storeId]);
                } else {
                    $stmt = $pdo->prepare("
                        INSERT INTO whatsapp_config 
                        (store_id, integration_type, whatsapp_number, api_url, api_key, instance_name, notify_new_order, notify_status_change, notify_payment, notify_shipping)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");
                    $stmt->execute([$storeId, $integrationType, $whatsappNumber, $apiUrl, $apiKey, $instanceName, $notifyNewOrder, $notifyStatusChange, $notifyPayment, $notifyShipping]);
                }
                
                $configStmt->execute([$storeId]);
                $whatsappConfig = $configStmt->fetch(PDO::FETCH_ASSOC);
                if ($whatsappConfig) {
                    $whatsappConfig['integration_type'] = $globalConfig['integration_type'] ?? 'evolution';
                    $whatsappConfig['whatsapp_number'] = $globalConfig['whatsapp_number'] ?? '';
                }
                
                $message = 'Configurações salvas com sucesso!';
                $messageType = 'success';
            } catch (Exception $e) {
                $message = 'Erro ao salvar: ' . $e->getMessage();
                $messageType = 'error';
            }
        }
    }
    
    if ($action === 'test_connection') {
        if ($whatsappConfig) {
            try {
                $api = new EvolutionAPI($whatsappConfig['api_url'], $whatsappConfig['api_key'], $whatsappConfig['instance_name']);
                $result = $api->getConnectionState();
                
                if ($result['success'] && isset($result['data']['state'])) {
                    $state = $result['data']['state'];
                    if ($state === 'open') {
                        $pdo->prepare("UPDATE whatsapp_config SET is_connected = 1 WHERE store_id = ?")->execute([$storeId]);
                        $whatsappConfig['is_connected'] = 1;
                        $message = 'WhatsApp conectado com sucesso!';
                        $messageType = 'success';
                    } else {
                        $message = 'WhatsApp não está conectado. Estado: ' . $state;
                        $messageType = 'warning';
                    }
                } else {
                    $message = 'Erro ao verificar conexão: ' . ($result['error'] ?? 'Resposta inválida');
                    $messageType = 'error';
                }
            } catch (Exception $e) {
                $message = 'Erro: ' . $e->getMessage();
                $messageType = 'error';
            }
        } else {
            $message = 'Configure a API primeiro.';
            $messageType = 'error';
        }
    }
    
    if ($action === 'get_qrcode') {
        header('Content-Type: application/json');
        if ($whatsappConfig) {
            try {
                $api = new EvolutionAPI($whatsappConfig['api_url'], $whatsappConfig['api_key'], $whatsappConfig['instance_name']);
                $instanceName = $whatsappConfig['instance_name'];
                
                // Verificar se instância existe
                $status = $api->getConnectionState($instanceName);
                
                // Se instância não existe, criar
                $notFound = ($status['http_code'] === 404);
                if (!$notFound && isset($status['data'])) {
                    $dataStr = json_encode($status['data']);
                    $notFound = (stripos($dataStr, 'not found') !== false);
                }
                
                if ($notFound) {
                    // Criar instância
                    $create = $api->createInstance($instanceName);
                    if (!$create['success'] && $create['http_code'] !== 201) {
                        echo json_encode(['success' => false, 'error' => 'Erro ao criar instância: ' . json_encode($create['data'])]);
                        exit;
                    }
                    sleep(1);
                }
                
                // Conectar e obter QR Code
                $result = $api->connectInstance($instanceName);
                
                // Tentar encontrar o QR Code na resposta
                $qrcode = null;
                if (isset($result['data']['base64'])) {
                    $qrcode = $result['data']['base64'];
                } elseif (isset($result['data']['qrcode']['base64'])) {
                    $qrcode = $result['data']['qrcode']['base64'];
                } elseif (isset($result['data']['code'])) {
                    $qrcode = $result['data']['code'];
                }
                
                if ($qrcode) {
                    if (strpos($qrcode, 'data:image') !== 0) {
                        $qrcode = 'data:image/png;base64,' . $qrcode;
                    }
                    echo json_encode(['success' => true, 'qrcode' => $qrcode, 'instance' => $instanceName]);
                } elseif (isset($result['data']['state']) && $result['data']['state'] === 'open') {
                    echo json_encode(['success' => true, 'connected' => true, 'message' => 'WhatsApp já está conectado!']);
                } else {
                    echo json_encode(['success' => false, 'error' => 'Erro ao gerar QR Code', 'debug' => $result['data']]);
                }
            } catch (Exception $e) {
                echo json_encode(['success' => false, 'error' => $e->getMessage()]);
            }
        } else {
            echo json_encode(['success' => false, 'error' => 'Configure a API primeiro']);
        }
        exit;
    }
    
    if ($action === 'send_test') {
        $testPhone = trim($_POST['test_phone'] ?? '');
        if ($whatsappConfig && !empty($testPhone)) {
            try {
                $integrationType = $whatsappConfig['integration_type'] ?? 'evolution';
                $testMessage = "*Mensagem de Teste*\n\nSua integração WhatsApp do MontaLoja está funcionando!\n\n_Enviado às " . date('H:i:s') . "_";
                
                if ($integrationType === 'api_send') {
                    $url = "https://api.whatsapp.com/send/?phone=" . urlencode($testPhone) . "&text=" . urlencode($testMessage);
                    $message = 'Link gerado com sucesso. <a href="' . htmlspecialchars($url) . '" target="_blank" style="color: inherit; text-decoration: underline;">Clique aqui para abrir o WhatsApp</a>';
                    $messageType = 'success';
                } else {
                    $api = new EvolutionAPI($whatsappConfig['api_url'], $whatsappConfig['api_key'], $whatsappConfig['instance_name']);
                    $result = $api->sendText($testPhone, $testMessage);
                    
                    if ($result['success']) {
                        $message = 'Mensagem de teste enviada com sucesso!';
                        $messageType = 'success';
                    } else {
                        $message = 'Erro ao enviar: ' . ($result['error'] ?? json_encode($result['data']));
                        $messageType = 'error';
                    }
                }
            } catch (Exception $e) {
                $message = 'Erro: ' . $e->getMessage();
                $messageType = 'error';
            }
        } else {
            $message = 'Informe o número para teste.';
            $messageType = 'error';
        }
    }
    
    if ($action === 'save_template') {
        $templateType = $_POST['template_type'] ?? '';
        $templateContent = $_POST['template_content'] ?? '';
        
        if (!empty($templateType) && !empty($templateContent)) {
            try {
                $stmt = $pdo->prepare("
                    INSERT INTO whatsapp_templates (store_id, template_type, template_name, template_content)
                    VALUES (?, ?, ?, ?)
                    ON DUPLICATE KEY UPDATE template_content = VALUES(template_content), updated_at = NOW()
                ");
                $stmt->execute([$storeId, $templateType, ucfirst(str_replace('_', ' ', $templateType)), $templateContent]);
                
                $message = 'Template salvo com sucesso!';
                $messageType = 'success';
                
                $templatesStmt->execute([$storeId]);
                $templates = $templatesStmt->fetchAll(PDO::FETCH_ASSOC);
            } catch (Exception $e) {
                $message = 'Erro ao salvar template: ' . $e->getMessage();
                $messageType = 'error';
            }
        }
    }
}

$pageTitle = 'WhatsApp';
include __DIR__ . '/../../../includes/dashboard-header.php';
?>

<?php include __DIR__ . '/../../../includes/responsive-styles.php'; ?>

<style>
.whatsapp-container {
    display: grid;
    grid-template-columns: 1fr;
    gap: 1.5rem;
    margin-top: 1rem;
}

.card {
    background: var(--bg-card);
    border-radius: 12px;
    padding: 1.5rem;
    border: 1px solid var(--border);
}

.card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 1.5rem;
    padding-bottom: 1rem;
    border-bottom: 1px solid var(--border);
}

.card-header h2 {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    font-size: 1.1rem;
    font-weight: 600;
    margin: 0;
}

.form-group {
    margin-bottom: 1rem;
}

.form-group label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: 500;
    font-size: 0.9rem;
}

.form-group input,
.form-group textarea,
.form-group select {
    width: 100%;
    padding: 0.75rem 1rem;
    background: var(--bg-darker);
    border: 1px solid var(--border);
    border-radius: 8px;
    color: var(--text-primary);
    font-size: 0.95rem;
}

.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
    outline: none;
    border-color: var(--primary);
}

.form-group textarea {
    min-height: 120px;
    resize: vertical;
    font-family: monospace;
}

.form-group small {
    display: block;
    margin-top: 0.35rem;
    color: var(--text-muted);
    font-size: 0.8rem;
}

.form-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1rem;
}

.checkbox-group {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 0.75rem;
    background: var(--bg-darker);
    border-radius: 8px;
    cursor: pointer;
}

.checkbox-group input[type="checkbox"] {
    width: 18px;
    height: 18px;
    accent-color: var(--primary);
}

.checkbox-group label {
    margin: 0;
    cursor: pointer;
}

.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
    padding: 0.75rem 1.25rem;
    border-radius: 8px;
    font-size: 0.9rem;
    font-weight: 500;
    cursor: pointer;
    border: none;
    transition: all 0.2s;
}

.btn-primary {
    background: linear-gradient(135deg, #25D366, #128C7E);
    color: white;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(37, 211, 102, 0.3);
}

.btn-secondary {
    background: var(--bg-darker);
    color: var(--text-primary);
    border: 1px solid var(--border);
}

.btn-secondary:hover {
    background: var(--border);
}

.btn-outline {
    background: transparent;
    color: var(--primary);
    border: 1px solid var(--primary);
}

.btn-group {
    display: flex;
    gap: 0.75rem;
    flex-wrap: wrap;
}

.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 0.35rem;
    padding: 0.4rem 0.75rem;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 500;
}

.status-connected {
    background: rgba(34, 197, 94, 0.15);
    color: #22C55E;
}

.status-disconnected {
    background: rgba(239, 68, 68, 0.15);
    color: #EF4444;
}

.alert {
    padding: 1rem;
    border-radius: 8px;
    margin-bottom: 1rem;
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

.alert-success {
    background: rgba(34, 197, 94, 0.15);
    color: #22C55E;
    border: 1px solid rgba(34, 197, 94, 0.3);
}

.alert-error {
    background: rgba(239, 68, 68, 0.15);
    color: #EF4444;
    border: 1px solid rgba(239, 68, 68, 0.3);
}

.alert-warning {
    background: rgba(245, 158, 11, 0.15);
    color: #F59E0B;
    border: 1px solid rgba(245, 158, 11, 0.3);
}

.qrcode-container {
    display: none;
    text-align: center;
    padding: 2rem;
    background: white;
    border-radius: 12px;
    margin-top: 1rem;
}

.qrcode-container img {
    max-width: 280px;
    border-radius: 8px;
}

.qrcode-container p {
    color: #333;
    margin-top: 1rem;
}

.tabs {
    display: flex;
    gap: 0.5rem;
    margin-bottom: 1.5rem;
    border-bottom: 1px solid var(--border);
    padding-bottom: 0.5rem;
    overflow-x: auto;
}

.tab-btn {
    padding: 0.5rem 1rem;
    background: transparent;
    border: none;
    color: var(--text-muted);
    cursor: pointer;
    border-radius: 6px;
    font-size: 0.9rem;
    white-space: nowrap;
}

.tab-btn.active {
    background: var(--primary);
    color: white;
}

.tab-content {
    display: none;
}

.tab-content.active {
    display: block;
}

.notification-log {
    max-height: 400px;
    overflow-y: auto;
}

.log-item {
    display: flex;
    align-items: flex-start;
    gap: 1rem;
    padding: 1rem;
    border-bottom: 1px solid var(--border);
}

.log-item:last-child {
    border-bottom: none;
}

.log-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}

.log-icon.sent {
    background: rgba(34, 197, 94, 0.15);
    color: #22C55E;
}

.log-icon.failed {
    background: rgba(239, 68, 68, 0.15);
    color: #EF4444;
}

.log-icon.pending {
    background: rgba(245, 158, 11, 0.15);
    color: #F59E0B;
}

.log-content {
    flex: 1;
    min-width: 0;
}

.log-content h4 {
    font-size: 0.9rem;
    margin-bottom: 0.25rem;
}

.log-content p {
    font-size: 0.8rem;
    color: var(--text-muted);
    margin-bottom: 0.25rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.log-content small {
    font-size: 0.75rem;
    color: var(--text-muted);
}

.empty-state {
    text-align: center;
    padding: 3rem;
    color: var(--text-muted);
}

.empty-state iconify-icon {
    font-size: 3rem;
    opacity: 0.5;
}

.variables-help {
    background: var(--bg-darker);
    border-radius: 8px;
    padding: 1rem;
    margin-top: 1rem;
}

.variables-help h4 {
    font-size: 0.85rem;
    margin-bottom: 0.5rem;
}

.variables-help code {
    background: var(--bg-card);
    padding: 0.15rem 0.4rem;
    border-radius: 4px;
    font-size: 0.8rem;
    color: var(--primary);
}

@media (max-width: 768px) {
    .form-row {
        grid-template-columns: 1fr;
    }
    
    .btn-group {
        flex-direction: column;
    }
    
    .btn-group .btn {
        width: 100%;
    }
    
    .card-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 0.75rem;
    }
}
</style>

<main class="main-content">
    <div class="page-header">
        <h1><iconify-icon icon="logos:whatsapp-icon"></iconify-icon> WhatsApp</h1>
        <p>Configure notificações automáticas via WhatsApp</p>
    </div>

    <?php if ($message): ?>
    <div class="alert alert-<?php echo $messageType; ?>">
        <iconify-icon icon="<?php echo $messageType === 'success' ? 'solar:check-circle-bold' : ($messageType === 'error' ? 'solar:close-circle-bold' : 'solar:danger-triangle-bold'); ?>"></iconify-icon>
        <?php echo htmlspecialchars($message); ?>
    </div>
    <?php endif; ?>

    <div class="whatsapp-container">
        <!-- Card de Conexão -->
        <div class="card">
            <div class="card-header">
                <?php if (($whatsappConfig['integration_type'] ?? 'evolution') === 'api_send'): ?>
                    <h2><iconify-icon icon="solar:link-bold"></iconify-icon> Link Direto (API Send)</h2>
                    <span class="status-badge status-connected" style="background: rgba(34, 197, 94, 0.15); color: #22C55E;">
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon> Ativo
                    </span>
                <?php else: ?>
                    <h2><iconify-icon icon="solar:plug-circle-bold"></iconify-icon> Conexão Evolution API</h2>
                    <?php if ($whatsappConfig && $whatsappConfig['is_connected']): ?>
                        <span class="status-badge status-connected">
                            <iconify-icon icon="solar:check-circle-bold"></iconify-icon> Conectado
                        </span>
                    <?php else: ?>
                        <span class="status-badge status-disconnected">
                            <iconify-icon icon="solar:close-circle-bold"></iconify-icon> Desconectado
                        </span>
                    <?php endif; ?>
                <?php endif; ?>
            </div>

            <form method="POST">
                <input type="hidden" name="action" value="save_config">
                
                <div class="form-row">
                    <div class="form-group" style="grid-column: 1 / -1; margin-bottom: 0;">
                        <?php if (($whatsappConfig['integration_type'] ?? 'evolution') === 'evolution'): ?>
                            <div class="alert alert-info" style="margin-bottom: 1rem; background: rgba(59, 130, 246, 0.1); border: 1px solid rgba(59, 130, 246, 0.2); color: #3B82F6;">
                                <iconify-icon icon="solar:info-circle-bold"></iconify-icon>
                                <span>O sistema está configurado para <strong>Evolution API (Envio Automático via Instância)</strong>. Preencha as credenciais abaixo:</span>
                            </div>
                        <?php else: ?>
                            <div class="alert alert-success" style="margin-bottom: 1rem;">
                                <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                                <span>O sistema está configurado para <strong>API Send (Link Direto WhatsApp Web/App)</strong>.</span>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="form-row" id="evolution_fields" style="display: <?php echo ($whatsappConfig['integration_type'] ?? 'evolution') === 'evolution' ? 'grid' : 'none'; ?>;">
                    <div class="form-group">
                        <label>URL da API Evolution *</label>
                        <input type="url" name="api_url" value="<?php echo htmlspecialchars($whatsappConfig['api_url'] ?? ''); ?>" placeholder="https://sua-api.com">
                        <small>Ex: https://api.evolution.seu-dominio.com</small>
                    </div>
                    
                    <div class="form-group">
                        <label>API Key *</label>
                        <input type="text" name="api_key" value="<?php echo htmlspecialchars($whatsappConfig['api_key'] ?? ''); ?>" placeholder="Sua chave de API">
                    </div>
                    
                    <div class="form-group">
                        <label>Nome da Instância *</label>
                        <input type="text" name="instance_name" value="<?php echo htmlspecialchars($whatsappConfig['instance_name'] ?? 'montaloja'); ?>" placeholder="montaloja">
                    </div>
                </div>
                
                <div class="form-row" id="apisend_fields" style="display: <?php echo ($whatsappConfig['integration_type'] ?? '') === 'api_send' ? 'grid' : 'none'; ?>;">
                    <div class="form-group">
                        <label>Número do WhatsApp Padrão</label>
                        <input type="text" name="whatsapp_number" class="form-input" value="<?php echo htmlspecialchars($whatsappConfig['whatsapp_number'] ?? ''); ?>" placeholder="5511999999999">
                        <small>Este número receberá os pedidos via Link Direto (WhatsApp Web/App).</small>
                    </div>
                </div>
                
                <div id="auto_notify_group" style="display: <?php echo ($whatsappConfig['integration_type'] ?? 'evolution') === 'evolution' ? 'block' : 'none'; ?>;">
                    <h4 style="margin: 1.5rem 0 1rem; font-size: 0.95rem;">Notificações Automáticas</h4>
                    
                    <div class="form-row">
                        <label class="checkbox-group">
                            <input type="checkbox" name="notify_new_order" <?php echo ($whatsappConfig['notify_new_order'] ?? 1) ? 'checked' : ''; ?>>
                            <span>📦 Novo Pedido</span>
                        </label>
                        
                        <label class="checkbox-group">
                            <input type="checkbox" name="notify_status_change" <?php echo ($whatsappConfig['notify_status_change'] ?? 1) ? 'checked' : ''; ?>>
                            <span>🔄 Mudança de Status</span>
                        </label>
                        
                        <label class="checkbox-group">
                            <input type="checkbox" name="notify_payment" <?php echo ($whatsappConfig['notify_payment'] ?? 1) ? 'checked' : ''; ?>>
                            <span>💰 Pagamento Confirmado</span>
                        </label>
                        
                        <label class="checkbox-group">
                            <input type="checkbox" name="notify_shipping" <?php echo ($whatsappConfig['notify_shipping'] ?? 1) ? 'checked' : ''; ?>>
                            <span>🚚 Envio Realizado</span>
                        </label>
                    </div>
                </div>
                
                <div class="btn-group" style="margin-top: 1.5rem; display: <?php echo ($whatsappConfig['integration_type'] ?? 'evolution') === 'evolution' ? 'flex' : 'none'; ?>;">
                    <button type="submit" class="btn btn-primary">
                        <iconify-icon icon="solar:diskette-bold"></iconify-icon> Salvar Configurações
                    </button>
                    
                    <?php if ($whatsappConfig): ?>
                    <button type="submit" name="action" value="test_connection" class="btn btn-secondary evo-only">
                        <iconify-icon icon="solar:refresh-bold"></iconify-icon> Verificar Conexão
                    </button>
                    
                    <button type="button" id="btn-qrcode" class="btn btn-outline evo-only">
                        <iconify-icon icon="solar:qr-code-bold"></iconify-icon> Gerar QR Code
                    </button>
                    <?php endif; ?>
                </div>
            </form>
            
            <div id="qrcode-container" class="qrcode-container">
                <img id="qrcode-img" src="" alt="QR Code">
                <p>Escaneie o QR Code com seu WhatsApp</p>
            </div>
        </div>

        <?php if ($whatsappConfig): ?>
        <!-- Card de Teste -->
        <div class="card">
            <div class="card-header">
                <h2><iconify-icon icon="solar:test-tube-bold"></iconify-icon> Enviar Mensagem de Teste</h2>
            </div>
            
            <form method="POST">
                <input type="hidden" name="action" value="send_test">
                
                <div class="form-row">
                    <div class="form-group">
                        <label>Número de Telefone</label>
                        <input type="text" name="test_phone" placeholder="11999999999" required>
                        <small>Apenas números, com DDD. Ex: 11999999999</small>
                    </div>
                </div>
                
                <button type="submit" class="btn btn-primary">
                    <iconify-icon icon="solar:plain-bold"></iconify-icon> Enviar Teste
                </button>
            </form>
        </div>
        
        <!-- Card de Templates -->
        <div class="card">
            <div class="card-header">
                <h2><iconify-icon icon="solar:document-text-bold"></iconify-icon> Templates de Mensagens</h2>
            </div>
            
            <div class="tabs">
                <button class="tab-btn active" data-tab="new_order">📦 Novo Pedido</button>
                <button class="tab-btn" data-tab="status_change">🔄 Mudança Status</button>
                <button class="tab-btn" data-tab="payment">💰 Pagamento</button>
                <button class="tab-btn" data-tab="shipping">🚚 Envio</button>
            </div>
            
            <?php
            $defaultTemplates = [
                'new_order' => "Olá {nome}! 🛒\n\nRecebemos seu pedido #{pedido}!\n\n📦 Itens:\n{itens}\n\n💰 Total: R$ {total}\n\nAcompanhe o status pelo nosso site.\nObrigado pela preferência! 🙏",
                'status_change' => "Olá {nome}! 📦\n\nSeu pedido #{pedido} teve uma atualização:\n\n📍 Status: {status}\n\nQualquer dúvida, estamos à disposição!",
                'payment' => "Olá {nome}! ✅\n\nPagamento do pedido #{pedido} confirmado!\n\n💰 Valor: R$ {total}\n\nEstamos preparando seu pedido para envio. 📦",
                'shipping' => "Olá {nome}! 🚚\n\nSeu pedido #{pedido} foi enviado!\n\n📦 Código de rastreio: {rastreio}\n\nAcompanhe pelo site dos Correios ou transportadora.\nBoas compras! 🎉"
            ];
            
            $templatesByType = [];
            foreach ($templates as $t) {
                $templatesByType[$t['template_type']] = $t['template_content'];
            }
            
            foreach (['new_order', 'status_change', 'payment', 'shipping'] as $type):
                $content = $templatesByType[$type] ?? $defaultTemplates[$type];
            ?>
            <div class="tab-content <?php echo $type === 'new_order' ? 'active' : ''; ?>" id="tab-<?php echo $type; ?>">
                <form method="POST">
                    <input type="hidden" name="action" value="save_template">
                    <input type="hidden" name="template_type" value="<?php echo $type; ?>">
                    
                    <div class="form-group">
                        <textarea name="template_content" placeholder="Conteúdo do template..."><?php echo htmlspecialchars($content); ?></textarea>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">
                        <iconify-icon icon="solar:diskette-bold"></iconify-icon> Salvar Template
                    </button>
                </form>
            </div>
            <?php endforeach; ?>
            
            <div class="variables-help">
                <h4>Variáveis Disponíveis:</h4>
                <p style="font-size: 0.85rem; color: var(--text-muted); margin-top: 0.5rem;">
                    <code>{nome}</code> Nome do cliente &nbsp;
                    <code>{pedido}</code> Número do pedido &nbsp;
                    <code>{total}</code> Valor total &nbsp;
                    <code>{itens}</code> Lista de itens &nbsp;
                    <code>{status}</code> Status atual &nbsp;
                    <code>{rastreio}</code> Código de rastreio
                </p>
            </div>
        </div>
        
        <!-- Histórico -->
        <div class="card">
            <div class="card-header">
                <h2><iconify-icon icon="solar:history-bold"></iconify-icon> Histórico de Notificações</h2>
            </div>
            
            <div class="notification-log">
                <?php if (empty($notificationLogs)): ?>
                <div class="empty-state">
                    <iconify-icon icon="solar:chat-round-dots-outline"></iconify-icon>
                    <p>Nenhuma notificação enviada ainda.</p>
                </div>
                <?php else: ?>
                    <?php foreach ($notificationLogs as $log): ?>
                    <div class="log-item">
                        <div class="log-icon <?php echo $log['status']; ?>">
                            <iconify-icon icon="<?php echo $log['status'] === 'sent' ? 'solar:check-read-bold' : ($log['status'] === 'failed' ? 'solar:close-circle-bold' : 'solar:clock-circle-bold'); ?>"></iconify-icon>
                        </div>
                        <div class="log-content">
                            <h4><?php echo ucfirst(str_replace('_', ' ', $log['message_type'])); ?> <?php echo $log['order_number'] ? '#' . $log['order_number'] : ''; ?></h4>
                            <p><?php echo htmlspecialchars(substr($log['message_content'], 0, 80)); ?>...</p>
                            <small>
                                📱 <?php echo $log['phone']; ?> • 
                                <?php echo date('d/m/Y H:i', strtotime($log['created_at'])); ?>
                            </small>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
</main>

<script>
document.querySelectorAll('.tab-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
        btn.classList.add('active');
        document.getElementById('tab-' + btn.dataset.tab).classList.add('active');
    });
});

document.getElementById('btn-qrcode')?.addEventListener('click', async () => {
    const container = document.getElementById('qrcode-container');
    const img = document.getElementById('qrcode-img');
    
    container.style.display = 'block';
    img.src = '';
    container.querySelector('p').textContent = 'Gerando QR Code...';
    
    try {
        const response = await fetch(window.location.href, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            credentials: 'include',
            body: 'action=get_qrcode'
        });
        
        const data = await response.json();
        
        if (data.success && data.qrcode) {
            img.src = data.qrcode.startsWith('data:') ? data.qrcode : 'data:image/png;base64,' + data.qrcode;
            container.querySelector('p').textContent = 'Escaneie o QR Code com seu WhatsApp';
        } else {
            container.querySelector('p').textContent = 'Erro: ' + (data.error || 'Falha ao gerar QR Code');
        }
    } catch (error) {
        container.querySelector('p').textContent = 'Erro de conexão: ' + error.message;
    }
});

</script>

<?php include __DIR__ . '/../../../includes/dashboard-footer.php'; ?>
