<?php
session_start();
header('Content-Type: application/json');

require_once __DIR__ . '/../classes/DB.php';
require_once __DIR__ . '/../classes/User.php';
require_once __DIR__ . '/../classes/Tag.php';

$user = User::fromSession();
if (!$user) {
    echo json_encode(["ok" => false, "error" => "Not logged in"]);
    exit;
}

$imageId = $_POST['image_id'] ?? null;
$tag     = $_POST['tag'] ?? null;

if (!$imageId || !$tag) {
    echo json_encode(["ok" => false, "error" => "Missing fields"]);
    exit;
}

$tag = trim($tag);
if ($tag === "") {
    echo json_encode(["ok" => false, "error" => "Empty tag"]);
    exit;
}

Tag::addUserTag((int)$imageId, $user->id, $tag);

echo json_encode(["ok" => true, "tag" => $tag]);