<?php
declare(strict_types=1);

require_once __DIR__ . '/../../security/auth_guard_web.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();

/* ================= INPUT ================= */
$data = json_decode(file_get_contents('php://input'), true);
if (!is_array($data)) {
    Response::error('Invalid JSON payload');
}

/* ================= VALIDATION ================= */
Validator::required($data, ['id', 'category_name', 'description']);

$id = (int) $data['id'];
if ($id <= 0) {
    Response::error('Invalid category id');
}

$categoryName = trim($data['category_name']);
Validator::minLength($categoryName, 2, 'category_name');

$shortDescription = $data['short_description'] ?? null;
$description      = trim($data['description']);

$metaTitle       = $data['meta_title'] ?? null;
$metaKeywords    = $data['meta_keywords'] ?? null;
$metaDescription = $data['meta_description'] ?? null;
$aiSummary       = $data['ai_summary'] ?? null;

/* ================= CHECK EXISTS ================= */
$stmt = $db->prepare("
    SELECT id, category_name
    FROM retail_categories
    WHERE id = :id
");
$stmt->execute(['id' => $id]);

$existing = $stmt->fetch();
if (!$existing) {
    Response::error('Category not found');
}

/* ================= SLUG HANDLING ================= */
$slug = Slug::unique($categoryName, 'retail_categories', $id);

/* ================= UPDATE ================= */
$stmt = $db->prepare("
    UPDATE retail_categories
    SET
        category_name     = :category_name,
        slug              = :slug,
        short_description = :short_description,
        description       = :description,
        meta_title        = :meta_title,
        meta_keywords     = :meta_keywords,
        meta_description  = :meta_description,
        ai_summary        = :ai_summary,
        updated_at        = NOW()
    WHERE id = :id
");

$stmt->execute([
    'category_name'     => $categoryName,
    'slug'              => $slug,
    'short_description' => $shortDescription,
    'description'       => $description,
    'meta_title'        => $metaTitle,
    'meta_keywords'     => $metaKeywords,
    'meta_description'  => $metaDescription,
    'ai_summary'        => $aiSummary,
    'id'                => $id
]);

Response::success('Category updated successfully', [
    'id'   => $id,
    'slug' => $slug
]);
