<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../../classes/Database.php';

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
if (empty($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Login required.']);
    exit;
}

$data = json_decode(file_get_contents("php://input"), true);
$uniqueCode = trim((string)($data['unique_code'] ?? ''));

if ($uniqueCode === '') {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing required parameter: unique_code']);
    exit;
}

$database = new Database();
$db = $database->getConnection();

// unique_code is globally unique across all items/branches, not scoped per branch.
$stmt = $db->prepare("SELECT COUNT(*) FROM items WHERE unique_code = :code");
$stmt->execute([':code' => $uniqueCode]);
$exists = $stmt->fetchColumn() > 0;

if ($exists) {
    echo json_encode(['success' => false, 'exists' => true, 'message' => 'This unique code already exists.']);
} else {
    echo json_encode(['success' => true, 'exists' => false, 'message' => 'Unique code is available.']);
}