<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
header('Content-Type: application/json');

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
}

if (!hasPermission('product_management') && !hasPermission('stock_management')) {
    echo json_encode(['success' => false, 'message' => 'Permission denied']);
    exit;
}

$product_type = $_GET['product_type'] ?? '';
$valid_types = ['phone', 'accessory', 'spare_part'];

if (!in_array($product_type, $valid_types)) {
    echo json_encode(['success' => false, 'message' => 'Invalid product type']);
    exit;
}

try {
    $barcode = generateUniqueBarcode($product_type);
    echo json_encode(['success' => true, 'barcode' => $barcode]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Unable to generate barcode']);
}
