<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/bootstrap.php';
require_once __DIR__ . '/../includes/comment_ai.php';

header('Content-Type: application/json; charset=utf-8');

if (!is_admin(current_user())) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'Yetkisiz'], JSON_UNESCAPED_UNICODE);
    exit;
}

$body = json_decode(file_get_contents('php://input') ?: '', true);
if (!is_array($body)) {
    $body = $_POST;
}

$title = trim((string) ($body['title'] ?? ''));
$category = trim((string) ($body['category'] ?? ''));
$description = trim((string) ($body['description'] ?? ''));
$sellerName = trim((string) ($body['seller_name'] ?? 'Satıcı'));
$sellerUsername = trim((string) ($body['seller_username'] ?? ''));
$count = (int) ($body['count'] ?? 3);

if ($title === '') {
    echo json_encode(['ok' => false, 'error' => 'Önce ürün adını yaz, sonra rastgele yorum üret.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$result = generate_product_comments($title, $category, $description, $count, $sellerName, $sellerUsername);
echo json_encode([
    'ok' => true,
    'source' => $result['source'],
    'comments' => $result['comments'],
    'has_ai' => gemini_api_keys() !== [],
], JSON_UNESCAPED_UNICODE);
