<?php
// Brand/Product name suggestions for POS search input
// Returns closest matching product names (treated as brands if names are brand-centric)

date_default_timezone_set('Asia/Colombo');
header('Content-Type: application/json');
require_once '../config.php';

$q = isset($_GET['q']) ? trim($_GET['q']) : '';
if ($q === '' || strlen($q) < 2) {
    echo json_encode(['success' => true, 'suggestions' => []]);
    exit;
}

// Prepare patterns for flexible matching
$likeStart = $q . '%';
$likeAnywhere = '%' . $q . '%';

// We don't have a dedicated brand column, so we suggest from products.name.
// Order strategy:
//  1) Exact prefix matches first (name LIKE q%)
//  2) Then infix matches (name LIKE %q%)
//  3) Within those, shorter names rank higher and earlier LOCATE positions rank higher
// Note: Using DISTINCT to avoid duplicates. Also return a count of products for that name.
$sql = "
    SELECT name, COUNT(*) AS cnt,
           CASE WHEN name LIKE ? THEN 0 ELSE 1 END AS rank_prefix,
           LOCATE(?, name) AS pos,
           LENGTH(name) AS len
    FROM products
    WHERE name LIKE ? OR name LIKE ?
    GROUP BY name
    ORDER BY rank_prefix ASC, pos ASC, len ASC, cnt DESC
    LIMIT 10
";

$stmt = $conn->prepare($sql);
if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'Query prepare failed', 'error' => $conn->error]);
    exit;
}
$stmt->bind_param('ssss', $likeStart, $q, $likeStart, $likeAnywhere);
$stmt->execute();
$res = $stmt->get_result();

$suggestions = [];
while ($row = $res->fetch_assoc()) {
    $suggestions[] = [
        'name' => $row['name'],
        'count' => (int)$row['cnt']
    ];
}

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