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

$pdo = db();
$stmt = $pdo->prepare("SELECT * FROM monitored_ips WHERE user_id = ? ORDER BY created_at DESC");
$stmt->execute([$user['id']]);
$ips = $stmt->fetchAll();

$totalIps = count($ips);
$onlineCount = 0;
$offlineCount = 0;
foreach ($ips as $ip) {
    if ($ip['last_status'] === 'online') $onlineCount++;
    elseif ($ip['last_status'] === 'offline') $offlineCount++;
}
$unknownCount = $totalIps - $onlineCount - $offlineCount;
?>

<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;">
    
    <!-- Header -->
    <div style="padding:24px 32px; border-bottom:1px solid #e2e8f0; background:#f8fafc; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:16px;">
        <div>
            <h2 style="margin:0; font-size:1.6rem; color:#0f172a; font-weight:800;">Meus IPs Monitorados</h2>
            <p style="margin:4px 0 0; color:#64748b; font-size:0.9rem;"><?php echo $totalIps; ?> instância<?php echo $totalIps !== 1 ? 's' : ''; ?> cadastrada<?php echo $totalIps !== 1 ? 's' : ''; ?></p>
        </div>
        <div style="display:flex; gap:8px; flex-wrap:wrap;">
            <a href="index.php?page=import_ips" style="text-decoration:none;">
                <button type="button" style="display:inline-flex; align-items:center; gap:8px; padding:12px 20px; font-size:0.95rem; border-radius:12px; font-weight:700; cursor:pointer; background:#f1f5f9; color:#334155; border:1px solid #cbd5e1;">
                    ↑ Importar CSV
                </button>
            </a>
            <a href="index.php?page=user_ip_form" style="text-decoration:none;">
                <button type="button" style="display:inline-flex; align-items:center; gap:8px; padding:12px 24px; font-size:1rem; border-radius:12px; font-weight:700; cursor:pointer;">
                    <svg width="18" height="18" 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>
                    Novo IP
                </button>
            </a>
        </div>
    </div>

    <div style="padding:24px 32px;">

        <!-- Counters -->
        <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap:12px; margin-bottom:24px;">
            <div style="background:#f0fdf4; border:1px solid #bbf7d0; border-radius:12px; padding:14px 18px; text-align:center;">
                <div style="font-size:1.6rem; font-weight:800; color:#16a34a;"><?php echo $onlineCount; ?></div>
                <div style="font-size:0.8rem; font-weight:600; color:#166534; text-transform:uppercase; letter-spacing:0.5px;">Online</div>
            </div>
            <div style="background:#fef2f2; border:1px solid #fecaca; border-radius:12px; padding:14px 18px; text-align:center;">
                <div style="font-size:1.6rem; font-weight:800; color:#dc2626;"><?php echo $offlineCount; ?></div>
                <div style="font-size:0.8rem; font-weight:600; color:#991b1b; text-transform:uppercase; letter-spacing:0.5px;">Offline</div>
            </div>
            <div style="background:#f8fafc; border:1px solid #e2e8f0; border-radius:12px; padding:14px 18px; text-align:center;">
                <div style="font-size:1.6rem; font-weight:800; color:#64748b;"><?php echo $totalIps; ?></div>
                <div style="font-size:0.8rem; font-weight:600; color:#475569; text-transform:uppercase; letter-spacing:0.5px;">Total</div>
            </div>
        </div>

        <!-- Buscador Live -->
        <div style="position:relative; margin-bottom:20px;">
            <svg width="20" height="20" fill="none" stroke="#94a3b8" viewBox="0 0 24 24" style="position:absolute; left:14px; top:50%; transform:translateY(-50%); pointer-events:none;">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
            </svg>
            <input type="text" id="ipSearchBox" placeholder="Buscar por nome, host ou status..." 
                   style="width:100%; padding:14px 16px 14px 44px; border:1px solid #cbd5e1; border-radius:12px; font-size:1rem; font-family:inherit; outline:none; transition:border-color 0.2s, box-shadow 0.2s; background:#fff;"
                   onfocus="this.style.borderColor='#3b82f6'; this.style.boxShadow='0 0 0 3px rgba(59,130,246,0.1)';"
                   onblur="this.style.borderColor='#cbd5e1'; this.style.boxShadow='none';">
            <span id="ipSearchCount" style="position:absolute; right:14px; top:50%; transform:translateY(-50%); font-size:0.8rem; color:#94a3b8; font-weight:600; pointer-events:none;"></span>
        </div>

        <!-- Mensagem quando sem resultados -->
        <div id="ipNoResults" style="display:none; text-align:center; padding:40px 0; color:#94a3b8;">
            <div style="font-size:2rem; margin-bottom:8px;">🔍</div>
            <p style="font-size:1rem; font-weight:600;">Nenhum IP encontrado para sua busca.</p>
            <p style="font-size:0.85rem;">Tente buscar por outro nome ou endereço.</p>
        </div>

        <!-- Ações em massa -->
        <form method="post" action="index.php?page=user_ips" id="bulkForm" style="margin-bottom:12px; display:flex; align-items:center; gap:10px; flex-wrap:wrap;">
            <input type="hidden" name="csrf_token" value="<?php echo h(csrf_token()); ?>">
            <input type="hidden" name="action" id="bulkAction" value="">
            <span style="font-size:0.85rem; color:#64748b; font-weight:600;">Selecionados:</span>
            <button type="button" onclick="setBulk('bulk_pause')" style="padding:7px 14px; border-radius:8px; border:1px solid #cbd5e1; background:#fff; color:#475569; font-weight:600; font-size:0.85rem; cursor:pointer;">⏸ Pausar</button>
            <button type="button" onclick="setBulk('bulk_resume')" style="padding:7px 14px; border-radius:8px; border:1px solid #cbd5e1; background:#fff; color:#16a34a; font-weight:600; font-size:0.85rem; cursor:pointer;">▶ Retomar</button>
            <button type="button" onclick="setBulk('bulk_delete')" style="padding:7px 14px; border-radius:8px; border:1px solid #fca5a5; background:#fff; color:#ef4444; font-weight:600; font-size:0.85rem; cursor:pointer;" onclick="return confirm('Deletar IPs selecionados?')">🗑 Deletar</button>
            <div id="bulkCheckboxes" style="display:none;"></div>
        </form>

        <!-- Tabela -->
        <div style="overflow-x:auto; border-radius:12px; border:1px solid #e2e8f0;" id="ipTableWrapper">
            <table style="width:100%; border-collapse:collapse; font-size:0.92rem;" id="ipTable">
                <thead>
                    <tr style="background:#f8fafc;">
                        <th style="padding:14px 16px; text-align:center; border-bottom:2px solid #e2e8f0; width:40px;"><input type="checkbox" id="selectAll" title="Selecionar todos" style="width:16px;height:16px;accent-color:#3b82f6;cursor:pointer;"></th>
                        <th style="padding:14px 16px; text-align:left; font-weight:800; color:#0f172a; font-size:0.82rem; text-transform:uppercase; letter-spacing:0.5px; border-bottom:2px solid #e2e8f0;">Nome</th>
                        <th style="padding:14px 16px; text-align:left; font-weight:800; color:#ea580c; font-size:0.82rem; text-transform:uppercase; letter-spacing:0.5px; border-bottom:2px solid #fed7aa;">Host / IP</th>
                        <th style="padding:14px 16px; text-align:center; font-weight:800; color:#4f46e5; font-size:0.82rem; text-transform:uppercase; letter-spacing:0.5px; border-bottom:2px solid #c7d2fe;">Intervalo</th>
                        <th style="padding:14px 16px; text-align:center; font-weight:800; color:#0f172a; font-size:0.82rem; text-transform:uppercase; letter-spacing:0.5px; border-bottom:2px solid #e2e8f0;">Status</th>
                        <th style="padding:14px 16px; text-align:center; font-weight:800; color:#16a34a; font-size:0.82rem; text-transform:uppercase; letter-spacing:0.5px; border-bottom:2px solid #bbf7d0;">Ping (ms)</th>
                        <th style="padding:14px 16px; text-align:center; font-weight:800; color:#7c3aed; font-size:0.82rem; text-transform:uppercase; letter-spacing:0.5px; border-bottom:2px solid #ddd6fe;">Último Check</th>
                        <th style="padding:14px 16px; text-align:center; font-weight:800; color:#475569; font-size:0.82rem; text-transform:uppercase; letter-spacing:0.5px; border-bottom:2px solid #e2e8f0;">Ações</th>
                    </tr>
                </thead>
                <tbody id="ipTableBody">
                <?php foreach ($ips as $ip):
                    $statusText = $ip['last_status'] ?: 'desconhecido';
                    $searchable = strtolower($ip['label'] . ' ' . $ip['host'] . ' ' . $statusText);
                    $latency = $ip['last_latency_ms'] !== null ? (int)$ip['last_latency_ms'] : null;

                    // Latência por faixa
                    if ($latency === null) {
                        $latBg = '#f1f5f9'; $latColor = '#94a3b8'; $latBorder = '#e2e8f0';
                        $latHtml = '—';
                    } elseif ($latency > 200) {
                        $latBg = '#fef2f2'; $latColor = '#dc2626'; $latBorder = '#fca5a5';
                        $latHtml = '<strong>' . $latency . '</strong> <small style="font-weight:400;">ms</small>';
                    } elseif ($latency > 100) {
                        $latBg = '#fffbeb'; $latColor = '#ca8a04'; $latBorder = '#fde68a';
                        $latHtml = '<strong>' . $latency . '</strong> <small style="font-weight:400;">ms</small>';
                    } else {
                        $latBg = '#f0fdf4'; $latColor = '#16a34a'; $latBorder = '#bbf7d0';
                        $latHtml = '<strong>' . $latency . '</strong> <small style="font-weight:400;">ms</small>';
                    }

                    // Intervalo
                    $interval = (int)$ip['interval_seconds'];
                    $intervalLabel = $interval >= 60 ? round($interval / 60) . ' min' : $interval . 's';
                ?>
                    <tr class="ip-row" data-search="<?php echo h($searchable); ?>" style="border-bottom:1px solid #f1f5f9; transition:background 0.15s; cursor:pointer;" onmouseover="this.style.background='#f0f9ff'" onmouseout="this.style.background='transparent'" onclick="window.location='index.php?page=user_ip_detail&id=<?php echo (int)$ip['id']; ?>'"  >

                        <!-- Checkbox -->
                        <td style="padding:14px 16px; text-align:center;" onclick="event.stopPropagation()">
                            <input type="checkbox" class="ip-check" value="<?php echo (int)$ip['id']; ?>" style="width:16px;height:16px;accent-color:#3b82f6;cursor:pointer;">
                        </td>

                        <!-- Nome -->
                        <td style="padding:14px 16px; font-weight:800; font-size:0.95rem; color:#0f172a;"><?php echo h($ip['label']); ?></td>

                        <!-- Host laranja -->
                        <td style="padding:14px 16px;">
                            <code style="font-size:1.05rem; font-weight:700; color:#ea580c; background:#fff7ed; padding:6px 12px; border-radius:8px; border:1.5px solid #fed7aa; letter-spacing:0.03em;"><?php echo h($ip['host']); ?></code>
                        </td>

                        <!-- Intervalo azul índigo -->
                        <td style="padding:14px 16px; text-align:center;">
                            <span style="display:inline-block; background:#eef2ff; color:#4f46e5; border:1px solid #c7d2fe; border-radius:99px; padding:6px 16px; font-size:0.95rem; font-weight:700; letter-spacing:0.3px;">
                                ⏱ <?php echo $intervalLabel; ?>
                            </span>
                        </td>

                        <!-- Status -->
                        <td style="padding:14px 16px; text-align:center;">
                            <?php if ($ip['last_status'] === 'online'): ?>
                                <span style="display:inline-flex; align-items:center; gap:6px; background:#dcfce7; color:#166534; padding:7px 16px; border-radius:20px; font-weight:700; font-size:0.95rem; border:1px solid #bbf7d0;">
                                    <span style="width:9px; height:9px; border-radius:50%; background:#22c55e; display:inline-block;"></span> Online
                                </span>
                            <?php elseif ($ip['last_status'] === 'offline'): ?>
                                <span style="display:inline-flex; align-items:center; gap:6px; background:#fee2e2; color:#991b1b; padding:7px 16px; border-radius:20px; font-weight:700; font-size:0.95rem; border:1px solid #fecaca;">
                                    <span style="width:9px; height:9px; border-radius:50%; background:#ef4444; display:inline-block;"></span> Offline
                                </span>
                            <?php else: ?>
                                <span style="display:inline-flex; align-items:center; gap:6px; background:#f1f5f9; color:#64748b; padding:7px 16px; border-radius:20px; font-weight:700; font-size:0.95rem; border:1px solid #e2e8f0;">
                                    <span style="width:9px; height:9px; border-radius:50%; background:#94a3b8; display:inline-block;"></span> ???
                                </span>
                            <?php endif; ?>
                        </td>

                        <!-- Ping com badge colorido por faixa -->
                        <td style="padding:14px 16px; text-align:center;">
                            <span style="display:inline-block; background:<?php echo $latBg; ?>; color:<?php echo $latColor; ?>; border:1px solid <?php echo $latBorder; ?>; border-radius:99px; padding:6px 16px; font-size:0.95rem;">
                                <?php echo $latHtml; ?>
                            </span>
                        </td>

                        <!-- Último Check roxo -->
                        <td style="padding:14px 16px; text-align:center;">
                            <?php if ($ip['last_check_at']): ?>
                                <span style="display:inline-block; background:#faf5ff; color:#7c3aed; border:1px solid #ddd6fe; border-radius:8px; padding:6px 12px; font-size:0.95rem; font-weight:600; font-family:monospace;">
                                    <?php echo format_datetime_tz($ip['last_check_at'], $user['timezone'] ?? null, 'd/m H:i:s'); ?>
                                </span>
                            <?php else: ?>
                                <span style="color:#cbd5e1;">—</span>
                            <?php endif; ?>
                        </td>
                        <td style="padding:14px 16px; text-align:center; white-space:nowrap;" onclick="event.stopPropagation()">
                            <div style="display:inline-flex; align-items:center; gap:6px;">

                                <!-- Editar -->
                                <a href="index.php?page=user_ip_form&id=<?php echo $ip['id']; ?>"
                                   style="display:inline-flex; flex-direction:column; align-items:center; gap:4px; padding:8px 12px; border-radius:10px; color:#3b82f6; background:#eff6ff; text-decoration:none; border:1px solid transparent; transition:all 0.2s;"
                                   onmouseover="this.style.borderColor='#93c5fd'; this.style.background='#dbeafe'"
                                   onmouseout="this.style.borderColor='transparent'; this.style.background='#eff6ff'">
                                    <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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
                                    <span style="font-size:0.7rem; font-weight:700; text-transform:uppercase; letter-spacing:0.4px;">Editar</span>
                                </a>

                                <!-- Ver Logs -->
                                <a href="index.php?page=user_logs&id=<?php echo $ip['id']; ?>"
                                   style="display:inline-flex; flex-direction:column; align-items:center; gap:4px; padding:8px 12px; border-radius:10px; color:#8b5cf6; background:#f5f3ff; text-decoration:none; border:1px solid transparent; transition:all 0.2s;"
                                   onmouseover="this.style.borderColor='#c4b5fd'; this.style.background='#ede9fe'"
                                   onmouseout="this.style.borderColor='transparent'; this.style.background='#f5f3ff'">
                                    <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="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
                                    <span style="font-size:0.7rem; font-weight:700; text-transform:uppercase; letter-spacing:0.4px;">Ver Logs</span>
                                </a>

                                <!-- Remover -->
                                <form method="post" action="index.php?page=user_ips" style="display:inline;" onsubmit="return confirm('Tem certeza que deseja remover este IP?');">
                                    <input type="hidden" name="csrf_token" value="<?php echo h(csrf_token()); ?>">
                                    <input type="hidden" name="action" value="delete_ip">
                                    <input type="hidden" name="id" value="<?php echo (int)$ip['id']; ?>">
                                    <button type="submit"
                                            style="display:inline-flex; flex-direction:column; align-items:center; gap:4px; padding:8px 12px; border-radius:10px; color:#ef4444; background:#fef2f2; border:1px solid transparent; cursor:pointer; transition:all 0.2s;"
                                            onmouseover="this.style.borderColor='#fca5a5'; this.style.background='#fee2e2'"
                                            onmouseout="this.style.borderColor='transparent'; this.style.background='#fef2f2'">
                                        <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="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>
                                        <span style="font-size:0.7rem; font-weight:700; text-transform:uppercase; letter-spacing:0.4px;">Remover</span>
                                    </button>
                                </form>

                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <?php if (empty($ips)): ?>
            <div style="text-align:center; padding:48px 0; color:#94a3b8;">
                <div style="font-size:3rem; margin-bottom:12px;">📡</div>
                <p style="font-size:1.1rem; font-weight:600; color:#64748b;">Nenhum IP cadastrado ainda.</p>
                <p style="font-size:0.9rem;">Clique em <strong>"Novo IP"</strong> para começar a monitorar.</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
