<?php
// #43 Importação de IPs em massa via CSV
require_once __DIR__ . '/../includes/header.php';
$pdo = db();
$plan = get_user_plan($user['id']);
$results = [];
$error = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_check($_POST['csrf_token'] ?? null)) {
        $error = 'CSRF inválido.';
    } elseif (empty($_FILES['csv_file']['tmp_name'])) {
        $error = 'Nenhum arquivo enviado.';
    } else {
        $handle = fopen($_FILES['csv_file']['tmp_name'], 'r');
        if (!$handle) {
            $error = 'Não foi possível ler o arquivo.';
        } else {
            $current = count_user_ips($user['id']);
            $max = (int)$plan['max_ips'];
            $minInterval = (int)$plan['min_interval_seconds'];
            $row = 0;

            // Detecta se a primeira linha é cabeçalho
            $firstLine = fgetcsv($handle, 500, ',') ?: fgetcsv($handle, 500, ';');
            $hasCsv = $firstLine !== false;
            $isHeader = $hasCsv && (strtolower(trim($firstLine[0] ?? '')) === 'label' || strtolower(trim($firstLine[0] ?? '')) === 'nome');
            if (!$isHeader && $hasCsv) {
                // Reprocessa primeira linha como dado
                fclose($handle);
                $handle = fopen($_FILES['csv_file']['tmp_name'], 'r');
            }

            while (($cols = fgetcsv($handle, 500, ',')) !== false) {
                if (count($cols) < 2) {
                    $cols = fgetcsv($handle, 500, ';') ?: $cols;
                }
                $row++;
                $label    = trim($cols[0] ?? '');
                $host     = trim($cols[1] ?? '');
                $interval = (int)($cols[2] ?? $minInterval);

                if (!$label || !$host) {
                    $results[] = ['row' => $row, 'ok' => false, 'msg' => "Linha {$row}: label ou host vazio."];
                    continue;
                }
                if ($current >= $max) {
                    $results[] = ['row' => $row, 'ok' => false, 'msg' => "Linha {$row}: limite de {$max} IPs atingido."];
                    continue;
                }
                if ($interval < $minInterval) $interval = $minInterval;
                $hostErr = null;
                if (!validate_monitor_host($host, $hostErr)) {
                    $results[] = ['row' => $row, 'ok' => false, 'msg' => "Linha {$row}: {$hostErr}"];
                    continue;
                }
                try {
                    $pdo->prepare("INSERT INTO monitored_ips (user_id, label, host, interval_seconds) VALUES (?, ?, ?, ?)")
                        ->execute([$user['id'], $label, $host, $interval]);
                    $current++;
                    $results[] = ['row' => $row, 'ok' => true, 'msg' => "Linha {$row}: {$label} ({$host}) adicionado."];
                } catch (Throwable $e) {
                    $results[] = ['row' => $row, 'ok' => false, 'msg' => "Linha {$row}: erro ao salvar — " . $e->getMessage()];
                }
            }
            fclose($handle);
        }
    }
}
?>

<div style="max-width:680px; margin:0 auto;">
    <div style="background:linear-gradient(135deg,#1e293b,#0f172a); border-radius:20px; padding:28px 32px; color:#f1f5f9; margin-bottom:24px;">
        <h1 style="font-size:1.5rem; font-weight:800; margin:0;">Importar IPs em Massa</h1>
        <p style="color:#94a3b8; margin-top:4px; font-size:0.9rem;">Envie um arquivo CSV para cadastrar vários hosts de uma vez.</p>
    </div>

    <?php if ($error): ?>
        <div style="background:rgba(239,68,68,.1); color:#dc2626; border:1px solid #fca5a5; padding:12px 16px; border-radius:10px; margin-bottom:20px; font-weight:600;"><?= h($error) ?></div>
    <?php endif; ?>

    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:16px; padding:28px; margin-bottom:24px;">
        <h3 style="margin:0 0 12px; font-size:1rem; font-weight:800; color:#0f172a;">Formato esperado</h3>
        <p style="font-size:0.9rem; color:#64748b; margin-bottom:12px;">Arquivo <strong>.csv</strong> com separador vírgula ou ponto-e-vírgula. Primeira linha pode ser cabeçalho (opcional).</p>
        <pre style="background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; padding:14px; font-size:0.88rem; color:#334155; overflow-x:auto;">label,host,interval_seconds
Servidor Web,192.168.1.1,60
Google DNS,8.8.8.8,120
API Externa,api.exemplo.com,300</pre>
        <p style="font-size:0.82rem; color:#94a3b8; margin-top:8px;">A coluna <code>interval_seconds</code> é opcional (padrão: <?= (int)$plan['min_interval_seconds'] ?>s mínimo do seu plano).</p>
    </div>

    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:16px; padding:28px; margin-bottom:24px;">
        <form method="post" enctype="multipart/form-data" style="display:flex; flex-direction:column; gap:16px;">
            <input type="hidden" name="csrf_token" value="<?= h(csrf_token()) ?>">
            <div>
                <label style="display:block; font-weight:600; font-size:0.9rem; color:#475569; margin-bottom:8px;">Arquivo CSV</label>
                <input type="file" name="csv_file" accept=".csv,text/csv" required
                    style="width:100%; padding:10px; border:1px solid #cbd5e1; border-radius:10px; font-size:0.95rem; background:#f8fafc; cursor:pointer;">
            </div>
            <button type="submit" style="background:#3b82f6; color:#fff; border:none; padding:13px; border-radius:10px; font-weight:700; font-size:1rem; cursor:pointer; align-self:flex-start; padding-left:32px; padding-right:32px;">
                Importar
            </button>
        </form>
    </div>

    <?php if (!empty($results)): ?>
    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:16px; padding:28px;">
        <h3 style="margin:0 0 16px; font-size:1rem; font-weight:800; color:#0f172a;">Resultado da importação</h3>
        <?php
        $ok    = count(array_filter($results, fn($r) => $r['ok']));
        $fail  = count($results) - $ok;
        ?>
        <p style="font-size:0.9rem; color:#64748b; margin-bottom:16px;">
            <strong style="color:#16a34a;"><?= $ok ?> adicionado(s)</strong>
            <?php if ($fail): ?> · <strong style="color:#dc2626;"><?= $fail ?> com erro</strong><?php endif; ?>
        </p>
        <div style="display:flex; flex-direction:column; gap:6px; max-height:300px; overflow-y:auto;">
        <?php foreach ($results as $r): ?>
            <div style="padding:8px 12px; border-radius:8px; font-size:0.88rem; background:<?= $r['ok'] ? '#f0fdf4' : '#fef2f2' ?>; color:<?= $r['ok'] ? '#166534' : '#b91c1c' ?>; border:1px solid <?= $r['ok'] ? '#bbf7d0' : '#fecaca' ?>;">
                <?= h($r['msg']) ?>
            </div>
        <?php endforeach; ?>
        </div>
        <?php if ($ok > 0): ?>
        <div style="margin-top:16px;">
            <a href="index.php?page=user_ips" style="display:inline-block; background:#22c55e; color:#fff; padding:11px 24px; border-radius:10px; font-weight:700; text-decoration:none;">Ver meus IPs</a>
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <div style="margin-top:16px; text-align:center;">
        <a href="index.php?page=user_ips" style="font-size:0.85rem; color:#64748b;">← Voltar para meus IPs</a>
    </div>
</div>

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