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

if ($editId) {
    $s = $pdo->prepare("SELECT * FROM ubiquiti_panels WHERE id=? AND user_id=?");
    $s->execute([$editId, $user['id']]);
    $panel = $s->fetch(PDO::FETCH_ASSOC);
    if (!$panel) { header('Location: ' . UBNT_URL . '?page=ubnt_panels'); 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'] ?? '');
        $location        = trim($_POST['location'] ?? '');
        $snmp_community  = trim($_POST['snmp_community'] ?? 'public') ?: 'public';
        $snmp_port       = max(1, min(65535, (int)($_POST['snmp_port'] ?? 161)));
        $alert_iface_speed = isset($_POST['alert_iface_speed']) ? 1 : 0;
        $alert_iface_down  = isset($_POST['alert_iface_down'])  ? 1 : 0;
        $alert_clients     = isset($_POST['alert_clients'])     ? 1 : 0;
        $alert_client_mode = in_array($_POST['alert_client_mode'] ?? '', ['absolute','percent'])
                             ? $_POST['alert_client_mode'] : 'absolute';
        $alert_client_threshold = max(1, min(999, (int)($_POST['alert_client_threshold'] ?? 3)));
        $alert_client_window    = max(1, min(60,  (int)($_POST['alert_client_window']    ?? 2)));
        $alert_phone     = preg_replace('/[^0-9+]/', '', $_POST['alert_phone'] ?? '');
        $poll_interval   = max(30, min(3600, (int)($_POST['poll_interval'] ?? 60)));
        $active          = isset($_POST['active']) ? 1 : 0;

        if ($name === '' || $hostname === '') {
            $errorMsg = 'Nome e hostname/IP são obrigatórios.';
        } else {
            try {
                if ($editId && $panel) {
                    $pdo->prepare("
                        UPDATE ubiquiti_panels SET
                            name=?, hostname=?, location=?, snmp_community=?, snmp_port=?,
                            alert_iface_speed=?, alert_iface_down=?,
                            alert_clients=?, alert_client_mode=?, alert_client_threshold=?, alert_client_window=?,
                            alert_phone=?, poll_interval=?, active=?
                        WHERE id=? AND user_id=?
                    ")->execute([
                        $name, $hostname, $location ?: null, $snmp_community, $snmp_port,
                        $alert_iface_speed, $alert_iface_down,
                        $alert_clients, $alert_client_mode, $alert_client_threshold, $alert_client_window,
                        $alert_phone ?: null, $poll_interval, $active,
                        $editId, $user['id']
                    ]);
                    $s = $pdo->prepare("SELECT * FROM ubiquiti_panels WHERE id=? AND user_id=?");
                    $s->execute([$editId, $user['id']]);
                    $panel = $s->fetch(PDO::FETCH_ASSOC);
                    $successMsg = 'Painel atualizado com sucesso!';
                } else {
                    $pdo->prepare("
                        INSERT INTO ubiquiti_panels
                            (user_id, name, hostname, location, snmp_community, snmp_port,
                             alert_iface_speed, alert_iface_down,
                             alert_clients, alert_client_mode, alert_client_threshold, alert_client_window,
                             alert_phone, poll_interval, active)
                        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
                    ")->execute([
                        $user['id'], $name, $hostname, $location ?: null, $snmp_community, $snmp_port,
                        $alert_iface_speed, $alert_iface_down,
                        $alert_clients, $alert_client_mode, $alert_client_threshold, $alert_client_window,
                        $alert_phone ?: null, $poll_interval, $active,
                    ]);
                    header('Location: ' . UBNT_URL . '?page=ubnt_panels'); exit;
                }
            } catch (PDOException $e) {
                $errorMsg = 'Erro ao salvar: ' . $e->getMessage();
            }
        }
    }
}

$v = fn(string $field, $default = '') => h($panel[$field] ?? $default);

