<?php
require_once __DIR__ . '/../includes/header.php';
require_admin();

$fields = [
    'smtp_host' => ['label' => 'Servidor SMTP', 'type' => 'text'],
    'smtp_port' => ['label' => 'Porta', 'type' => 'number'],
    'smtp_secure' => ['label' => 'Seguranca', 'type' => 'select'],
    'smtp_user' => ['label' => 'Usuario', 'type' => 'text'],
    'smtp_pass' => ['label' => 'Senha', 'type' => 'password'],
    'smtp_from' => ['label' => 'Remetente (email)', 'type' => 'email'],
    'smtp_from_name' => ['label' => 'Nome do remetente', 'type' => 'text'],
    'smtp_timeout' => ['label' => 'Timeout (s)', 'type' => 'number'],
];

$success = false;
$error = null;
$testSuccess = null;
$testMessage = null;
$whatsSuccess = null;
$whatsMessage = null;
$action = $_POST['action'] ?? 'save';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (!csrf_check($_POST['csrf_token'] ?? null)) {
            throw new Exception('CSRF inválido.');
        }
        if ($action === 'save') {
            foreach ($fields as $key => $_) {
                $value = isset($_POST[$key]) ? trim($_POST[$key]) : '';
                if ($key === 'smtp_timeout' || $key === 'smtp_port') {
                    $value = (string)max(0, (int)$value);
                }
                set_system_setting($key, $value);
            }
            set_system_setting('whatsapp_webhook_url', trim($_POST['whatsapp_webhook_url'] ?? ''));
            set_system_setting('whatsapp_webhook_token', trim($_POST['whatsapp_webhook_token'] ?? ''));
            set_system_setting('telegram_bot_token', trim($_POST['telegram_bot_token'] ?? ''));
            $success = true;
            system_settings_cache(true);
        } elseif ($action === 'test_email') {
            $testEmail = trim($_POST['test_email'] ?? '');
            if (!$testEmail || !filter_var($testEmail, FILTER_VALIDATE_EMAIL)) {
                throw new Exception('Informe um e-mail valido para teste.');
            }
            if (!rate_limit_check('admin_test_email', 60)) {
                throw new Exception('Aguarde alguns segundos antes de novo teste.');
            }
            $errorMsg = null;
            $sampleIp = [
                'label' => 'Canal de Teste',
                'host' => 'demo.monitorping.local',
                'user_id' => $_SESSION['user']['id'] ?? null,
            ];
            $sampleContent = build_alert_email_content(
                $sampleIp,
                'online',
                rand(5, 60),
                $_SESSION['user']['name'] ?? 'MonitorPing',
                $_SESSION['user']['timezone'] ?? 'America/Sao_Paulo',
                '5 minutos',
                null
            );
            $textBody = "Teste de envio em " . date('Y-m-d H:i:s') . "\n\n" . $sampleContent['text'];
            $testHtml = str_replace('Dispositivo Recuperado!', 'Dispositivo Recuperado! · Teste SMTP', $sampleContent['html']);
            if (send_email_message($testEmail, '[MonitorPing] Teste de SMTP', $textBody, $errorMsg, $testHtml)) {
                $testSuccess = true;
                $testMessage = "E-mail de teste enviado para {$testEmail}.";
            } else {
                $testSuccess = false;
                $testMessage = 'Falha ao enviar teste: ' . ($errorMsg ?: 'Erro desconhecido.');
            }
        } elseif ($action === 'test_whatsapp') {
            $testNumber = trim($_POST['test_phone'] ?? '');
            if (!$testNumber) {
                throw new Exception('Informe um numero/ID para o teste de WhatsApp.');
            }
            $whats = get_whatsapp_settings();
            if (empty($whats['webhook_url'])) {
                throw new Exception('Webhook WhatsApp nao configurado.');
            }
            if (!rate_limit_check('admin_test_whatsapp', 60)) {
                throw new Exception('Aguarde alguns segundos antes de novo teste.');
            }
            $payload = [
                'phone' => $testNumber,
                'host' => 'teste',
                'label' => 'Teste WhatsApp',
                'status' => 'online',
                'latency' => null,
                'timestamp' => date('c'),
                'token' => $whats['token'],
            ];
            $context = stream_context_create([
                'http' => [
                    'method' => 'POST',
                    'header' => "Content-Type: application/json\r\n",
                    'content' => json_encode($payload),
                    'timeout' => 5
                ]
            ]);
            $result = @file_get_contents($whats['webhook_url'], false, $context);
            $httpCode = 0;
            if (!empty($http_response_header)) {
                foreach ($http_response_header as $headerLine) {
                    if (preg_match('#HTTP/\d\.\d\s+(\d+)#', $headerLine, $match)) {
                        $httpCode = (int)$match[1];
                        break;
                    }
                }
            }
            if ($result === false || $httpCode >= 400 || $httpCode === 0) {
                $whatsSuccess = false;
                $whatsMessage = 'Teste falhou: codigo HTTP ' . ($httpCode ?: 'N/A');
            } else {
                $whatsSuccess = true;
                $whatsMessage = "Webhook acionado para {$testNumber}. Verifique o fluxo no n8n/WhatsApp.";
            }
        }
    } catch (Exception $e) {
        if ($action === 'test_email') {
            $testSuccess = false;
            $testMessage = $e->getMessage();
        } elseif ($action === 'test_whatsapp') {
            $whatsSuccess = false;
            $whatsMessage = $e->getMessage();
        } else {
            $error = $e->getMessage();
        }
    }
}

