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

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

$productName = $_POST['product_name'] ?? '';
$originalBarcode = $_POST['original_barcode'] ?? '';

if (empty($productName)) {
    echo json_encode(['success' => false, 'message' => 'Product name is required']);
    exit;
}

try {
    // First check if the product name exists at all
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM {$tables['products']} WHERE ProductName = ?");
    $stmt->execute([$productName]);
    $totalCount = $stmt->fetchColumn();

    // If we're editing (originalBarcode is not empty), check if it's the same product
    if (!empty($originalBarcode)) {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM {$tables['products']} WHERE ProductName = ? AND Barcode = ?");
        $stmt->execute([$productName, $originalBarcode]);
        $currentProductCount = $stmt->fetchColumn();
        
        // If the name exists in other products (total - current > 0)
        $exists = ($totalCount - $currentProductCount) > 0;
    } else {
        // For new products, if the name exists at all, it's a duplicate
        $exists = $totalCount > 0;
    }

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