<?php

declare(strict_types=1);

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

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

try {
    $conn = db_connect();

    // Query
    $q = isset($_GET['q']) ? (string)$_GET['q'] : '';
    $q = trim($q);

    // Limit
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 8;
    if ($limit < 1) {
        $limit = 1;
    }
    if ($limit > 15) {
        $limit = 15;
    }

    // Minimum query length to reduce load/noise
    if (mb_strlen($q, 'UTF-8') < 1) {
        echo json_encode(['items' => []], JSON_UNESCAPED_UNICODE);
        exit;
    }

    // Escape LIKE wildcards (% _), then add %...%
    $like = addcslashes($q, "%_\\");
    $like = '%' . $like . '%';

    // Simple search: model + description
    $sql = "
        SELECT p.productID, p.model, p.description, p.imagePath
        FROM products p
        WHERE (p.model LIKE ? OR p.description LIKE ?)
        ORDER BY
            CASE WHEN p.model LIKE ? THEN 0 ELSE 1 END,
            p.model ASC
        LIMIT ?
    ";

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        http_response_code(500);
        echo json_encode(['error' => 'DB-Query konnte nicht vorbereitet werden.'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $stmt->bind_param('sssi', $like, $like, $like, $limit);
    $stmt->execute();
    $res = $stmt->get_result();

    $items = [];
    while ($row = $res->fetch_assoc()) {
        $id = (int)($row['productID'] ?? 0);
        if ($id <= 0) {
            continue;
        }

        $items[] = [
            'id' => $id,
            'model' => (string)($row['model'] ?? ''),
            'description' => (string)($row['description'] ?? ''),
            'imagePath' => (string)($row['imagePath'] ?? ''),
            'url' => 'productpage.php?id=' . $id,
        ];
    }

    echo json_encode(['items' => $items], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Serverfehler'], JSON_UNESCAPED_UNICODE);
}

