<?php
/**
 * AJAX endpoint — AI product description generator
 * Routed through central security: Auth + CSRF enforced.
 */
if (!defined('ROOT_PATH')) {
    define('ROOT_PATH', dirname(__DIR__, 3));
}

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

header('Content-Type: application/json');

// ── Auth guard ────────────────────────────────────────────────────────────────
if (
    empty($_SESSION['admin_logged_in']) ||
    $_SESSION['admin_logged_in'] !== true ||
    empty($_SESSION['admin_id'])
) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

// ── CSRF check ────────────────────────────────────────────────────────────────
$csrfHeader = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? $_SERVER['HTTP_X_CSRF'] ?? '';
$csrfPost   = $_POST['_csrf'] ?? '';
$csrfToken  = trim($csrfHeader ?: $csrfPost);

if (
    $csrfToken === '' ||
    empty($_SESSION['_csrf']) ||
    !hash_equals((string) $_SESSION['_csrf'], $csrfToken)
) {
    http_response_code(419);
    echo json_encode(['success' => false, 'message' => 'CSRF token mismatch']);
    exit;
}

// ── Autoloader ────────────────────────────────────────────────────────────────
spl_autoload_register(function ($class) {
    $class   = ltrim($class, '\\');
    $relPath = str_replace('\\', '/', $class) . '.php';
    $relPath = str_replace(
        ['Core/', 'System/', 'App/'],
        ['core/', 'system/', 'app/'],
        $relPath
    );
    $file = ROOT_PATH . '/' . $relPath;
    if (is_file($file)) {
        require_once $file;
    }
});

require_once ROOT_PATH . '/core/system/Env.php';
\Core\System\Env::bootstrap(ROOT_PATH);

use Core\App\Services\GeminiService;
use Core\System\Language;

try {
    $title   = trim($_POST['title'] ?? '');
    $short   = trim($_POST['short_description'] ?? '');
    $dialect = $_POST['dialect'] ?? 'fusha';

    if ($title === '' || $short === '') {
        throw new Exception(__('ai.missing_fields', 'Missing required fields'));
    }

    $lang = Language::code();
    $text = GeminiService::generateProductDescription($title, $short, $lang, $dialect);

    echo json_encode(['success' => true, 'text' => $text]);

} catch (Throwable $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
