<?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']);

$slug = Slug::make($name);

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

/**
 * Slug conflict check
 */
$stmt = $db->prepare("
    SELECT id FROM faq_categories
    WHERE slug = :slug AND id != :id
");
$stmt->execute([
    'slug' => $slug,
    'id'   => $categoryId
]);
if ($stmt->fetch()) {
    Response::error('Another FAQ category with same name exists', 409);
}

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

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