require_once __DIR__ . '/../../includes/header.php';
?>

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

    <!-- Breadcrumb -->
    <div style="display:flex;align-items:center;gap:8px;font-size:0.85rem;color:#64748b;">
        <a href="<?= UBNT_URL ?>?page=ubnt_panels" style="color:#1d4ed8;text-decoration:none;font-weight:600;">Painéis</a>
        <span>›</span>
        <span><?= $editId ? 'Editar Painel' : 'Novo Painel' ?></span>
    </div>

    <?php if ($successMsg): ?>
        <div style="background:#f0fdf4;border:1px solid #86efac;border-radius:12px;padding:14px 20px;color:#166534;font-weight:600;"><?= h($successMsg) ?></div>
    <?php endif; ?>
    <?php if ($errorMsg): ?>
        <div style="background:#fef2f2;border:1px solid #fca5a5;border-radius:12px;padding:14px 20px;color:#991b1b;font-weight:600;"><?= h($errorMsg) ?></div>
    <?php endif; ?>

    <form method="POST" action="<?= UBNT_URL ?>?page=ubnt_panel_form<?= $editId ? '&id='.$editId : '' ?>">
        <input type="hidden" name="csrf_token" value="<?= csrf_token() ?>">

        <!-- Identificação -->
        <div style="background:#fff;border-radius:20px;border:1px solid #e2e8f0;padding:28px;margin-bottom:16px;">
            <h3 style="margin:0 0 20px;font-size:1rem;font-weight:700;color:#0f172a;display:flex;align-items:center;gap:8px;">
                <svg width="16" height="16" fill="none" stroke="#1d4ed8" 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>
                Identificação
            </h3>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                <div>
                    <label style="display:block;font-size:0.82rem;font-weight:600;color:#374151;margin-bottom:6px;">Nome *</label>
                    <input type="text" name="name" value="<?= $v('name') ?>" required
                        style="width:100%;padding:10px 14px;border:1px solid #d1d5db;border-radius:10px;font-size:0.9rem;box-sizing:border-box;"
                        placeholder="Torre Norte - AP 01">
                </div>
                <div>
                    <label style="display:block;font-size:0.82rem;font-weight:600;color:#374151;margin-bottom:6px;">Hostname / IP *</label>
                    <input type="text" name="hostname" value="<?= $v('hostname') ?>" required
                        style="width:100%;padding:10px 14px;border:1px solid #d1d5db;border-radius:10px;font-size:0.9rem;box-sizing:border-box;"
                        placeholder="192.168.1.100">
                </div>
                <div style="grid-column:1/-1;">
                    <label style="display:block;font-size:0.82rem;font-weight:600;color:#374151;margin-bottom:6px;">Localização</label>
                    <input type="text" name="location" value="<?= $v('location') ?>"
                        style="width:100%;padding:10px 14px;border:1px solid #d1d5db;border-radius:10px;font-size:0.9rem;box-sizing:border-box;"
                        placeholder="Bairro / Cidade">
                </div>
            </div>
        </div>

        <!-- SNMP -->
        <div style="background:#fff;border-radius:20px;border:1px solid #e2e8f0;padding:28px;margin-bottom:16px;">
            <h3 style="margin:0 0 20px;font-size:1rem;font-weight:700;color:#0f172a;">SNMP</h3>
            <div style="display:grid;grid-template-columns:2fr 1fr;gap:16px;">
                <div>
                    <label style="display:block;font-size:0.82rem;font-weight:600;color:#374151;margin-bottom:6px;">Community</label>
                    <input type="text" name="snmp_community" value="<?= $v('snmp_community','public') ?>"
                        style="width:100%;padding:10px 14px;border:1px solid #d1d5db;border-radius:10px;font-size:0.9rem;box-sizing:border-box;"
                        placeholder="public">
                </div>
                <div>
                    <label style="display:block;font-size:0.82rem;font-weight:600;color:#374151;margin-bottom:6px;">Porta</label>
                    <input type="number" name="snmp_port" value="<?= $v('snmp_port',161) ?>" min="1" max="65535"
                        style="width:100%;padding:10px 14px;border:1px solid #d1d5db;border-radius:10px;font-size:0.9rem;box-sizing:border-box;">
                </div>
                <div>
                    <label style="display:block;font-size:0.82rem;font-weight:600;color:#374151;margin-bottom:6px;">Intervalo de polling (s)</label>
                    <input type="number" name="poll_interval" value="<?= $v('poll_interval',60) ?>" min="30" max="3600"
                        style="width:100%;padding:10px 14px;border:1px solid #d1d5db;border-radius:10px;font-size:0.9rem;box-sizing:border-box;">
                </div>
                <div style="display:flex;align-items:center;gap:10px;margin-top:20px;">
                    <label style="display:flex;align-items:center;gap:8px;cursor:pointer;">
                        <input type="checkbox" name="active" value="1" <?= ($panel['active'] ?? 1) ? 'checked' : '' ?>
                            style="width:16px;height:16px;accent-color:#1d4ed8;">
                        <span style="font-size:0.88rem;font-weight:600;color:#374151;">Ativo</span>
                    </label>
                </div>
            </div>
        </div>

        <!-- Alertas -->
        <div style="background:#fff;border-radius:20px;border:1px solid #e2e8f0;padding:28px;margin-bottom:16px;">
            <h3 style="margin:0 0 20px;font-size:1rem;font-weight:700;color:#0f172a;">Configuração de Alertas</h3>

            <!-- Interface -->
            <div style="background:#f8fafc;border-radius:12px;padding:16px 20px;margin-bottom:16px;">
                <p style="margin:0 0 12px;font-size:0.85rem;font-weight:700;color:#475569;text-transform:uppercase;letter-spacing:0.05em;">Interface Ethernet</p>
                <div style="display:flex;gap:24px;flex-wrap:wrap;">
                    <label style="display:flex;align-items:center;gap:8px;cursor:pointer;">
                        <input type="checkbox" name="alert_iface_speed" value="1" <?= ($panel['alert_iface_speed'] ?? 1) ? 'checked' : '' ?>
                            style="width:16px;height:16px;accent-color:#1d4ed8;">
                        <span style="font-size:0.88rem;color:#374151;">Alertar degradação de velocidade (1G→100M, 1G→10M)</span>
                    </label>
                    <label style="display:flex;align-items:center;gap:8px;cursor:pointer;">
                        <input type="checkbox" name="alert_iface_down" value="1" <?= ($panel['alert_iface_down'] ?? 1) ? 'checked' : '' ?>
                            style="width:16px;height:16px;accent-color:#1d4ed8;">
                        <span style="font-size:0.88rem;color:#374151;">Alertar quando painel ficar offline</span>
                    </label>
                </div>
            </div>

            <!-- Clientes -->
            <div style="background:#f8fafc;border-radius:12px;padding:16px 20px;">
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
                    <p style="margin:0;font-size:0.85rem;font-weight:700;color:#475569;text-transform:uppercase;letter-spacing:0.05em;">Queda de Clientes</p>
                    <label style="display:flex;align-items:center;gap:8px;cursor:pointer;">
                        <input type="checkbox" name="alert_clients" value="1" id="alertClientsChk" <?= ($panel['alert_clients'] ?? 1) ? 'checked' : '' ?>
                            style="width:16px;height:16px;accent-color:#1d4ed8;">
                        <span style="font-size:0.85rem;font-weight:600;color:#374151;">Ativo</span>
                    </label>
                </div>
                <div id="clientAlertFields" style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;">
                    <div>
                        <label style="display:block;font-size:0.82rem;font-weight:600;color:#374151;margin-bottom:6px;">Modo</label>
                        <select name="alert_client_mode" id="clientModeSelect"
                            style="width:100%;padding:10px 14px;border:1px solid #d1d5db;border-radius:10px;font-size:0.9rem;">
                            <option value="absolute" <?= ($panel['alert_client_mode'] ?? 'absolute') === 'absolute' ? 'selected' : '' ?>>Absoluto (N clientes)</option>
                            <option value="percent"  <?= ($panel['alert_client_mode'] ?? '') === 'percent'  ? 'selected' : '' ?>>Percentual (%)</option>
                        </select>
                    </div>
                    <div>
                        <label style="display:block;font-size:0.82rem;font-weight:600;color:#374151;margin-bottom:6px;" id="thresholdLabel">
                            Limiar
                        </label>
                        <div style="position:relative;">
                            <input type="number" name="alert_client_threshold" id="thresholdInput"
                                value="<?= $v('alert_client_threshold', 3) ?>" min="1" max="999"
                                style="width:100%;padding:10px 40px 10px 14px;border:1px solid #d1d5db;border-radius:10px;font-size:0.9rem;box-sizing:border-box;">
                            <span id="thresholdUnit" style="position:absolute;right:12px;top:50%;transform:translateY(-50%);font-size:0.8rem;color:#94a3b8;font-weight:600;">clientes</span>
                        </div>
                    </div>
                    <div>
                        <label style="display:block;font-size:0.82rem;font-weight:600;color:#374151;margin-bottom:6px;">Janela de confirmação (min)</label>
                        <input type="number" name="alert_client_window"
                            value="<?= $v('alert_client_window', 2) ?>" min="1" max="60"
                            style="width:100%;padding:10px 14px;border:1px solid #d1d5db;border-radius:10px;font-size:0.9rem;box-sizing:border-box;">
                    </div>
                </div>
                <p style="margin:10px 0 0;font-size:0.8rem;color:#94a3b8;">
                    Exemplo: modo <strong>Absoluto</strong> com limiar <strong>3</strong> → alerta se 3 ou mais clientes caírem ao mesmo tempo e permanecerem ausentes por 2 min.
                </p>
            </div>

            <!-- WhatsApp -->
            <div style="margin-top:16px;background:#f0fdf4;border:1px solid #bbf7d0;border-radius:12px;padding:16px 20px;">
                <p style="margin:0 0 10px;font-size:0.85rem;font-weight:700;color:#166534;text-transform:uppercase;letter-spacing:0.05em;">Notificação WhatsApp</p>
                <input type="text" name="alert_phone" value="<?= $v('alert_phone') ?>"
                    style="width:100%;padding:10px 14px;border:1px solid #86efac;border-radius:10px;font-size:0.9rem;box-sizing:border-box;background:#fff;"
                    placeholder="(93) 99999-9999 ou 5593999999999">
                <p style="margin:8px 0 0;font-size:0.78rem;color:#16a34a;">Deixe em branco para não notificar por WhatsApp.</p>
            </div>
        </div>

        <!-- Botões -->
        <div style="display:flex;gap:12px;justify-content:flex-end;">
            <a href="<?= UBNT_URL ?>?page=ubnt_panels"
                style="padding:12px 24px;border-radius:12px;border:1px solid #e2e8f0;background:#fff;color:#475569;text-decoration:none;font-weight:600;font-size:0.92rem;">
                Cancelar
            </a>
            <button type="submit"
                style="padding:12px 28px;border-radius:12px;background:#1d4ed8;color:#fff;border:none;font-weight:700;font-size:0.95rem;cursor:pointer;">
                <?= $editId ? 'Salvar Alterações' : 'Criar Painel' ?>
            </button>
        </div>
    </form>
</div>

<script>
const modeSelect = document.getElementById('clientModeSelect');
const unitSpan   = document.getElementById('thresholdUnit');
function updateUnit() {
    unitSpan.textContent = modeSelect.value === 'percent' ? '%' : 'clientes';
}
modeSelect.addEventListener('change', updateUnit);
updateUnit();
</script>

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