<?php
// /linkstorm/save_set.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;
}

$raw = file_get_contents('php://input');
$data = json_decode($raw, true);

if (!$data) {
    echo json_encode(['error' => 'Invalid JSON.']);
    exit;
}

$name         = trim($data['name'] ?? '');
$sourceType   = trim($data['source_type'] ?? 'paste');
$sourceLabel  = trim($data['source_label'] ?? '');
$handles      = $data['handles'] ?? [];
$hashtags     = $data['hashtags'] ?? [];
$links        = $data['links'] ?? [];
$emails       = $data['emails'] ?? [];

if ($name === '') {
    echo json_encode(['error' => 'Name is required.']);
    exit;
}

try {
    $pdo = ls_pdo();
    $pdo->beginTransaction();

    $stmt = $pdo->prepare("INSERT INTO ls_tag_sets (user_id, name, source_type, source_label) VALUES (?, ?, ?, ?)");
    $stmt->execute([$user['id'], $name, $sourceType, $sourceLabel]);
    $setId = (int)$pdo->lastInsertId();

    $insert = $pdo->prepare("INSERT INTO ls_tag_items (set_id, item_type, value) VALUES (?, ?, ?)");

    foreach ($handles as $h) {
        $h = trim($h);
        if ($h !== '') $insert->execute([$setId, 'handle', $h]);
    }
    foreach ($hashtags as $t) {
        $t = trim($t);
        if ($t !== '') $insert->execute([$setId, 'hashtag', $t]);
    }
    foreach ($links as $lk) {
        $lk = trim($lk);
        if ($lk !== '') $insert->execute([$setId, 'link', $lk]);
    }
    foreach ($emails as $em) {
        $em = trim($em);
        if ($em !== '') $insert->execute([$setId, 'email', $em]);
    }

    $pdo->commit();
    echo json_encode(['success' => true, 'set_id' => $setId]);
} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    echo json_encode(['error' => 'DB error.']);
}
