<?php
include 'includes/config.php';
header('Content-Type: application/json');

$field = $_POST['field'] ?? '';

$name     = $_POST['name'] ?? '';
$code     = $_POST['product_code'] ?? '';
$color    = $_POST['color_id'] ?? '';
$size     = $_POST['size_id'] ?? '';
$barcode  = $_POST['barcode'] ?? '';

$response = ['exists' => false];

if ($field === "unique_product") {
    $stmt = $conn->prepare("
        SELECT COUNT(*) 
        FROM products 
        WHERE name = :name 
          AND product_code = :code 
          AND color_id = :color 
          AND size_id = :size
    ");
    $stmt->execute([
        ':name'  => $name,
        ':code'  => $code,
        ':color' => $color,
        ':size'  => $size
    ]);
    $exists = $stmt->fetchColumn() > 0;
    $response['exists'] = $exists;
}

if ($field === "unique_barcode") {
    $stmt = $conn->prepare("SELECT COUNT(*) FROM products WHERE barcode = :barcode");
    $stmt->execute([':barcode' => $barcode]);
    $exists = $stmt->fetchColumn() > 0;
    $response['exists'] = $exists;
}

echo json_encode($response);
