<?php
declare(strict_types=1);

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

dbnToolsRequireMethod('POST');
dbnToolsRequireAuth();

$input = dbnToolsJsonInput(8000);

$tool   = substr(preg_replace('/[^a-z_]/', '', strtolower((string)($input['tool'] ?? ''))), 0, 30);
$rating = (string)($input['rating'] ?? '');
$missed = substr(trim((string)($input['missed_or_wrong'] ?? '')), 0, 2000);
$engine = substr(preg_replace('/[^a-zA-Z0-9_.() \-]/', '', (string)($input['engine'] ?? '')), 0, 60);

if (!in_array($rating, ['positive', 'negative'], true)) {
    dbnToolsAbort('Invalid rating value.', 422, 'invalid_rating');
}
if ($tool === '') {
    dbnToolsAbort('Tool name is required.', 422, 'missing_tool');
}

try {
    $db   = dbnToolsDb();
    $stmt = $db->prepare(
        'INSERT INTO tool_feedback (session_id, tool, rating, missed_or_wrong, engine)
         VALUES (?, ?, ?, ?, ?)'
    );
    $stmt->execute([
        substr(session_id(), 0, 40) ?: null,
        $tool,
        $rating,
        $missed !== '' ? $missed : null,
        $engine !== '' ? $engine : null,
    ]);
} catch (Throwable $e) {
    error_log('tool_feedback insert failed: ' . $e->getMessage());
    dbnToolsAbort('Could not save feedback.', 500, 'db_error');
}

header('Content-Type: application/json');
echo json_encode(['ok' => true]);
