<?php
/**
 * Check if barcode already exists in database
 */
session_start();
header('Content-Type: application/json');

include_once('../../includes/config.php');

if (!isset($_SESSION['uid'])) {
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['barcode'])) {
    $barcode = mysqli_real_escape_string($con, $_POST['barcode']);
    
    // Check if barcode exists
    $query = "SELECT ID, ItemCode, ItemName FROM tblitems WHERE Barcode = '$barcode' LIMIT 1";
    $result = mysqli_query($con, $query);
    
    if ($result && mysqli_num_rows($result) > 0) {
        $item = mysqli_fetch_assoc($result);
        echo json_encode([
            'exists' => true,
            'itemId' => $item['ID'],
            'itemCode' => $item['ItemCode'],
            'itemName' => $item['ItemName']
        ]);
    } else {
        echo json_encode([
            'exists' => false
        ]);
    }
} else {
    echo json_encode(['error' => 'Invalid request']);
}
?>
