<?php
require_once '../config/database.php';

header('Content-Type: application/json');

$barcode = $_POST['barcode'] ?? '';
$originalBarcode = $_POST['original_barcode'] ?? '';

if (empty($barcode)) {
    echo json_encode(['success' => true, 'exists' => false, 'message' => 'Barcode is optional']);
    exit;
}

try {
    // Check if barcode exists in products table
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM {$tables['products']} WHERE Barcode = ? AND Barcode != ? AND Barcode IS NOT NULL");
    $stmt->execute([$barcode, $originalBarcode]);
    $exists = $stmt->fetchColumn() > 0;

    echo json_encode([
        'success' => true,
        'exists' => $exists,
        'message' => $exists ? 'Barcode already exists' : 'Barcode is available'
    ]);
} catch(Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?> 