<?php
// /linkstorm/list_sets.php
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/inc/db.php';

$user = ls_current_user();
if (!$user) {
    echo json_encode(['error' => 'Not logged in.']);
    exit;
}

$pdo = ls_pdo();
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($id > 0) {
    $stmt = $pdo->prepare("SELECT * FROM ls_tag_sets WHERE id = ? AND user_id = ?");
    $stmt->execute([$id, $user['id']]);
    $set = $stmt->fetch();
    if (!$set) {
        echo json_encode(['error' => 'Tag set not found.']);
        exit;
    }

    $stmt2 = $pdo->prepare("SELECT item_type, value FROM ls_tag_items WHERE set_id = ? ORDER BY item_type, value");
    $stmt2->execute([$id]);
    $items = $stmt2->fetchAll();

    $handles = $hashtags = $links = $emails = [];
    foreach ($items as $row) {
        switch ($row['item_type']) {
            case 'handle':  $handles[]  = $row['value']; break;
            case 'hashtag': $hashtags[] = $row['value']; break;
            case 'link':    $links[]    = $row['value']; break;
            case 'email':   $emails[]   = $row['value']; break;
        }
    }

    echo json_encode([
        'id'           => $set['id'],
        'name'         => $set['name'],
        'source_type'  => $set['source_type'],
        'source_label' => $set['source_label'],
        'handles'      => $handles,
        'hashtags'     => $hashtags,
        'links'        => $links,
        'emails'       => $emails
    ]);
    exit;
}

$stmt = $pdo->prepare("SELECT id, name, source_type, source_label, created_at FROM ls_tag_sets WHERE user_id = ? ORDER BY created_at DESC LIMIT 100");
$stmt->execute([$user['id']]);
$rows = $stmt->fetchAll();

echo json_encode(['sets' => $rows]);
