<?php
/**
 * ============================================================
 *  বধুবরণ জুয়েলার্স ERP — Sales Module
 *  File: api/sales/search_items.php
 *  Date: 2026-06-17 (v3.2 — note দিয়ে search যুক্ত)
 *
 *  v3.2: barcode_stock search-এ note কলাম যুক্ত
 *        (barcode, item_name বা note যেকোনোটা দিয়ে খুঁজবে)
 *  v3.1 (2026-06-15): gross_weight_gram priority fix
 *  v3.0 (2026-05-16): output buffer + strict JSON
 * ============================================================
 */

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']      ?? '');
$source = $_GET['source']      ?? 'both';
$limit  = min((int)($_GET['limit'] ?? 20), 50);
if ($limit < 1) $limit = 20;

$results = [];

try {
    // -------------------------------------------------------
    // 1) Barcode Stock Search — barcode, item_name, note
    // -------------------------------------------------------
    if ($source === 'barcode' || $source === 'both') {
        try {
            $sql = "
                SELECT id,
                       barcode,
                       item_name AS product_name,
                       NULL       AS category,
                       karat,
                       COALESCE(NULLIF(gross_weight_gram,0), NULLIF(weight,0), 0) AS gross_weight_gram,
                       sale_price,
                       cost_price,
                       note,
                       location_id,
                       'barcode'  AS source_type
                  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);
            foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
                $results[] = $r;
            }
        } catch (Exception $e) {
            error_log("search_items.php barcode_stock error: " . $e->getMessage());
        }
    }

    // -------------------------------------------------------
    // 2) New Stock Search
    // -------------------------------------------------------
    if ($source === 'new_stock' || $source === 'both') {
        try {
            $sql = "
                SELECT id,
                       NULL                  AS barcode,
                       product_name,
                       category,
                       karat,
                       available_weight_gram AS gross_weight_gram,
                       available_pcs,
                       total_pcs,
                       total_weight_gram,
                       pure_weight_gram,
                       rate_per_vori,
                       NULL                  AS note,
                       location_id,
                       'new_stock'           AS source_type
                  FROM new_stock
                 WHERE available_weight_gram > 0
                   AND deleted_at IS NULL
            ";
            $params = [];
            if ($q !== '') {
                $sql .= " AND (product_name LIKE ? OR category LIKE ? OR karat LIKE ?) ";
                $params[] = "%{$q}%";
                $params[] = "%{$q}%";
                $params[] = "%{$q}%";
            }
            $sql .= " ORDER BY id DESC LIMIT " . (int)$limit;

            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
                $results[] = $r;
            }
        } catch (Exception $e) {
            error_log("search_items.php new_stock error: " . $e->getMessage());
        }
    }

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

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