<?php
/**
 * ============================================================
 *  বধুবরণ জুয়েলার্স ERP — Barcode Sale Module
 *  File: api/barcode/search_barcode.php
 *  Date: 2026-06-17 (v2 — note দিয়ে search যুক্ত)
 *
 *  v2: barcode, item_name বা note যেকোনোটা দিয়ে খুঁজবে
 * ============================================================
 */

ob_start();
@ini_set('display_errors', '0');
error_reporting(E_ERROR | E_PARSE);

require_once __DIR__ . '/../_core.php';
$stray = ob_get_clean();

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

if (!is_logged_in()) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'লগইন করুন']);
    exit;
}

$q     = trim($_GET['q'] ?? '');
$limit = min((int)($_GET['limit'] ?? 20), 50);
if ($limit < 1) $limit = 20;

try {
    $sql = "
        SELECT id,
               barcode,
               item_name,
               karat,
               COALESCE(NULLIF(gross_weight_gram,0), NULLIF(weight,0), 0) AS gross_weight_gram,
               sale_price,
               cost_price,
               note,
               location_id,
               status
          FROM barcode_stock
         WHERE status = 'in_stock'
           AND is_deleted = 0
    ";
    $params = [];
    if ($q !== '') {
        $sql .= " AND (barcode LIKE ? OR item_name LIKE ? OR note LIKE ?) ";
        $params[] = "%{$q}%";
        $params[] = "%{$q}%";
        $params[] = "%{$q}%";
    }
    $sql .= " ORDER BY id DESC LIMIT " . (int)$limit;

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'ok'     => true,
        'count'  => count($rows),
        'query'  => $q,
        'items'  => $rows
    ], JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}