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

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

/**
 * Mandatory
 */
Validator::required($data, [
    'product_id',
    'meta_title',
    'meta_description'
]);

$productId = (int)$data['product_id'];

/**
 * Check product exists
 */
$stmt = $db->prepare("
    SELECT id FROM retail_products WHERE id = :id
");
$stmt->execute(['id' => $productId]);

if (!$stmt->fetch()) {
    Response::error('Retail product not found', 404);
}

/**
 * SEO fields (sanitize & trim)
 */
$metaTitle       = trim($data['meta_title']);
$metaDescription = trim($data['meta_description']);
$metaKeywords    = isset($data['meta_keywords']) ? trim($data['meta_keywords']) : null;
$seoSchema       = $data['seo_schema'] ?? null;
$aiSeoContent    = $data['ai_seo_content'] ?? null;

Validator::minLength($metaTitle, 5, 'meta_title');
Validator::minLength($metaDescription, 10, 'meta_description');

/**
 * Update SEO
 */
$stmt = $db->prepare("
    UPDATE retail_products
    SET
        meta_title = :meta_title,
        meta_description = :meta_description,
        meta_keywords = :meta_keywords,
        seo_schema = :seo_schema,
        ai_seo_content = :ai_seo_content,
        updated_by = :updated_by,
        updated_at = NOW()
    WHERE id = :id
");

$stmt->execute([
    'meta_title'       => $metaTitle,
    'meta_description' => $metaDescription,
    'meta_keywords'    => $metaKeywords,
    'seo_schema'       => $seoSchema,
    'ai_seo_content'   => $aiSeoContent,
    'updated_by'       => $_SESSION['employee_id'],
    'id'               => $productId
]);

Response::success('Retail product SEO updated successfully');