$current = [
    'smtp_host' => get_system_setting('smtp_host', SMTP_HOST),
    'smtp_port' => get_system_setting('smtp_port', SMTP_PORT),
    'smtp_secure' => get_system_setting('smtp_secure', SMTP_SECURE ?: 'tls'),
    'smtp_user' => get_system_setting('smtp_user', SMTP_USER),
    'smtp_pass' => get_system_setting('smtp_pass', SMTP_PASS),
    'smtp_from' => get_system_setting('smtp_from', SMTP_FROM),
    'smtp_from_name' => get_system_setting('smtp_from_name', SMTP_FROM_NAME),
    'smtp_timeout' => get_system_setting('smtp_timeout', SMTP_TIMEOUT ?: 10),
];
$whatsCurrent = [
    'webhook_url' => get_system_setting('whatsapp_webhook_url', WHATSAPP_WEBHOOK_URL),
    'token' => get_system_setting('whatsapp_webhook_token', WHATSAPP_WEBHOOK_TOKEN),
];
$telegramToken = get_system_setting('telegram_bot_token', '');
$smtpConfigured = !empty($current['smtp_host']) && !empty($current['smtp_from']);
$whatsConfigured = !empty($whatsCurrent['webhook_url']);
$telegramConfigured = !empty($telegramToken);
?>

