<?php
declare(strict_types=1);

require_once __DIR__ . '/../../../security/auth_guard.php';
require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../core/Response.php';
require_once __DIR__ . '/../../../core/Validator.php';
require_once __DIR__ . '/../../../core/Slug.php';

$db   = Database::getInstance();
$data = json_decode(file_get_contents('php://input'), true);

Validator::required($data, ['tag_id', 'name']);

$tagId = (int)$data['tag_id'];
$name  = trim($data['name']);

/**
 * Exists check
 */
$stmt = $db->prepare("SELECT id FROM blog_tags WHERE id = :id");
$stmt->execute(['id' => $tagId]);
if (!$stmt->fetch()) {
    Response::error('Tag not found', 404);
}

/**
 * Generate UNIQUE slug (ignore current ID)
 */
$slug = Slug::unique($name, 'blog_tags', $tagId);

/**
 * Update
 */
$stmt = $db->prepare("
    UPDATE blog_tags
    SET name = :name, slug = :slug
    WHERE id = :id
");
$stmt->execute([
    'name' => $name,
    'slug' => $slug,
    'id'   => $tagId
]);

Response::success('Blog tag updated successfully');
