<?php
require_once __DIR__ . '/../includes/header.php';
$pdo = db();
$plan = get_user_plan($user['id']);
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$ip = null;
$channels = [];

// Carrega tags do usuário
$userTagsStmt = $pdo->prepare("SELECT * FROM tags WHERE user_id = ? ORDER BY name ASC");
$userTagsStmt->execute([$user['id']]);
$userTags = $userTagsStmt->fetchAll();

// Tags associadas ao IP atual
$currentIpTagIds = [];


if ($id) {
    $stmt = $pdo->prepare("SELECT * FROM monitored_ips WHERE id = ? AND user_id = ?");
    $stmt->execute([$id, $user['id']]);
    $ip = $stmt->fetch();
    if (!$ip) {
        echo "<p>IP não encontrado.</p>";
        require_once __DIR__ . '/../includes/footer.php';
        exit;
    }
    $channels = get_alert_channels($ip['id']);
    // Carrega tags do IP
    $tagRows = $pdo->prepare("SELECT tag_id FROM ip_tags WHERE monitored_ip_id = ?");
    $tagRows->execute([$ip['id']]);
    $currentIpTagIds = array_column($tagRows->fetchAll(), 'tag_id');
}
if (!$channels) {
    $channels[] = [
        'type' => 'email',
        'target' => $ip['alert_email'] ?? $user['email'],
        'min_failures' => 1,
        'cooldown_minutes' => 0,
        'silence_start' => null,
        'silence_end' => null,
        'active' => 1,
    ];
}

$hostValue  = $ip['host'] ?? '';
$hostParts  = split_host_and_port($hostValue);
$formHost   = $hostParts['host'];
$formPort   = $hostParts['port'];
$checkMethod = $ip['check_method'] ?? 'auto';
$isEdit = (bool)$ip;
?>

