<?php
$file = "/var/www/html/mikrotik/views/device_detail.php";
$content = file_get_contents($file);

if (strpos($content, 'set_interface_alert') !== false) {
    echo "JA_APLICADO\n";
    exit;
}

// Patch 1: Handler POST logo após inicialização do $id
$old1 = 'if (!$id) { header(\'Location: mikrotik/index.php?page=nms_devices\'); exit; }';
$new1 = 'if (!$id) { header(\'Location: mikrotik/index.php?page=nms_devices\'); exit; }

// Handler: salvar configuração de alerta por interface
if ($_SERVER[\'REQUEST_METHOD\'] === \'POST\' && ($_POST[\'action\'] ?? \'\') === \'set_interface_alert\') {
    $ifaceId  = (int)($_POST[\'iface_id\'] ?? 0);
    $alertOn  = !empty($_POST[\'alert_on_down\']);
    $alertEmail = trim($_POST[\'alert_email\'] ?? \'\');
    if ($ifaceId) {
        if ($alertOn && filter_var($alertEmail, FILTER_VALIDATE_EMAIL)) {
            $pdo->prepare("UPDATE nms_interfaces SET alert_on_down=\'true\', alert_email=? WHERE id=? AND device_id=?")
                ->execute([$alertEmail, $ifaceId, $id]);
        } else {
            $pdo->prepare("UPDATE nms_interfaces SET alert_on_down=\'false\', alert_email=NULL WHERE id=? AND device_id=?")
                ->execute([$ifaceId, $id]);
        }
    }
    header(\'Location: \' . NMS_URL . \'?page=nms_device_detail&id=\' . $id);
    exit;
}';

$content = str_replace($old1, $new1, $content);

// Patch 2: Cabeçalho da coluna Alerta
$old2 = '<th style="padding:14px 16px; text-align:center; font-weight:700; color:#475569; font-size:0.85rem; text-transform:uppercase; border-bottom:2px solid #e2e8f0;">Banda</th>
                        </tr>';
$new2 = '<th style="padding:14px 16px; text-align:center; font-weight:700; color:#475569; font-size:0.85rem; text-transform:uppercase; border-bottom:2px solid #e2e8f0;">Banda</th>
                            <th style="padding:14px 16px; text-align:center; font-weight:700; color:#475569; font-size:0.85rem; text-transform:uppercase; border-bottom:2px solid #e2e8f0;">Alerta</th>
                        </tr>';
$content = str_replace($old2, $new2, $content);

// Patch 3: Após o botão de Gráfico, adicionar coluna Alerta + row configuração
$old3 = '                                </td>
                            </tr>
                            <!-- Row expandível com gráfico de banda -->
                            <tr id="bwrow-<?= (int)$iface[\'id\'] ?>" style="display:none;">
                                <td colspan="7"';
$new3 = '                                </td>
                                <!-- Coluna Alerta -->
                                <td style="padding:14px 16px; text-align:center;">
                                    <?php if (!empty($iface[\'alert_on_down\']) && !empty($iface[\'alert_email\'])): ?>
                                        <button onclick="toggleAlertRow(<?= (int)$iface[\'id\'] ?>)" title="Monitoramento ativo"
                                            style="display:inline-flex;align-items:center;gap:6px;padding:8px 14px;background:#dcfce7;color:#15803d;border:1px solid #86efac;border-radius:8px;font-size:0.85rem;font-weight:700;cursor:pointer;">
                                            🔔 Alertando
                                        </button>
                                    <?php else: ?>
                                        <button onclick="toggleAlertRow(<?= (int)$iface[\'id\'] ?>)" title="Ativar alerta"
                                            style="display:inline-flex;align-items:center;gap:6px;padding:8px 14px;background:#f1f5f9;color:#64748b;border:1px solid #e2e8f0;border-radius:8px;font-size:0.85rem;font-weight:700;cursor:pointer;">
                                            🔕 Monitorar
                                        </button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <!-- Row expandível: configuração de alerta -->
                            <tr id="alertrow-<?= (int)$iface[\'id\'] ?>" style="display:none;">
                                <td colspan="8" style="padding:0;background:#fffbeb;border-bottom:2px solid #fde68a;">
                                    <div style="padding:20px 28px;display:flex;align-items:center;gap:16px;flex-wrap:wrap;">
                                        <span style="font-size:1rem;font-weight:800;color:#92400e;">🔔 Alerta — <?= h($iface[\'if_name\']) ?></span>
                                        <form method="post" style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;">
                                            <input type="hidden" name="action" value="set_interface_alert">
                                            <input type="hidden" name="iface_id" value="<?= (int)$iface[\'id\'] ?>">
                                            <input type="email" name="alert_email"
                                                value="<?= h($iface[\'alert_email\'] ?? $user[\'email\'] ?? \'\') ?>"
                                                placeholder="email@destino.com"
                                                style="padding:8px 12px;border:1px solid #fcd34d;border-radius:8px;font-size:0.9rem;min-width:220px;background:#fff;">
                                            <label style="display:flex;align-items:center;gap:6px;font-size:0.9rem;font-weight:600;color:#92400e;cursor:pointer;">
                                                <input type="checkbox" name="alert_on_down" value="1"
                                                    <?= !empty($iface[\'alert_on_down\']) ? \'checked\' : \'\' ?>>
                                                Alertar quando cair
                                            </label>
                                            <button type="submit"
                                                style="padding:8px 18px;background:#f59e0b;color:#fff;border:none;border-radius:8px;font-weight:700;font-size:0.9rem;cursor:pointer;">
                                                Salvar
                                            </button>
                                            <?php if (!empty($iface[\'alert_on_down\'])): ?>
                                            <button type="submit" onclick="document.querySelector(\'#alertrow-<?= (int)$iface[\'id\'] ?> input[name=alert_on_down]\').checked=false"
                                                style="padding:8px 14px;background:#fee2e2;color:#dc2626;border:1px solid #fca5a5;border-radius:8px;font-weight:700;font-size:0.9rem;cursor:pointer;">
                                                Desativar
                                            </button>
                                            <?php endif; ?>
                                            <button type="button" onclick="toggleAlertRow(<?= (int)$iface[\'id\'] ?>)"
                                                style="padding:8px 14px;background:#f1f5f9;color:#64748b;border:1px solid #e2e8f0;border-radius:8px;font-weight:700;font-size:0.9rem;cursor:pointer;">
                                                Cancelar
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                            <!-- Row expandível com gráfico de banda -->
                            <tr id="bwrow-<?= (int)$iface[\'id\'] ?>" style="display:none;">
                                <td colspan="8"';
$content = str_replace($old3, $new3, $content);

// Patch 4: JS toggleAlertRow
$old4 = 'function toggleBwChart(ifaceId) {';
$new4 = 'function toggleAlertRow(ifaceId) {
    const row = document.getElementById(\'alertrow-\' + ifaceId);
    if (!row) return;
    row.style.display = row.style.display === \'none\' ? \'table-row\' : \'none\';
}

function toggleBwChart(ifaceId) {';
$content = str_replace($old4, $new4, $content);

file_put_contents($file, $content);
echo "PATCH_OK\n";
echo "Size: " . strlen($content) . "\n";
