<?php
// product_lookup.php?q=...
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/src/auth.php';
// no require_login() so public ajax works if needed; if you want protect it, uncomment next line:
// require_login();

$q = $_GET['q'] ?? '';
$q = trim($q);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if($q === ''){
    // return top 20 products
    $stmt = $pdo->prepare("SELECT id, sku, name, stock, sale_price FROM products ORDER BY name LIMIT 50");
    $stmt->execute();
} else {
    $like = "%{$q}%";
    $stmt = $pdo->prepare("SELECT id, sku, name, stock, sale_price FROM products WHERE name LIKE ? OR sku LIKE ? ORDER BY name LIMIT 50");
    $stmt->execute([$like, $like]);
}
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($rows);
