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

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

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

/* ================= OPTIONAL FIELDS ================= */
$shortDesc = $data['short_description'] ?? null;
$desc      = $data['description'] ?? null;

$imagePath = $data['image_path'] ?? null;
$imageAlt  = $data['image_alt'] ?? null;

$metaTitle = $data['meta_title'] ?? null;
$metaDesc  = $data['meta_description'] ?? null;
$metaKeys  = $data['meta_keywords'] ?? null;

$aiSummary = $data['ai_summary'] ?? null;

/* ================= SLUG ================= */
$slug = Slug::unique($name, 'retail_categories');

/* ================= INSERT ================= */
$stmt = $db->prepare("
    INSERT INTO retail_categories (
        category_name,
        slug,
        short_description,
        description,
        image_path,
        image_alt,
        meta_title,
        meta_description,
        meta_keywords,
        ai_summary,
        status
    ) VALUES (
        :name,
        :slug,
        :short_desc,
        :description,
        :image_path,
        :image_alt,
        :meta_title,
        :meta_description,
        :meta_keywords,
        :ai_summary,
        'Active'
    )
");

$stmt->execute([
    'name'             => $name,
    'slug'             => $slug,
    'short_desc'       => $shortDesc,
    'description'      => $desc,
    'image_path'       => $imagePath,
    'image_alt'        => $imageAlt,
    'meta_title'       => $metaTitle,
    'meta_description' => $metaDesc,
    'meta_keywords'    => $metaKeys,
    'ai_summary'       => $aiSummary,
]);

Response::success('Retail category created', [
    'id'   => $db->lastInsertId(),
    'slug' => $slug
]);
