<?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 = [];

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']);
}
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';
?>

<div style="background:#fff; border-radius:20px; border:1px solid #e2e8f0; box-shadow:0 10px 15px -3px rgba(0,0,0,0.05); overflow:hidden;">
    <div style="padding: 24px 32px; border-bottom:1px solid #e2e8f0; background:#f8fafc;">
        <h2 style="margin:0; font-size:1.6rem; color:#0f172a; font-weight:800;"><?php echo $ip ? 'Ajustes da Extremidade (IP)' : 'Nova Extremidade (IP)'; ?></h2>
        <p style="margin:4px 0 0; color:#64748b; font-size:0.95rem;">Configure os parâmetros de rede e defina a tolerância de falhas para o monitoramento contínuo.</p>
    </div>
    
    <div style="padding: 32px;">
        <?php if (!empty($error)): ?>
            <div style="padding:12px 16px; background:#fee2e2; border-left:4px solid #ef4444; color:#b91c1c; border-radius:6px; margin-bottom:24px; font-weight:600;">
                <?php echo h($error); ?>
            </div>
        <?php endif; ?>
        
        <form method="post" action="index.php?page=user_ip_form<?php echo $ip ? '&id='.$ip['id'] : ''; ?>">
            <input type="hidden" name="csrf_token" value="<?php echo h(csrf_token()); ?>">
            
            <h3 style="margin:0 0 16px; color:#0f172a; font-size:1.1rem; border-bottom:1px solid #e2e8f0; padding-bottom:8px;">Parâmetros Principais</h3>
            
            <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap:20px; margin-bottom:24px;">
                <div>
                    <label style="display:block; font-weight:600; font-size:0.9rem; color:#475569; margin-bottom:6px;">Nome de Identificação</label>
                    <input type="text" name="label" value="<?php echo h($ip['label'] ?? ''); ?>" placeholder="Ex: Servidor de Banco de Dados" required style="width:100%; border:1px solid #cbd5e1; border-radius:10px; padding:10px 14px; font-size:0.95rem;">
                </div>
                <div>
                    <label style="display:block; font-weight:600; font-size:0.9rem; color:#475569; margin-bottom:6px;">Host (IP ou domínio)</label>
                    <input type="text" name="host" value="<?php echo h($formHost); ?>" placeholder="Ex: 8.8.8.8" required style="width:100%; border:1px solid #cbd5e1; border-radius:10px; padding:10px 14px; font-size:0.95rem; font-family:monospace;">
                </div>
            </div>

            <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap:20px; margin-bottom:24px;">
                <div>
                    <label style="display:block; font-weight:600; font-size:0.9rem; color:#475569; margin-bottom:6px;">Método de Checagem</label>
                    <select name="check_method" style="width:100%; border:1px solid #cbd5e1; border-radius:10px; padding:10px 14px; font-size:0.95rem; background:#f8fafc;">
                        <option value="auto" <?php echo $checkMethod === 'auto' ? 'selected' : ''; ?>>Automático (ICMP/TCP)</option>
                        <option value="icmp" <?php echo $checkMethod === 'icmp' ? 'selected' : ''; ?>>Somente ICMP (ping nativo)</option>
                        <option value="tcp" <?php echo $checkMethod === 'tcp' ? 'selected' : ''; ?>>Somente porta TCP</option>
                    </select>
                </div>
                <div>
                    <label style="display:block; font-weight:600; font-size:0.9rem; color:#475569; margin-bottom:6px;">Porta TCP Direcionada (Opcional)</label>
                    <input type="number" name="check_port" min="1" max="65535" value="<?php echo h($formPort ?? ''); ?>" placeholder="Padrão porta 80 ou 443" style="width:100%; border:1px solid #cbd5e1; border-radius:10px; padding:10px 14px; font-size:0.95rem;">
                    <small style="color:#94a3b8; display:block; margin-top:4px;">Útil caso o servidor bloqueie Ping.</small>
                </div>
            </div>

            <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap:20px; margin-bottom:24px;">
                <div>
                    <label style="display:block; font-weight:600; font-size:0.9rem; color:#475569; margin-bottom:6px;">Frequência (Cron)</label>
                    <div style="position:relative;">
                        <input type="number" name="interval_seconds" min="<?php echo $plan['min_interval_seconds']; ?>" value="<?php echo h($ip['interval_seconds'] ?? $plan['min_interval_seconds']); ?>" required style="width:100%; border:1px solid #cbd5e1; border-radius:10px; padding:10px 14px; font-size:0.95rem;">
                        <span style="position:absolute; right:14px; top:11px; color:#94a3b8; font-size:0.85rem; pointer-events:none;">segundos</span>
                    </div>
                </div>
                <div>
                    <label style="display:block; font-weight:600; font-size:0.9rem; color:#475569; margin-bottom:6px;">Tolerância (Timeout PING)</label>
                    <div style="position:relative;">
                        <input type="number" name="timeout_ms" min="200" max="10000" value="<?php echo h($ip['timeout_ms'] ?? 1000); ?>" required style="width:100%; border:1px solid #cbd5e1; border-radius:10px; padding:10px 14px; font-size:0.95rem;">
                        <span style="position:absolute; right:14px; top:11px; color:#94a3b8; font-size:0.85rem; pointer-events:none;">ms</span>
                    </div>
                </div>
            </div>

            <div style="margin-bottom:32px;">
                <label style="display:block; font-weight:600; font-size:0.9rem; color:#475569; margin-bottom:6px;">Notificação Padrão de Recuo (Fallback E-mail)</label>
                <input type="email" name="alert_email" value="<?php echo h($ip['alert_email'] ?? $user['email']); ?>" style="width:100%; border:1px solid #cbd5e1; border-radius:10px; padding:10px 14px; font-size:0.95rem; max-width:50%;">
            </div>

            <h3 style="margin:0 0 8px; color:#0f172a; font-size:1.1rem; border-bottom:1px solid #e2e8f0; padding-bottom:8px;">Protocolos e Canais de Alerta (Opcional)</h3>
            <p style="margin:0 0 24px; color:#64748b; font-size:0.9rem;">Subscreva Webhooks, endpoints do N8N/WhatsApp ou disparos segmentados por queda. Deixe em branco caso não queira.</p>
            
            <div id="alert-channels" style="display:flex; flex-direction:column; gap:16px; margin-bottom:24px;">
                <?php foreach ($channels as $index => $channel): ?>
                    <?php include __DIR__ . '/partials/alert_channel_row.php'; ?>
                <?php endforeach; ?>
            </div>
            
            <div style="padding:16px 20px; background:#f8fafc; border-radius:12px; border:1px dashed #cbd5e1; display:flex; justify-content:space-between; align-items:center;">
                <span style="color:#64748b; font-size:0.9rem;">Deseja cruzar notificações para outro canal (ex: Telegram)?</span>
                <button type="button" id="add-channel" style="background:#fff; color:#3b82f6; border:1px solid #bfdbfe; font-weight:600; padding:8px 16px; border-radius:8px; display:inline-flex; align-items:center; gap:6px; cursor:pointer;" onmouseover="this.style.background='#eff6ff'" onmouseout="this.style.background='#fff'">
                    <span style="font-size:1.1rem; line-height:1;">+</span> Engatilhar Novo Canal
                </button>
            </div>

            <div style="margin-top:32px; display:flex; justify-content:flex-end; gap:12px; border-top:1px solid #e2e8f0; padding-top:24px;">
                <a href="index.php?page=user_ips" style="padding:12px 24px; color:#475569; font-weight:600; text-decoration:none; border-radius:10px;">Cancelar</a>
                <button type="submit" style="padding:12px 32px; font-size:1.05rem;"><?php echo $ip ? 'Confirmar e Salvar' : 'Implantar Máquina'; ?></button>
            </div>
        </form>
    </div>
</div>

<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>
(function() {
    const btn = document.getElementById('add-channel');
    if (!btn) return;
    const container = document.getElementById('alert-channels');
    const tpl = document.getElementById('channel-template');
    let index = <?php echo 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'; ?>
