<?php
// ── Toda lógica PHP ANTES de incluir o header (que já envia HTML) ──

$editId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$dev    = null;
$successMsg = null;
$errorMsg   = null;

if ($editId) {
    $s = $pdo->prepare("SELECT * FROM nms_devices WHERE id=? AND user_id=?");
    $s->execute([$editId, $user['id']]);
    $dev = $s->fetch();
    if (!$dev) {
        header('Location: ' . NMS_URL . '?page=nms_devices');
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_check($_POST['csrf_token'] ?? null)) {
        $errorMsg = 'Token CSRF inválido.';
    } else {
        $name           = trim($_POST['name'] ?? '');
        $hostname       = trim($_POST['hostname'] ?? '');
        $type           = $_POST['type'] ?? 'mikrotik';
        $location       = trim($_POST['location'] ?? '');
        $snmp_enabled   = isset($_POST['snmp_enabled']) ? 1 : 0;
        $snmp_version   = in_array($_POST['snmp_version'] ?? '', ['2c','3']) ? $_POST['snmp_version'] : '2c';
        $snmp_community = trim($_POST['snmp_community'] ?? 'public');
        $snmp_user      = trim($_POST['snmp_user'] ?? '');
        $snmp_auth_proto = in_array($_POST['snmp_auth_proto'] ?? '', ['MD5','SHA']) ? $_POST['snmp_auth_proto'] : 'MD5';
        $snmp_priv_proto = in_array($_POST['snmp_priv_proto'] ?? '', ['DES','AES']) ? $_POST['snmp_priv_proto'] : 'DES';
        $snmp_auth_pass = trim($_POST['snmp_auth_pass'] ?? '');
        $snmp_priv_pass = trim($_POST['snmp_priv_pass'] ?? '');
        $snmp_port      = max(1, min(65535, (int)($_POST['snmp_port'] ?? 161)));
        $api_enabled    = isset($_POST['api_enabled']) ? 1 : 0;
        $api_user       = trim($_POST['api_user'] ?? '');
        $api_password   = trim($_POST['api_password'] ?? '');
        $api_port       = max(1, min(65535, (int)($_POST['api_port'] ?? 8728)));
        $api_use_ssl    = isset($_POST['api_use_ssl']) ? 1 : 0;
        $poll_interval  = max(10, min(3600, (int)($_POST['poll_interval'] ?? 60)));
        $active         = isset($_POST['active']) ? 1 : 0;
        $map_lat        = $_POST['map_lat'] !== '' ? (float)$_POST['map_lat'] : null;
        $map_lng        = $_POST['map_lng'] !== '' ? (float)$_POST['map_lng'] : null;
        // Valida range de coordenadas
        if ($map_lat !== null && ($map_lat < -90 || $map_lat > 90))   { $map_lat = null; }
        if ($map_lng !== null && ($map_lng < -180 || $map_lng > 180)) { $map_lng = null; }

        if ($name === '' || $hostname === '') {
            $errorMsg = 'Nome e hostname/IP são obrigatórios.';
        } elseif (!in_array($type, ['mikrotik','cisco','olt','switch','server','other'])) {
            $errorMsg = 'Tipo inválido.';
        } else {
            try {
                if ($editId && $dev) {
                    // EDIÇÃO — atualiza e exibe mensagem de sucesso na mesma página
                    $pdo->prepare("UPDATE nms_devices SET name=?, hostname=?, type=?, location=?,
                        snmp_enabled=?, snmp_version=?, snmp_community=?, snmp_user=?, snmp_auth_proto=?, snmp_priv_proto=?, snmp_auth_pass=?, snmp_priv_pass=?, snmp_port=?,
                        api_enabled=?, api_user=?, api_password=?, api_port=?, api_use_ssl=?,
                        poll_interval=?, active=?, map_lat=?, map_lng=?
                        WHERE id=? AND user_id=?")
                        ->execute([$name, $hostname, $type, $location ?: null,
                            $snmp_enabled, $snmp_version, $snmp_community ?: null, $snmp_user ?: null,
                            $snmp_auth_proto, $snmp_priv_proto,
                            $snmp_auth_pass ?: null, $snmp_priv_pass ?: null, $snmp_port,
                            $api_enabled, $api_user ?: null, $api_password ?: null, $api_port, $api_use_ssl,
                            $poll_interval, $active, $map_lat, $map_lng, $editId, $user['id']]);
                    // Recarrega dados atualizados
                    $s = $pdo->prepare("SELECT * FROM nms_devices WHERE id=? AND user_id=?");
                    $s->execute([$editId, $user['id']]);
                    $dev = $s->fetch();

                    // Testa conexão SNMP imediatamente após salvar
                    $testResult = '';
                    if ($snmp_enabled && $dev) {
                        require_once __DIR__ . '/../../mikrotik/includes/snmp.php';
                        $uptime = nms_get_uptime($dev);
                        $cpu    = nms_get_cpu($dev);
                        if ($uptime !== null || $cpu !== null) {
                            $pdo->prepare("UPDATE nms_devices SET last_status='online', last_check_at=NOW() WHERE id=?")
                                ->execute([$editId]);
                            $testResult = ' — 🟢 SNMP OK (resposta recebida)';
                        } else {
                            $testResult = ' — 🔴 SNMP sem resposta (verifique IP, community e porta)';
                        }
                    }
                    $successMsg = 'Equipamento atualizado com sucesso!' . $testResult;
                } else {
                    // CRIAÇÃO — redireciona (PRG pattern: evita duplicação no F5/voltar)
                    $pdo->prepare("INSERT INTO nms_devices (user_id, name, hostname, type, location,
                        snmp_enabled, snmp_version, snmp_community, snmp_user, snmp_auth_proto, snmp_priv_proto, snmp_auth_pass, snmp_priv_pass, snmp_port,
                        api_enabled, api_user, api_password, api_port, api_use_ssl, poll_interval, active, map_lat, map_lng)
                        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
                        ->execute([$user['id'], $name, $hostname, $type, $location ?: null,
                            $snmp_enabled, $snmp_version, $snmp_community ?: null, $snmp_user ?: null,
                            $snmp_auth_proto, $snmp_priv_proto,
                            $snmp_auth_pass ?: null, $snmp_priv_pass ?: null, $snmp_port,
                            $api_enabled, $api_user ?: null, $api_password ?: null, $api_port, $api_use_ssl,
                            $poll_interval, $active, $map_lat, $map_lng]);
                    // Redirect-After-Post: impede duplicação ao recarregar ou usar botão Voltar
                    header('Location: ' . NMS_URL . '?page=nms_devices&saved=1');
                    exit;
                }
            } catch (Exception $e) {
                $errorMsg = 'Erro ao salvar: ' . $e->getMessage();
            }
        }
    }
}

$isEdit = $dev !== null;
$f = $dev ?? [
    'name'=>'', 'hostname'=>'', 'type'=>'mikrotik', 'location'=>'',
    'snmp_enabled'=>1, 'snmp_version'=>'2c', 'snmp_community'=>'public',
    'snmp_user'=>'', 'snmp_auth_proto'=>'MD5', 'snmp_priv_proto'=>'DES',
    'snmp_auth_pass'=>'', 'snmp_priv_pass'=>'', 'snmp_port'=>161,
    'api_enabled'=>0, 'api_user'=>'admin', 'api_password'=>'', 'api_port'=>8728, 'api_use_ssl'=>0,
    'poll_interval'=>60, 'active'=>1, 'map_lat'=>null, 'map_lng'=>null,
];

// ── Somente agora inclui o header (que envia HTML) ──
require_once __DIR__ . '/../../includes/header.php';

$inputStyle      = "width:100%; padding:11px 14px; border:1px solid #cbd5e1; border-radius:10px; font-size:0.95rem; font-family:inherit; outline:none; transition:border-color 0.2s; box-sizing:border-box;";
$labelStyle      = "display:block; font-weight:600; font-size:0.85rem; color:#475569; margin-bottom:6px;";
$sectionStyle    = "background:#fff; border-radius:16px; border:1px solid #e2e8f0; overflow:hidden;";
$sectionHdrStyle = "padding:18px 24px; border-bottom:1px solid #e2e8f0; background:#f8fafc;";
$sectionBdyStyle = "padding:24px;";
?>

<div style="display:flex; flex-direction:column; gap:20px; max-width:1000px; margin:0 auto; width:100%;">

    <!-- Breadcrumb -->
    <div style="display:flex; align-items:center; gap:8px; font-size:0.85rem; color:#64748b;">
        <a href="<?= NMS_URL ?>?page=nms_dashboard" style="color:#3b82f6; text-decoration:none; font-weight:600;">NMS</a>
        <span>›</span>
        <a href="<?= NMS_URL ?>?page=nms_devices" style="color:#3b82f6; text-decoration:none; font-weight:600;">Equipamentos</a>
        <span>›</span>
        <span style="color:#0f172a; font-weight:700;"><?= $isEdit ? h($dev['name']) : 'Novo Equipamento' ?></span>
    </div>

    <!-- Page Header -->
    <div style="background:linear-gradient(135deg,#1e293b,#0f172a); border-radius:20px; padding:28px 32px; color:#f1f5f9;">
        <h1 style="margin:0; font-size:1.6rem; font-weight:900;">
            <?= $isEdit ? '✏️ Editar Equipamento' : '➕ Novo Equipamento' ?>
        </h1>
        <p style="margin:6px 0 0; color:#94a3b8; font-size:0.9rem;">
            <?= $isEdit ? 'Atualize as configurações do equipamento monitorado.' : 'Cadastre um novo equipamento para monitoramento via SNMP ou API MikroTik.' ?>
        </p>
    </div>

    <?php if ($successMsg): ?>
        <div style="padding:14px 18px; background:#dcfce7; border-left:4px solid #22c55e; color:#166534; border-radius:10px; font-weight:600; display:flex; align-items:center; gap:8px;">
            ✅ <?= h($successMsg) ?>
            <a href="<?= NMS_URL ?>?page=nms_devices" style="margin-left:auto; font-size:0.85rem; color:#166534; text-decoration:underline;">Voltar à lista</a>
        </div>
    <?php endif; ?>
    <?php if ($errorMsg): ?>
        <div style="padding:14px 18px; background:#fee2e2; border-left:4px solid #ef4444; color:#b91c1c; border-radius:10px; font-weight:600;">
            ⚠️ <?= h($errorMsg) ?>
        </div>
    <?php endif; ?>

    <form method="post" style="display:flex; flex-direction:column; gap:20px;">
        <input type="hidden" name="csrf_token" value="<?= h(csrf_token()) ?>">

        <!-- Identificação -->
        <div style="<?= $sectionStyle ?>">
            <div style="<?= $sectionHdrStyle ?>">
                <h3 style="margin:0; font-size:1rem; font-weight:700; color:#0f172a;">🏷️ Identificação</h3>
                <p style="margin:2px 0 0; color:#64748b; font-size:0.82rem;">Informações básicas do equipamento</p>
            </div>
            <div style="<?= $sectionBdyStyle ?>">
                <div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(240px,1fr)); gap:16px;">
                    <div>
                        <label style="<?= $labelStyle ?>">Nome do Equipamento <span style="color:#ef4444;">*</span></label>
                        <input type="text" name="name" value="<?= h($f['name']) ?>" placeholder="Ex: MikroTik-Core-01" required
                            style="<?= $inputStyle ?>" onfocus="this.style.borderColor='#3b82f6'" onblur="this.style.borderColor='#cbd5e1'">
                    </div>
                    <div>
                        <label style="<?= $labelStyle ?>">Hostname / IP <span style="color:#ef4444;">*</span></label>
                        <input type="text" name="hostname" value="<?= h($f['hostname']) ?>" placeholder="Ex: 192.168.1.1 ou router.local" required
                            style="<?= $inputStyle ?>" onfocus="this.style.borderColor='#3b82f6'" onblur="this.style.borderColor='#cbd5e1'">
                    </div>
                    <div>
                        <label style="<?= $labelStyle ?>">Tipo de Equipamento</label>
                        <select name="type" style="<?= $inputStyle ?> background:#fff; cursor:pointer;"
                            onfocus="this.style.borderColor='#3b82f6'" onblur="this.style.borderColor='#cbd5e1'">
                            <?php foreach (['mikrotik'=>'MikroTik','cisco'=>'Cisco','olt'=>'OLT','switch'=>'Switch','server'=>'Servidor','other'=>'Outro'] as $v=>$l): ?>
                                <option value="<?= $v ?>" <?= $f['type']===$v?'selected':'' ?>><?= $l ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label style="<?= $labelStyle ?>">Localização (opcional)</label>
                        <input type="text" name="location" value="<?= h($f['location'] ?? '') ?>" placeholder="Ex: Rack A - Sala de TI"
                            style="<?= $inputStyle ?>" onfocus="this.style.borderColor='#3b82f6'" onblur="this.style.borderColor='#cbd5e1'">
                    </div>
                </div>
                <div style="margin-top:20px; display:flex; gap:24px; flex-wrap:wrap;">
                    <label style="display:inline-flex; align-items:center; gap:10px; cursor:pointer; background:#f8fafc; padding:12px 18px; border-radius:10px; border:1px solid #e2e8f0; width:fit-content;">
                        <input type="checkbox" name="active" <?= $f['active'] ? 'checked' : '' ?> style="width:18px; height:18px; accent-color:#3b82f6;">
                        <span style="font-weight:700; color:#0f172a; font-size:0.9rem;">Equipamento Ativo</span>
                    </label>
                    <div>
                        <label style="<?= $labelStyle ?>">Intervalo de Poll (segundos)</label>
                        <input type="number" name="poll_interval" value="<?= (int)$f['poll_interval'] ?>" min="10" max="3600"
                            style="<?= $inputStyle ?> width:140px;" onfocus="this.style.borderColor='#3b82f6'" onblur="this.style.borderColor='#cbd5e1'">
                    </div>
                </div>
            </div>
        </div>

        <!-- SNMP -->
        <div style="<?= $sectionStyle ?>">
            <div style="<?= $sectionHdrStyle ?> display:flex; justify-content:space-between; align-items:center;">
                <div>
                    <h3 style="margin:0; font-size:1rem; font-weight:700; color:#0f172a;">📡 SNMP</h3>
                    <p style="margin:2px 0 0; color:#64748b; font-size:0.82rem;">Coleta via SNMP v2c ou v3 (funciona para qualquer equipamento)</p>
                </div>
                <label style="display:inline-flex; align-items:center; gap:8px; cursor:pointer;">
                    <input type="checkbox" name="snmp_enabled" id="snmpToggle" <?= $f['snmp_enabled'] ? 'checked' : '' ?> style="width:18px; height:18px; accent-color:#3b82f6;">
                    <span style="font-weight:700; color:#0f172a; font-size:0.85rem;">Habilitar SNMP</span>
                </label>
            </div>
            <div id="snmpFields" style="<?= $sectionBdyStyle ?> <?= $f['snmp_enabled'] ? '' : 'display:none;' ?>">
                <div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(200px,1fr)); gap:16px;">
                    <div>
                        <label style="<?= $labelStyle ?>">Versão SNMP</label>
                        <select name="snmp_version" id="snmpVersion" style="<?= $inputStyle ?> background:#fff; cursor:pointer;"
                            onfocus="this.style.borderColor='#3b82f6'" onblur="this.style.borderColor='#cbd5e1'" onchange="toggleSnmpV3()">
                            <option value="2c" <?= ($f['snmp_version']==='2c')?'selected':'' ?>>SNMP v2c</option>
                            <option value="3"  <?= ($f['snmp_version']==='3') ?'selected':'' ?>>SNMP v3</option>
                        </select>
                    </div>
                    <div>
                        <label style="<?= $labelStyle ?>">Porta SNMP</label>
                        <input type="number" name="snmp_port" value="<?= (int)$f['snmp_port'] ?>" min="1" max="65535"
                            style="<?= $inputStyle ?>" onfocus="this.style.borderColor='#3b82f6'" onblur="this.style.borderColor='#cbd5e1'">
                    </div>
                    <div id="snmpCommunityField" <?= $f['snmp_version']==='3' ? 'style="display:none"' : '' ?>>
                        <label style="<?= $labelStyle ?>">Nome da Community v2c</label>
                        <input type="text" name="snmp_community" value="<?= h($f['snmp_community'] ?? 'public') ?>" placeholder="public"
                            style="<?= $inputStyle ?>" onfocus="this.style.borderColor='#3b82f6'" onblur="this.style.borderColor='#cbd5e1'">
                        <div style="font-size:0.75rem; color:#64748b; margin-top:4px;">
                            Nome configurado no equipamento em <code>SNMP → Communities</code>. Este nome serve como autenticação (ex: <code>public</code>, <code>gohost</code>).
                        </div>
                    </div>
                </div>
                <div id="snmpV3Fields" style="margin-top:16px; display:grid; grid-template-columns:repeat(auto-fit,minmax(200px,1fr)); gap:16px; <?= $f['snmp_version']==='3' ? '' : 'display:none!important' ?>">
                    <div>
                        <label style="<?= $labelStyle ?>">Usuário SNMPv3</label>
                        <input type="text" name="snmp_user" value="<?= h($f['snmp_user'] ?? '') ?>" placeholder="monitoruser"
                            style="<?= $inputStyle ?>" onfocus="this.style.borderColor='#3b82f6'" onblur="this.style.borderColor='#cbd5e1'">
                    </div>
                    <div>
                        <label style="<?= $labelStyle ?>">Protocolo Auth</label>
                        <select name="snmp_auth_proto" style="<?= $inputStyle ?> background:#fff; cursor:pointer;"
                            onfocus="this.style.borderColor='#3b82f6'" onblur="this.style.borderColor='#cbd5e1'">
                            <option value="MD5" <?= ($f['snmp_auth_proto'] ?? 'MD5')==='MD5'?'selected':'' ?>>MD5</option>
                            <option value="SHA" <?= ($f['snmp_auth_proto'] ?? '')==='SHA'?'selected':'' ?>>SHA</option>
                        </select>
                    </div>
                    <div>
                        <label style="<?= $labelStyle ?>">Auth Password</label>
                        <input type="password" name="snmp_auth_pass" value="<?= h($f['snmp_auth_pass'] ?? '') ?>" placeholder="••••••••"
                            style="<?= $inputStyle ?>" onfocus="this.style.borderColor='#3b82f6'" onblur="this.style.borderColor='#cbd5e1'">
                    </div>
                    <div>
                        <label style="<?= $labelStyle ?>">Protocolo Priv</label>
                        <select name="snmp_priv_proto" style="<?= $inputStyle ?> background:#fff; cursor:pointer;"
                            onfocus="this.style.borderColor='#3b82f6'" onblur="this.style.borderColor='#cbd5e1'">
                            <option value="DES" <?= ($f['snmp_priv_proto'] ?? 'DES')==='DES'?'selected':'' ?>>DES</option>
                            <option value="AES" <?= ($f['snmp_priv_proto'] ?? '')==='AES'?'selected':'' ?>>AES</option>
                        </select>
                    </div>
                    <div>
                        <label style="<?= $labelStyle ?>">Priv Password</label>
                        <input type="password" name="snmp_priv_pass" value="<?= h($f['snmp_priv_pass'] ?? '') ?>" placeholder="••••••••"
                            style="<?= $inputStyle ?>" onfocus="this.style.borderColor='#3b82f6'" onblur="this.style.borderColor='#cbd5e1'">
                    </div>
                </div>
            </div>
        </div>

        <!-- API MikroTik -->
        <div style="<?= $sectionStyle ?>">
            <div style="<?= $sectionHdrStyle ?> display:flex; justify-content:space-between; align-items:center;">
                <div>
                    <h3 style="margin:0; font-size:1rem; font-weight:700; color:#0f172a;">⚡ API MikroTik (RouterOS)</h3>
                    <p style="margin:2px 0 0; color:#64748b; font-size:0.82rem;">Coleta via REST API RouterOS 7.x — mais detalhes (PPPoE, DHCP, filas)</p>
                </div>
                <label style="display:inline-flex; align-items:center; gap:8px; cursor:pointer;">
                    <input type="checkbox" name="api_enabled" id="apiToggle" <?= $f['api_enabled'] ? 'checked' : '' ?> style="width:18px; height:18px; accent-color:#8b5cf6;">
                    <span style="font-weight:700; color:#0f172a; font-size:0.85rem;">Habilitar API</span>
                </label>
            </div>
            <div id="apiFields" style="<?= $sectionBdyStyle ?> <?= $f['api_enabled'] ? '' : 'display:none;' ?>">
                <div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(200px,1fr)); gap:16px;">
                    <div>
                        <label style="<?= $labelStyle ?>">Usuário API</label>
                        <input type="text" name="api_user" value="<?= h($f['api_user'] ?? 'admin') ?>" placeholder="admin"
                            style="<?= $inputStyle ?>" onfocus="this.style.borderColor='#8b5cf6'" onblur="this.style.borderColor='#cbd5e1'">
                    </div>
                    <div>
                        <label style="<?= $labelStyle ?>">Senha API</label>
                        <input type="password" name="api_password" value="<?= h($f['api_password'] ?? '') ?>" placeholder="••••••••"
                            style="<?= $inputStyle ?>" onfocus="this.style.borderColor='#8b5cf6'" onblur="this.style.borderColor='#cbd5e1'">
                    </div>
                    <div>
                        <label style="<?= $labelStyle ?>">Porta REST API</label>
                        <input type="number" name="api_port" value="<?= (int)($f['api_port'] ?? 8728) ?>" min="1" max="65535"
                            style="<?= $inputStyle ?>" onfocus="this.style.borderColor='#8b5cf6'" onblur="this.style.borderColor='#cbd5e1'">
                        <div style="font-size:0.75rem; color:#94a3b8; margin-top:4px;">Padrão: 8728 (sem SSL) ou 8729 (com SSL)</div>
                    </div>
                    <div style="display:flex; align-items:flex-end; padding-bottom:4px;">
                        <label style="display:inline-flex; align-items:center; gap:10px; cursor:pointer; background:#f5f3ff; padding:12px 18px; border-radius:10px; border:1px solid #e9d5ff; width:100%;">
                            <input type="checkbox" name="api_use_ssl" <?= $f['api_use_ssl'] ? 'checked' : '' ?> style="width:18px; height:18px; accent-color:#8b5cf6;">
                            <span style="font-weight:700; color:#6d28d9; font-size:0.9rem;">Usar SSL/TLS</span>
                        </label>
                    </div>
                </div>
                <div style="margin-top:14px; padding:12px 16px; background:#fffbeb; border:1px solid #fde68a; border-radius:8px; font-size:0.82rem; color:#92400e;">
                    ⚠️ Certifique-se que a API REST está habilitada no MikroTik em <code>IP → Services → api-ssl</code> ou <code>api</code>.
                </div>
            </div>
        </div>

        <!-- Localização no Mapa -->
        <div style="<?= $sectionStyle ?>">
            <div style="<?= $sectionHdrStyle ?>">
                <h3 style="margin:0; font-size:1rem; font-weight:700; color:#0f172a;">🗺️ Posição no Mapa</h3>
                <p style="margin:2px 0 0; color:#64748b; font-size:0.82rem;">Clique no mapa para definir a localização do equipamento (opcional)</p>
            </div>
            <div style="<?= $sectionBdyStyle ?>">
                <div style="display:grid; grid-template-columns:1fr 1fr; gap:16px; margin-bottom:16px;">
                    <div>
                        <label style="<?= $labelStyle ?>">Latitude</label>
                        <input type="text" name="map_lat" id="map_lat" value="<?= $f['map_lat'] !== null ? h((string)$f['map_lat']) : '' ?>" placeholder="Ex: -23.5505"
                            style="<?= $inputStyle ?>" onfocus="this.style.borderColor='#3b82f6'" onblur="this.style.borderColor='#cbd5e1'" oninput="updateMarkerFromInputs()">
                    </div>
                    <div>
                        <label style="<?= $labelStyle ?>">Longitude</label>
                        <input type="text" name="map_lng" id="map_lng" value="<?= $f['map_lng'] !== null ? h((string)$f['map_lng']) : '' ?>" placeholder="Ex: -46.6333"
                            style="<?= $inputStyle ?>" onfocus="this.style.borderColor='#3b82f6'" onblur="this.style.borderColor='#cbd5e1'" oninput="updateMarkerFromInputs()">
                    </div>
                </div>
                <div id="formMap" style="height:340px; border-radius:12px; border:1px solid #e2e8f0; overflow:hidden; background:#f1f5f9;"></div>
                <p style="margin:10px 0 0; font-size:0.78rem; color:#94a3b8;">
                    💡 Clique em qualquer ponto do mapa para posicionar o equipamento. Use o campo de busca para encontrar a cidade. Deixe em branco para não exibir no mapa.
                </p>
                <div style="margin-top:10px;">
                    <button type="button" onclick="clearMapCoords()" style="padding:8px 18px; border:1px solid #e2e8f0; border-radius:8px; background:#f8fafc; color:#64748b; font-size:0.82rem; font-weight:600; cursor:pointer;">
                        🗑️ Limpar coordenadas
                    </button>
                </div>
            </div>
        </div>

        <!-- Botões -->
        <div style="display:flex; justify-content:space-between; align-items:center; padding:20px 0;">
            <a href="<?= NMS_URL ?>?page=nms_devices" style="padding:12px 24px; border:1px solid #e2e8f0; border-radius:12px; color:#64748b; font-weight:600; text-decoration:none; font-size:0.95rem; transition:0.2s;"
                onmouseover="this.style.background='#f8fafc'" onmouseout="this.style.background='transparent'">
                ← Cancelar
            </a>
            <button type="submit" style="padding:13px 36px; background:linear-gradient(135deg,#3b82f6,#2563eb); color:#fff; border:none; border-radius:12px; font-weight:700; font-size:1rem; cursor:pointer; transition:0.2s; box-shadow:0 4px 12px rgba(37,99,235,0.3);"
                onmouseover="this.style.transform='translateY(-1px)'; this.style.boxShadow='0 6px 16px rgba(37,99,235,0.4)'"
                onmouseout="this.style.transform=''; this.style.boxShadow='0 4px 12px rgba(37,99,235,0.3)'">
                <?= $isEdit ? '💾 Salvar Alterações' : '✅ Cadastrar Equipamento' ?>
            </button>
        </div>
    </form>

    <?php if ($isEdit): ?>
    <!-- Zona de perigo -->
    <div style="background:#fff; border-radius:16px; border:2px solid #fee2e2; overflow:hidden; margin-top:4px;">
        <div style="padding:18px 24px; border-bottom:1px solid #fee2e2; background:#fef2f2; display:flex; align-items:center; gap:8px;">
            <svg width="18" height="18" fill="none" stroke="#ef4444" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg>
            <h3 style="margin:0; font-size:1rem; font-weight:700; color:#b91c1c;">Zona de Perigo</h3>
        </div>
        <div style="padding:20px 24px; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:16px;">
            <div>
                <p style="margin:0; font-weight:600; color:#0f172a; font-size:0.95rem;">Remover este equipamento</p>
                <p style="margin:4px 0 0; color:#64748b; font-size:0.82rem;">Remove permanentemente o equipamento, interfaces, histórico de banda e métricas.</p>
            </div>
            <form method="post" action="<?= NMS_URL ?>?page=nms_devices"
                onsubmit="return confirm('Tem certeza? Esta ação remove o equipamento e TODOS os dados coletados. Não há como desfazer.');">
                <input type="hidden" name="csrf_token" value="<?= h(csrf_token()) ?>">
                <input type="hidden" name="action" value="delete_device">
                <input type="hidden" name="id" value="<?= (int)$dev['id'] ?>">
                <button type="submit" style="display:inline-flex; align-items:center; gap:8px; padding:11px 22px; background:#ef4444; color:#fff; border:none; border-radius:10px; font-weight:700; font-size:0.95rem; cursor:pointer; transition:0.2s;"
                    onmouseover="this.style.background='#dc2626'" onmouseout="this.style.background='#ef4444'">
                    <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                    Deletar Equipamento
                </button>
            </form>
        </div>
    </div>
    <?php endif; ?>