<style>
.form-section {
    background: #fff;
    border: 1px solid #e2e8f0;
    border-radius: 16px;
    overflow: hidden;
    margin-bottom: 20px;
}
.form-section-header {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 18px 24px;
    border-bottom: 1px solid #e2e8f0;
}
.form-section-icon {
    width: 38px; height: 38px;
    border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    flex-shrink: 0;
}
.form-section-body { padding: 24px; }
.field-group { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 20px; }
.field-wrap { display: flex; flex-direction: column; gap: 6px; }
.field-label {
    font-size: .82rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: .06em;
    color: #374151;
    display: flex;
    align-items: center;
    gap: 6px;
}
.field-label span.badge {
    font-size: .65rem;
    background: #f1f5f9;
    color: #64748b;
    border-radius: 4px;
    padding: 1px 6px;
    font-weight: 600;
    text-transform: none;
    letter-spacing: 0;
}
.field-input {
    width: 100%;
    border: 1.5px solid #e2e8f0;
    border-radius: 10px;
    padding: 11px 14px;
    font-size: .95rem;
    color: #0f172a;
    background: #f8fafc;
    transition: border-color .15s, box-shadow .15s, background .15s;
    box-sizing: border-box;
}
.field-input:focus {
    outline: none;
    border-color: #3b82f6;
    background: #fff;
    box-shadow: 0 0 0 3px rgba(59,130,246,.12);
}
.field-hint {
    font-size: .78rem;
    color: #94a3b8;
    line-height: 1.4;
}
.field-suffix {
    position: absolute; right: 14px; top: 50%;
    transform: translateY(-50%);
    font-size: .8rem; color: #94a3b8; pointer-events: none;
    font-weight: 600;
}
.method-cards { display: flex; flex-wrap: wrap; gap: 10px; }
.method-card {
    display: flex; align-items: center; gap: 10px;
    padding: 12px 18px;
    border: 2px solid #e2e8f0;
    border-radius: 12px;
    cursor: pointer;
    background: #f8fafc;
    transition: all .15s;
    user-select: none;
}
.method-card:hover { border-color: #93c5fd; background: #eff6ff; }
.method-card.active { background: #eff6ff; border-color: #3b82f6; }
.method-card .mc-dot {
    width: 10px; height: 10px; border-radius: 50%;
    background: #cbd5e1; transition: background .15s;
}
.method-card.active .mc-dot { background: #3b82f6; }
.method-card .mc-label { font-weight: 700; font-size: .88rem; color: #374151; }
.method-card .mc-desc { font-size: .75rem; color: #94a3b8; }
</style>

<?php if (!empty($error)): ?>
<div style="background:#fff1f2; border:1px solid #fca5a5; border-left:4px solid #ef4444; color:#b91c1c; border-radius:12px; padding:14px 18px; margin-bottom:20px; font-weight:600; display:flex; align-items:center; gap:10px;">
    <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/></svg>
    <?php echo h($error); ?>
</div>
<?php endif; ?>

<!-- HEADER -->
<div style="background:linear-gradient(135deg,#1e40af,#3b82f6); border-radius:16px; padding:28px 32px; margin-bottom:20px; color:#fff;">
    <div style="display:flex; align-items:center; gap:16px;">
        <div style="width:52px;height:52px;background:rgba(255,255,255,.15);border-radius:14px;display:flex;align-items:center;justify-content:center;">
            <svg width="26" height="26" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-9 2h4"/></svg>
        </div>
        <div>
            <h1 style="margin:0;font-size:1.5rem;font-weight:800;"><?= $isEdit ? 'Editar monitoramento' : 'Novo monitoramento' ?></h1>
            <p style="margin:4px 0 0;opacity:.8;font-size:.92rem;"><?= $isEdit ? 'Atualize os parâmetros de rede e canais de alerta.' : 'Configure o host, frequência e como você quer ser alertado.' ?></p>
        </div>
    </div>
</div>

<form method="post" action="index.php?page=user_ip_form<?= $ip ? '&id='.$ip['id'] : '' ?>">
<input type="hidden" name="csrf_token" value="<?= h(csrf_token()) ?>">

<!-- SEÇÃO 1: IDENTIFICAÇÃO -->
<div class="form-section">
    <div class="form-section-header">
        <div class="form-section-icon" style="background:#eff6ff;">
            <svg width="18" height="18" fill="none" stroke="#3b82f6" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A2 2 0 013 12V7a4 4 0 014-4z"/></svg>
        </div>
        <div>
            <div style="font-weight:700;font-size:1rem;color:#0f172a;">Identificação</div>
            <div style="font-size:.8rem;color:#64748b;">Nome e endereço do host a monitorar</div>
        </div>
    </div>
    <div class="form-section-body">
        <div class="field-group">
            <div class="field-wrap">
                <label class="field-label">
                    <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h8m-8 6h16"/></svg>
                    Nome de identificação
                </label>
                <input class="field-input" type="text" name="label" value="<?= h($ip['label'] ?? '') ?>" placeholder="Ex: Servidor Principal, VPS Produção..." required>
                <span class="field-hint">Nome amigável para identificar este host no painel.</span>
            </div>
            <div class="field-wrap">
                <label class="field-label" id="hostLabel">
                    <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9"/></svg>
                    Host / IP / URL
                </label>
                <input class="field-input" type="text" name="host" id="hostInput" value="<?= h($formHost) ?>" placeholder="Ex: 8.8.8.8 ou meusite.com" required style="font-family:monospace;">
                <span class="field-hint" id="hostHint">IP, domínio ou URL completa dependendo do método escolhido.</span>
            </div>
        </div>
    </div>
</div>

<!-- SEÇÃO 2: PROTOCOLO -->
<div class="form-section">
    <div class="form-section-header">
        <div class="form-section-icon" style="background:#f5f3ff;">
            <svg width="18" height="18" fill="none" stroke="#7c3aed" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.141 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0"/></svg>
        </div>
        <div>
            <div style="font-weight:700;font-size:1rem;color:#0f172a;">Protocolo de checagem</div>
            <div style="font-size:.8rem;color:#64748b;">Como o sistema vai testar a disponibilidade do host</div>
        </div>
    </div>
    <div class="form-section-body" style="display:flex;flex-direction:column;gap:20px;">

        <div class="field-wrap">
            <label class="field-label">
                <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 3H5a2 2 0 00-2 2v4m6-6h10a2 2 0 012 2v4M9 3v18m0 0h10a2 2 0 002-2V9M9 21H5a2 2 0 01-2-2V9m0 0h18"/></svg>
                Método
            </label>
            <input type="hidden" name="check_method" id="checkMethodInput" value="<?= h($checkMethod) ?>">
            <div class="method-cards" id="methodCards">
                <?php
                $methods = [
                    'auto'  => ['label'=>'Automático',  'desc'=>'ICMP → TCP fallback',   'color'=>'#64748b'],
                    'icmp'  => ['label'=>'ICMP',         'desc'=>'Ping nativo',           'color'=>'#2563eb'],
                    'tcp'   => ['label'=>'TCP',           'desc'=>'Porta específica',      'color'=>'#7c3aed'],
                    'http'  => ['label'=>'HTTP',          'desc'=>'Resposta web',          'color'=>'#059669'],
                    'https' => ['label'=>'HTTPS',         'desc'=>'Resposta segura (SSL)', 'color'=>'#0891b2'],
                ];
                foreach ($methods as $val => $m):
                    $active = $checkMethod === $val ? 'active' : '';
                ?>
                <div class="method-card <?= $active ?>" data-value="<?= $val ?>" onclick="selectMethod('<?= $val ?>')" style="<?= $active ? "border-color:{$m['color']};background:{$m['color']}12;" : '' ?>">
                    <div class="mc-dot" style="<?= $active ? "background:{$m['color']};" : '' ?>"></div>
                    <div>
                        <div class="mc-label" style="<?= $active ? "color:{$m['color']};" : '' ?>"><?= $m['label'] ?></div>
                        <div class="mc-desc"><?= $m['desc'] ?></div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="field-wrap" id="portField" style="max-width:320px;">
            <label class="field-label">
                <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
                Porta TCP
                <span class="badge">opcional</span>
            </label>
            <div style="position:relative;">
                <input class="field-input" type="number" name="check_port" id="checkPort" min="1" max="65535" value="<?= h($formPort ?? '') ?>" placeholder="Ex: 443, 22, 3306...">
            </div>
            <span class="field-hint" id="portHint">Deixe vazio para tentar as portas padrão (80, 443, 22, 53).</span>
        </div>

    </div>
</div>

<!-- SEÇÃO 3: FREQUÊNCIA -->
<div class="form-section">
    <div class="form-section-header">
        <div class="form-section-icon" style="background:#fff7ed;">
            <svg width="18" height="18" fill="none" stroke="#f97316" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
        </div>
        <div>
            <div style="font-weight:700;font-size:1rem;color:#0f172a;">Frequência e tolerância</div>
            <div style="font-size:.8rem;color:#64748b;">Com que frequência checar e quanto tempo aguardar resposta</div>
        </div>
    </div>
    <div class="form-section-body">
        <div class="field-group">
            <div class="field-wrap">
                <label class="field-label">
                    <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>
                    Intervalo de checagem
                </label>
                <div style="position:relative;">
                    <input class="field-input" type="number" name="interval_seconds" min="<?= $plan['min_interval_seconds'] ?>" value="<?= h($ip['interval_seconds'] ?? $plan['min_interval_seconds']) ?>" required style="padding-right:80px;">
                    <span class="field-suffix">segundos</span>
                </div>
                <span class="field-hint">Mínimo do seu plano: <strong><?= $plan['min_interval_seconds'] ?>s</strong>. Menor = mais checks, mais precisão.</span>
            </div>
            <div class="field-wrap">
                <label class="field-label">
                    <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/></svg>
                    Timeout do ping
                </label>
                <div style="position:relative;">
                    <input class="field-input" type="number" name="timeout_ms" min="200" max="10000" value="<?= h($ip['timeout_ms'] ?? 1000) ?>" required style="padding-right:40px;">
                    <span class="field-suffix">ms</span>
                </div>
                <span class="field-hint">Tempo máximo de espera por resposta. Padrão: <strong>1000 ms</strong>.</span>
            </div>
            <div class="field-wrap">
                <label class="field-label">
                    <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/></svg>
                    Alerta de latência alta
                    <span class="badge">opcional</span>
                </label>
                <div style="position:relative;">
                    <input class="field-input" type="number" name="latency_alert_ms" min="50" max="60000" value="<?= h($ip['latency_alert_ms'] ?? '') ?>" placeholder="Ex: 300" style="padding-right:40px;">
                    <span class="field-suffix">ms</span>
                </div>
                <span class="field-hint">Dispara alerta se latência ultrapassar este valor, mesmo online. Deixe vazio para desativar.</span>
            </div>
        </div>
    </div>
</div>

<!-- SEÇÃO 4: ALERTAS -->
<div class="form-section">
    <div class="form-section-header">
        <div class="form-section-icon" style="background:#fff1f2;">
            <svg width="18" height="18" fill="none" stroke="#e11d48" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"/></svg>
        </div>
        <div>
            <div style="font-weight:700;font-size:1rem;color:#0f172a;">Canais de alerta</div>
            <div style="font-size:.8rem;color:#64748b;">Para onde enviar notificações quando o host cair ou se recuperar</div>
        </div>
    </div>
    <div class="form-section-body" style="display:flex;flex-direction:column;gap:16px;">

        <div class="field-wrap" style="max-width:480px;">
            <label class="field-label">
                <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/></svg>
                E-mail fallback
            </label>
            <input class="field-input" type="email" name="alert_email" value="<?= h($ip['alert_email'] ?? $user['email']) ?>">
            <span class="field-hint">Usado caso nenhum canal abaixo esteja configurado ou todos falhem.</span>
        </div>

        <div style="border-top:1px solid #f1f5f9; padding-top:16px;">
            <div style="font-size:.8rem;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:#94a3b8;margin-bottom:12px;">Canais adicionais</div>
            <div id="alert-channels" style="display:flex; flex-direction:column; gap:12px;">
                <?php foreach ($channels as $index => $channel): ?>
                    <?php include __DIR__ . '/partials/alert_channel_row.php'; ?>
                <?php endforeach; ?>
            </div>
            <button type="button" id="add-channel" style="margin-top:12px; display:inline-flex; align-items:center; gap:8px; padding:10px 18px; background:#f8fafc; border:1.5px dashed #cbd5e1; border-radius:10px; color:#3b82f6; font-weight:700; font-size:.88rem; cursor:pointer; transition:all .15s;" onmouseover="this.style.background='#eff6ff';this.style.borderColor='#93c5fd';" onmouseout="this.style.background='#f8fafc';this.style.borderColor='#cbd5e1';">
                <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M12 4v16m8-8H4"/></svg>
                Adicionar canal (Webhook, WhatsApp, SMS...)
            </button>
        </div>

    </div>
</div>

<!-- SEÇÃO 5: TAGS -->
<?php if (!empty($userTags)): ?>
<div class="form-section">
    <div class="form-section-header">
        <div class="form-section-icon" style="background:#fef9c3;">
            🏷️
        </div>
        <div>
            <div style="font-weight:700;font-size:1rem;color:#0f172a;">Tags</div>
            <div style="font-size:.8rem;color:#64748b;">Categorize este host para facilitar filtros e organização</div>
        </div>
    </div>
    <div class="form-section-body">
        <div style="display:flex;flex-wrap:wrap;gap:10px;">
            <?php foreach ($userTags as $tag): ?>
            <label style="display:inline-flex;align-items:center;gap:8px;padding:8px 14px;border:2px solid <?php echo h($tag['color']); ?>30;border-radius:20px;cursor:pointer;background:<?php echo h($tag['color']); ?>10;transition:all .15s;"
                   onmouseover="this.style.borderColor='<?php echo $tag['color']; ?>';this.style.background='<?php echo $tag['color']; ?>20';"
                   onmouseout="this.style.borderColor='<?php echo $tag['color']; ?>30';this.style.background='<?php echo $tag['color']; ?>10';">
                <input type="checkbox" name="tag_ids[]" value="<?php echo $tag['id']; ?>"
                       <?php echo in_array($tag['id'], $currentIpTagIds) ? 'checked' : ''; ?>
                       style="accent-color:<?php echo h($tag['color']); ?>;width:15px;height:15px;margin:0;">
                <span style="width:10px;height:10px;border-radius:50%;background:<?php echo h($tag['color']); ?>;display:inline-block;"></span>
                <span style="font-size:.88rem;font-weight:600;color:#374151;"><?php echo h($tag['name']); ?></span>
            </label>
            <?php endforeach; ?>
        </div>
        <p style="font-size:.78rem;color:#94a3b8;margin-top:8px;">Crie novas tags em <a href="<?php echo BASE_URL; ?>index.php?page=user_tags" style="color:var(--primary);">🏷️ Tags</a>.</p>
    </div>
</div>
<?php endif; ?>

<!-- SEÇÃO 6: SSL -->
<div class="form-section">
    <div class="form-section-header">
        <div class="form-section-icon" style="background:#f0fdf4;">🔒</div>
        <div>
            <div style="font-weight:700;font-size:1rem;color:#0f172a;">Monitoramento SSL</div>
            <div style="font-size:.8rem;color:#64748b;">Receba alertas quando o certificado SSL estiver expirando</div>
        </div>
    </div>
    <div class="form-section-body">
        <label style="display:inline-flex;align-items:center;gap:10px;cursor:pointer;">
            <input type="checkbox" name="ssl_check_enabled" id="sslCheckEnabled"
                   <?php echo ($ip['ssl_check_enabled'] ?? false) ? 'checked' : ''; ?>
                   style="width:18px;height:18px;accent-color:#22c55e;margin:0;">
            <span style="font-size:.95rem;font-weight:600;">Monitorar certificado SSL deste host</span>
        </label>
        <p style="font-size:.78rem;color:#94a3b8;margin-top:8px;">
            Verificado a cada 12 horas. Alertas enviados quando faltar 30, 14 ou 7 dias para expirar.
            Funciona apenas com hosts HTTPS acessíveis pela internet.
        </p>
        <?php if (!empty($ip['ssl_expires_at'])): ?>
        <div style="margin-top:10px;padding:10px 14px;background:#f0fdf4;border-radius:8px;border:1px solid #bbf7d0;font-size:13px;">
            🔒 Certificado SSL expira em: <strong><?php echo date('d/m/Y', strtotime($ip['ssl_expires_at'])); ?></strong>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- RODAPÉ -->
<div style="display:flex; justify-content:space-between; align-items:center; padding:20px 0 8px;">
    <a href="index.php?page=user_ips" style="display:inline-flex;align-items:center;gap:6px;padding:11px 20px;color:#64748b;font-weight:600;font-size:.9rem;text-decoration:none;border:1.5px solid #e2e8f0;border-radius:10px;background:#fff;transition:all .15s;" onmouseover="this.style.background='#f8fafc'" onmouseout="this.style.background='#fff'">
        <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"/></svg>
        Cancelar
    </a>
    <button type="submit" style="display:inline-flex;align-items:center;gap:8px;padding:12px 32px;background:linear-gradient(135deg,#1e40af,#3b82f6);color:#fff;border:none;border-radius:10px;font-size:1rem;font-weight:700;cursor:pointer;box-shadow:0 4px 12px rgba(59,130,246,.35);transition:all .15s;" onmouseover="this.style.transform='translateY(-1px)';this.style.boxShadow='0 6px 16px rgba(59,130,246,.45)'" onmouseout="this.style.transform='';this.style.boxShadow='0 4px 12px rgba(59,130,246,.35)'">
        <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>
        <?= $isEdit ? 'Salvar alterações' : 'Criar monitoramento' ?>
    </button>
</div>

</form>

<template id="channel-template">
    <?php $index = '__INDEX__'; $channel = ['type' => 'email', 'target' => '', 'min_failures' => 1, 'cooldown_minutes' => 0, 'silence_start' => null, 'silence_end' => null, 'active' => 1]; ?>
    <?php include __DIR__ . '/partials/alert_channel_row.php'; ?>
</template>

<script>
const methodColors = {
    auto:  '#64748b', icmp: '#2563eb', tcp: '#7c3aed', http: '#059669', https: '#0891b2'
};

function selectMethod(val) {
    document.getElementById('checkMethodInput').value = val;
    document.querySelectorAll('.method-card').forEach(card => {
        const v = card.dataset.value;
        const c = methodColors[v];
        const isActive = v === val;
        card.classList.toggle('active', isActive);
        card.style.borderColor = isActive ? c : '';
        card.style.background  = isActive ? c + '12' : '';
        card.querySelector('.mc-dot').style.background   = isActive ? c : '';
        card.querySelector('.mc-label').style.color      = isActive ? c : '';
    });

    const portField  = document.getElementById('portField');
    const hostLabel  = document.getElementById('hostLabel');
    const hostInput  = document.getElementById('hostInput');
    const hostHint   = document.getElementById('hostHint');
    const portHint   = document.getElementById('portHint');
    const portInput  = document.getElementById('checkPort');

    if (val === 'http' || val === 'https') {
        hostLabel.childNodes[hostLabel.childNodes.length - 1].textContent = ' URL ou domínio';
        hostInput.placeholder = 'Ex: meusite.com ou https://meusite.com/path';
        hostInput.style.fontFamily = 'monospace';
        hostHint.textContent = 'Informe domínio, IP ou URL completa. O protocolo ' + val + ':// será aplicado automaticamente.';
        portField.style.display = 'none';
        // Timeout mínimo recomendado para HTTP é 8s
        const toEl = document.querySelector('input[name="timeout_ms"]');
        if (toEl && parseInt(toEl.value) < 8000) toEl.value = 8000;
    } else if (val === 'tcp') {
        hostLabel.childNodes[hostLabel.childNodes.length - 1].textContent = ' Host / IP';
        hostInput.placeholder = 'Ex: 8.8.8.8 ou meusite.com';
        hostHint.textContent = 'IP ou domínio. A porta abaixo é obrigatória para TCP.';
        portField.style.display = '';
        portHint.textContent = 'Obrigatório para TCP. Ex: 443, 22, 3306...';
        portInput.required = true;
    } else {
        hostLabel.childNodes[hostLabel.childNodes.length - 1].textContent = ' Host / IP';
        hostInput.placeholder = 'Ex: 8.8.8.8 ou meusite.com';
        hostHint.textContent = 'IP, domínio ou host:porta. Ex: 8.8.8.8 ou meusite.com:8080';
        portField.style.display = '';
        portHint.textContent = 'Deixe vazio para tentar as portas padrão (80, 443, 22, 53).';
        portInput.required = false;
    }
}

// Init
selectMethod(document.getElementById('checkMethodInput').value);

(function() {
    const btn = document.getElementById('add-channel');
    if (!btn) return;
    const container = document.getElementById('alert-channels');
    const tpl = document.getElementById('channel-template');
    let index = <?= count($channels) ?>;
    btn.addEventListener('click', () => {
        const html = tpl.innerHTML.replace(/__INDEX__/g, index++);
        const wrapper = document.createElement('div');
        wrapper.innerHTML = html;
        container.appendChild(wrapper.firstElementChild);
    });
})();
</script>

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