<div class="settings-wrapper card">
    <div class="settings-hero">
        <div class="settings-hero-text">
            <p class="settings-eyebrow">Notificacoes globais</p>
            <h2>SMTP & WhatsApp</h2>
            <p>Defina o servidor de e-mail utilizado em todos os alertas e a rota WhatsApp compartilhada.</p>
        </div>
        <div class="settings-hero-status">
            <div class="settings-status <?php echo $smtpConfigured ? 'ok' : 'warn'; ?>">
                <span>SMTP</span>
                <strong><?php echo $smtpConfigured ? 'Configurado' : 'Pendente'; ?></strong>
            </div>
            <div class="settings-status <?php echo $whatsConfigured ? 'ok' : 'warn'; ?>">
                <span>WhatsApp</span>
                <strong><?php echo $whatsConfigured ? 'Ativo' : 'Incompleto'; ?></strong>
            </div>
            <div class="settings-status <?php echo $telegramConfigured ? 'ok' : 'warn'; ?>">
                <span>Telegram</span>
                <strong><?php echo $telegramConfigured ? 'Configurado' : 'Pendente'; ?></strong>
            </div>
        </div>
    </div>

    <?php if ($success || $error): ?>
        <div class="settings-flash <?php echo $success ? 'success' : 'error'; ?>">
            <?php echo $success ? 'Configuracoes salvas com sucesso.' : h($error); ?>
        </div>
    <?php endif; ?>

    <form method="post" class="settings-grid">
        <input type="hidden" name="action" value="save">
        <input type="hidden" name="csrf_token" value="<?php echo h(csrf_token()); ?>">
        <section class="form-card">
            <div class="form-card-head">
                <h4>Servidor SMTP</h4>
                <p>Host, porta e protocolo utilizados na conexao.</p>
            </div>
            <label><?php echo h($fields['smtp_host']['label']); ?></label>
            <input type="text" name="smtp_host" value="<?php echo h($current['smtp_host']); ?>">
            <label><?php echo h($fields['smtp_port']['label']); ?></label>
            <input type="number" name="smtp_port" value="<?php echo h($current['smtp_port']); ?>">
            <label><?php echo h($fields['smtp_secure']['label']); ?></label>
            <select name="smtp_secure">
                <?php foreach (['none' => 'Sem seguranca', 'tls' => 'TLS', 'ssl' => 'SSL'] as $value => $label): ?>
                    <option value="<?php echo $value; ?>" <?php echo ($current['smtp_secure'] === $value) ? 'selected' : ''; ?>>
                        <?php echo h($label); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </section>
        <section class="form-card">
            <div class="form-card-head">
                <h4>Autenticacao e remetente</h4>
                <p>Credenciais e nome apresentadas ao destinatario.</p>
            </div>
            <label><?php echo h($fields['smtp_user']['label']); ?></label>
            <input type="text" name="smtp_user" value="<?php echo h($current['smtp_user']); ?>">
            <label><?php echo h($fields['smtp_pass']['label']); ?></label>
            <input type="password" name="smtp_pass" value="<?php echo h($current['smtp_pass']); ?>">
            <label><?php echo h($fields['smtp_from']['label']); ?></label>
            <input type="email" name="smtp_from" value="<?php echo h($current['smtp_from']); ?>">
            <label><?php echo h($fields['smtp_from_name']['label']); ?></label>
            <input type="text" name="smtp_from_name" value="<?php echo h($current['smtp_from_name']); ?>">
        </section>
        <section class="form-card">
            <div class="form-card-head">
                <h4>Timeout & webhook WhatsApp</h4>
                <p>Defina o limite de conexao e o endpoint global para n8n.</p>
            </div>
            <label><?php echo h($fields['smtp_timeout']['label']); ?></label>
            <input type="number" name="smtp_timeout" value="<?php echo h($current['smtp_timeout']); ?>">
            <p class="hint">Em branco = valor padrao do config.php.</p>
            <label>URL do webhook (ex.: fluxo n8n)</label>
            <input type="text" name="whatsapp_webhook_url" value="<?php echo h($whatsCurrent['webhook_url']); ?>">
            <label>Token/segredo (opcional)</label>
            <input type="text" name="whatsapp_webhook_token" value="<?php echo h($whatsCurrent['token']); ?>">
            <p class="hint">O token sera enviado junto com cada chamada.</p>
            <hr style="border:none;border-top:1px solid var(--border);margin:16px 0;">
            <label>🤖 Telegram Bot Token</label>
            <input type="text" name="telegram_bot_token" value="<?php echo h($telegramToken); ?>" placeholder="123456789:ABCdefGhIJKlmNOPqrstUVwxyZ">
            <p class="hint">Obtenha o token via <strong>@BotFather</strong> no Telegram. O chat_id é configurado por canal de alerta.</p>
        </section>
        <div class="form-actions">
            <button type="submit" class="primary-button">Salvar configuracoes</button>
            <span class="muted-text">Aplicado imediatamente para todos os usuarios.</span>
        </div>
    </form>

    <div class="settings-tests">
        <section class="test-card">
            <div class="form-card-head">
                <h4>Teste de SMTP</h4>
                <p>Confirme se o servidor aceita conexoes.</p>
            </div>
            <?php if ($testSuccess !== null): ?>
                <div class="inline-feedback <?php echo $testSuccess ? 'success' : 'error'; ?>">
                    <?php echo h($testMessage); ?>
                </div>
            <?php endif; ?>
            <form method="post" class="test-form">
                <input type="hidden" name="action" value="test_email">
                <input type="hidden" name="csrf_token" value="<?php echo h(csrf_token()); ?>">
                <label>Destino para teste</label>
                <input type="email" name="test_email" placeholder="exemplo@dominio.com" required>
                <button type="submit">Enviar e-mail de teste</button>
            </form>
        </section>
        <section class="test-card">
            <div class="form-card-head">
                <h4>Teste de WhatsApp</h4>
                <p>Aciona o webhook configurado para validar o fluxo.</p>
            </div>
            <?php if ($whatsSuccess !== null): ?>
                <div class="inline-feedback <?php echo $whatsSuccess ? 'success' : 'error'; ?>">
                    <?php echo h($whatsMessage); ?>
                </div>
            <?php endif; ?>
            <form method="post" class="test-form">
                <input type="hidden" name="action" value="test_whatsapp">
                <input type="hidden" name="csrf_token" value="<?php echo h(csrf_token()); ?>">
                <label>Numero/ID para teste</label>
                <input type="text" name="test_phone" placeholder="+5511999999999" required>
                <button type="submit">Enviar teste WhatsApp</button>
            </form>
        </section>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
