<?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, ['category_id', 'name']);

$categoryId = (int)$data['category_id'];
$name = trim($data['name']);

if ($name === '') {
    Response::error('Category name is required', 422);
}

/**
 * Check exists
 */
$stmt = $db->prepare("SELECT id FROM blog_categories WHERE id = :id");
$stmt->execute(['id' => $categoryId]);
if (!$stmt->fetch()) {
    Response::error('Category not found', 404);
}

// ✅ Correct slug regeneration
$slug = Slug::unique($name, 'blog_categories', $categoryId);

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

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