</div>

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
document.getElementById('snmpToggle').addEventListener('change', function() {
    document.getElementById('snmpFields').style.display = this.checked ? '' : 'none';
});
document.getElementById('apiToggle').addEventListener('change', function() {
    document.getElementById('apiFields').style.display = this.checked ? '' : 'none';
});
function toggleSnmpV3() {
    const v3 = document.getElementById('snmpVersion').value === '3';
    document.getElementById('snmpV3Fields').style.display      = v3 ? 'grid' : 'none';
    document.getElementById('snmpCommunityField').style.display = v3 ? 'none' : '';
}
toggleSnmpV3();

// ── Mapa picker ──
(function() {
    const latInput = document.getElementById('map_lat');
    const lngInput = document.getElementById('map_lng');
    const initLat  = parseFloat(latInput.value) || -15.7801;
    const initLng  = parseFloat(lngInput.value) || -47.9292;
    const initZoom = (latInput.value && lngInput.value) ? 13 : 5;

    const map = L.map('formMap').setView([initLat, initLng], initZoom);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors',
        maxZoom: 19
    }).addTo(map);

    let marker = null;

    function placeMarker(lat, lng) {
        if (marker) marker.setLatLng([lat, lng]);
        else marker = L.marker([lat, lng], { draggable: true }).addTo(map);
        marker.off('dragend').on('dragend', function(e) {
            const p = e.target.getLatLng();
            latInput.value = p.lat.toFixed(7);
            lngInput.value = p.lng.toFixed(7);
        });
    }

    if (latInput.value && lngInput.value) {
        placeMarker(initLat, initLng);
    }

    map.on('click', function(e) {
        latInput.value = e.latlng.lat.toFixed(7);
        lngInput.value = e.latlng.lng.toFixed(7);
        placeMarker(e.latlng.lat, e.latlng.lng);
    });

    window.updateMarkerFromInputs = function() {
        const lat = parseFloat(latInput.value);
        const lng = parseFloat(lngInput.value);
        if (!isNaN(lat) && !isNaN(lng) && lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180) {
            placeMarker(lat, lng);
            map.setView([lat, lng], map.getZoom() < 8 ? 13 : map.getZoom());
        }
    };

    window.clearMapCoords = function() {
        latInput.value = '';
        lngInput.value = '';
        if (marker) { map.removeLayer(marker); marker = null; }
    };
})();
</script>

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