<?php
date_default_timezone_set('Asia/Colombo');
include '../config.php';

header('Content-Type: application/json');
// Prevent PHP notices/warnings from corrupting JSON output
@ini_set('display_errors', '0');
@ini_set('display_startup_errors', '0');
// Still log errors to the server log if configured

$barcode = $_GET['barcode'] ?? '';
$barcode_trim = trim($barcode);
// Remove control characters and unicode spaces that some scanners may insert
$barcode_clean = preg_replace('/[\x00-\x1F\x7F\x{00A0}\x{1680}\x{2000}-\x{200D}\x{202F}\x{205F}\x{3000}]/u', '', $barcode_trim);
// Also build an alphanumeric-only version for permissive matching
$barcode_alnum = preg_replace('/[^A-Za-z0-9]/u', '', $barcode_clean);
$product_id = $_GET['id'] ?? '';

if (empty($barcode) && empty($product_id)) {
    echo json_encode(['success' => false, 'message' => 'Barcode or Product ID required']);
    exit;
}

// Search by product ID first (for resuming held orders)
if (!empty($product_id)) {
    $stmt = $conn->prepare("SELECT id, name, category, price, half_price, stock, barcode FROM products WHERE id = ? LIMIT 1");
    $stmt->bind_param("i", $product_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($product = $result->fetch_assoc()) {
        echo json_encode(['success' => true, 'data' => $product]);
        exit;
    } else {
        echo json_encode(['success' => false, 'message' => 'Product not found']);
        exit;
    }
}

// Search by barcode (multi-product support)
if (!empty($barcode_clean)) {
    // 1) Exact match first
    $stmt = $conn->prepare("SELECT id, name, category, price, half_price, stock, barcode FROM products WHERE barcode = ?");
    $stmt->bind_param("s", $barcode_clean);
    $stmt->execute();
    $result = $stmt->get_result();
    $products = [];
    while ($row = $result->fetch_assoc()) { $products[] = $row; }

    // 2) Fallback: ignore embedded CR/LF and spaces in stored barcode
    if (count($products) === 0) {
        $sql2 = "SELECT id, name, category, price, half_price, stock, barcode
                 FROM products
                 WHERE REPLACE(REPLACE(REPLACE(TRIM(barcode), CHAR(13), ''), CHAR(10), ''), ' ', '') = ?";
        $stmt2 = $conn->prepare($sql2);
        $stmt2->bind_param("s", $barcode_clean);
        $stmt2->execute();
        $res2 = $stmt2->get_result();
        while ($row = $res2->fetch_assoc()) { $products[] = $row; }
    }

    // 3) Fallback: compare after stripping common separators (dash, dot, slash, backslash, spaces)
    if (count($products) === 0 && $barcode_alnum !== '') {
        $sql3 = "SELECT id, name, category, price, half_price, stock, barcode
                 FROM products
                 WHERE REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(TRIM(barcode),' ', ''), '-', ''), '.', ''), '/', ''), '\\', ''), CHAR(13), '') = ?";
        $stmt3 = $conn->prepare($sql3);
        $stmt3->bind_param("s", $barcode_alnum);
        $stmt3->execute();
        $res3 = $stmt3->get_result();
        while ($row = $res3->fetch_assoc()) { $products[] = $row; }
    }

    if (count($products) === 1) {
        echo json_encode(['success' => true, 'data' => $products[0]]);
    } else if (count($products) > 1) {
        echo json_encode(['success' => true, 'multiple' => true, 'data' => $products]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Product not found']);
    }
}
?>
