<?php
require_once __DIR__ . '/../includes/header.php';
$pdo = db();

// ── CRUD de Tags ──────────────────────────────────────────────────────────────
$success = $error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_check($_POST['csrf_token'] ?? null)) {
        $error = 'Token inválido.';
    } else {
        $action = $_POST['action'] ?? '';
        if ($action === 'create') {
            $name  = trim($_POST['name'] ?? '');
            $color = preg_match('/^#[0-9a-fA-F]{6}$/', $_POST['color'] ?? '') ? $_POST['color'] : '#6366f1';
            if (!$name || mb_strlen($name) > 50) {
                $error = 'Nome inválido (máx. 50 caracteres).';
            } else {
                try {
                    $pdo->prepare("INSERT INTO tags (user_id, name, color) VALUES (?, ?, ?)")
                        ->execute([$user['id'], $name, $color]);
                    $success = "Tag \"{$name}\" criada!";
                } catch (PDOException $e) {
                    $error = 'Essa tag já existe.';
                }
            }
        } elseif ($action === 'delete') {
            $tagId = (int)($_POST['tag_id'] ?? 0);
            if ($tagId) {
                $pdo->prepare("DELETE FROM tags WHERE id = ? AND user_id = ?")->execute([$tagId, $user['id']]);
                $success = 'Tag removida.';
            }
        } elseif ($action === 'update_color') {
            $tagId = (int)($_POST['tag_id'] ?? 0);
            $color = preg_match('/^#[0-9a-fA-F]{6}$/', $_POST['color'] ?? '') ? $_POST['color'] : '#6366f1';
            if ($tagId) {
                $pdo->prepare("UPDATE tags SET color = ? WHERE id = ? AND user_id = ?")->execute([$color, $tagId, $user['id']]);
                $success = 'Cor atualizada.';
            }
        }
        redirect('index.php?page=user_tags' . ($success ? '&ok=1' : ''));
    }
}

if (isset($_GET['ok'])) $success = 'Operação realizada com sucesso!';

$tags = $pdo->prepare("
    SELECT t.*, COUNT(it.monitored_ip_id) AS ip_count
    FROM tags t
    LEFT JOIN ip_tags it ON it.tag_id = t.id
    WHERE t.user_id = ?
    GROUP BY t.id
    ORDER BY t.name ASC
");
$tags->execute([$user['id']]);
$tags = $tags->fetchAll();
?>

<div class="card">
    <div class="card-head">
        <div>
            <h2>🏷️ Gerenciar Tags</h2>
            <p>Crie tags coloridas para organizar e filtrar seus hosts monitorados.</p>
        </div>
    </div>

    <?php if ($success): ?><div class="alert alert-success"><?php echo h($success); ?></div><?php endif; ?>
    <?php if ($error): ?><div class="alert alert-error"><?php echo h($error); ?></div><?php endif; ?>

    <!-- Formulário de criação -->
    <form method="POST" action="" style="display:flex;gap:12px;align-items:flex-end;flex-wrap:wrap;margin-bottom:24px;">
        <input type="hidden" name="csrf_token" value="<?php echo csrf_token(); ?>">
        <input type="hidden" name="action" value="create">
        <div style="flex:1;min-width:200px;">
            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px;">Nome da Tag</label>
            <input type="text" name="name" maxlength="50" placeholder="Ex: servidores, clientes, links..." required
                   style="width:100%;padding:9px 12px;border:1px solid var(--border);border-radius:8px;background:var(--bg-card);color:var(--text-primary);font-size:14px;">
        </div>
        <div>
            <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px;">Cor</label>
            <input type="color" name="color" value="#6366f1"
                   style="width:48px;height:38px;border:1px solid var(--border);border-radius:8px;cursor:pointer;padding:2px;">
        </div>
        <button type="submit" class="primary-button">+ Criar Tag</button>
    </form>

    <!-- Lista de tags -->
    <?php if (empty($tags)): ?>
        <div style="text-align:center;padding:40px;color:var(--text-secondary);">
            <div style="font-size:48px;margin-bottom:12px;">🏷️</div>
            <p>Nenhuma tag criada ainda.</p>
            <p style="font-size:13px;">Crie tags para organizar seus hosts monitorados por categoria.</p>
        </div>
    <?php else: ?>
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:12px;">
            <?php foreach ($tags as $tag): ?>
            <div class="card" style="padding:16px;margin:0;border-left:4px solid <?php echo h($tag['color']); ?>;">
                <div style="display:flex;align-items:center;gap:10px;margin-bottom:8px;">
                    <span style="display:inline-block;width:14px;height:14px;border-radius:50%;background:<?php echo h($tag['color']); ?>;flex-shrink:0;"></span>
                    <strong style="font-size:15px;flex:1;"><?php echo h($tag['name']); ?></strong>
                    <span style="font-size:12px;color:var(--text-secondary);"><?php echo $tag['ip_count']; ?> host<?php echo $tag['ip_count'] != 1 ? 's' : ''; ?></span>
                </div>

                <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
                    <!-- Alterar cor -->
                    <form method="POST" style="display:flex;gap:4px;align-items:center;">
                        <input type="hidden" name="csrf_token" value="<?php echo csrf_token(); ?>">
                        <input type="hidden" name="action" value="update_color">
                        <input type="hidden" name="tag_id" value="<?php echo $tag['id']; ?>">
                        <input type="color" name="color" value="<?php echo h($tag['color']); ?>"
                               style="width:30px;height:28px;border:1px solid var(--border);border-radius:6px;cursor:pointer;padding:1px;">
                        <button type="submit" class="ghost-button" style="padding:4px 10px;font-size:12px;">Salvar cor</button>
                    </form>

                    <!-- Ver hosts desta tag -->
                    <a href="<?php echo BASE_URL; ?>index.php?page=user_ips&tag=<?php echo urlencode($tag['name']); ?>"
                       class="ghost-button" style="padding:4px 10px;font-size:12px;">Ver hosts</a>

                    <!-- Deletar -->
                    <form method="POST" onsubmit="return confirm('Remover tag \'<?php echo h(addslashes($tag['name'])); ?>\'?');">
                        <input type="hidden" name="csrf_token" value="<?php echo csrf_token(); ?>">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="tag_id" value="<?php echo $tag['id']; ?>">
                        <button type="submit" class="ghost-button" style="padding:4px 10px;font-size:12px;color:var(--danger);">Remover</button>
                    </form>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<div class="card">
    <h3>Como usar Tags</h3>
    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:16px;margin-top:12px;">
        <div style="text-align:center;padding:16px;">
            <div style="font-size:32px;margin-bottom:8px;">1️⃣</div>
            <strong>Crie tags</strong>
            <p style="font-size:13px;color:var(--text-secondary);margin:4px 0 0;">Defina categorias coloridas como "servidores", "clientes" ou "links".</p>
        </div>
        <div style="text-align:center;padding:16px;">
            <div style="font-size:32px;margin-bottom:8px;">2️⃣</div>
            <strong>Aplique nos hosts</strong>
            <p style="font-size:13px;color:var(--text-secondary);margin:4px 0 0;">Ao adicionar ou editar um host, selecione as tags desejadas.</p>
        </div>
        <div style="text-align:center;padding:16px;">
            <div style="font-size:32px;margin-bottom:8px;">3️⃣</div>
            <strong>Filtre rapidamente</strong>
            <p style="font-size:13px;color:var(--text-secondary);margin:4px 0 0;">Na lista de IPs, use os filtros de tag para ver apenas o que importa.</p>
        </div>
    </div>
</div>

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