// Bulk operations
function setBulk(action) {
    const checks = document.querySelectorAll('.ip-check:checked');
    if (checks.length === 0) { alert('Selecione ao menos um IP.'); return; }
    if (action === 'bulk_delete' && !confirm('Deletar ' + checks.length + ' IP(s) selecionado(s)?')) return;
    document.getElementById('bulkAction').value = action;
    const container = document.getElementById('bulkCheckboxes');
    container.innerHTML = '';
    checks.forEach(c => {
        const inp = document.createElement('input');
        inp.type = 'hidden'; inp.name = 'ids[]'; inp.value = c.value;
        container.appendChild(inp);
    });
    document.getElementById('bulkForm').submit();
}
document.getElementById('selectAll').addEventListener('change', function() {
    document.querySelectorAll('.ip-check').forEach(c => c.checked = this.checked);
});
</script>

<script>
(function() {
    const searchBox = document.getElementById('ipSearchBox');
    const rows = document.querySelectorAll('.ip-row');
    const noResults = document.getElementById('ipNoResults');
    const tableWrapper = document.getElementById('ipTableWrapper');
    const countEl = document.getElementById('ipSearchCount');
    const total = rows.length;

    if (!searchBox || total === 0) return;

    searchBox.addEventListener('input', function() {
        const query = this.value.trim().toLowerCase();
        let visible = 0;

        rows.forEach(function(row) {
            const data = row.getAttribute('data-search') || '';
            if (query === '' || data.includes(query)) {
                row.style.display = '';
                visible++;
            } else {
                row.style.display = 'none';
            }
        });

        if (query === '') {
            countEl.textContent = '';
            noResults.style.display = 'none';
            tableWrapper.style.display = '';
        } else {
            countEl.textContent = visible + ' de ' + total;
            if (visible === 0) {
                noResults.style.display = 'block';
                tableWrapper.style.display = 'none';
            } else {
                noResults.style.display = 'none';
                tableWrapper.style.display = '';
            }
        }
    });
})();
</script>

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