44 lines
1.5 KiB
PHP
44 lines
1.5 KiB
PHP
<?php
|
|
session_start();
|
|
require_once 'db/config.php';
|
|
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
|
|
try {
|
|
$role = $_SESSION['user_role'] ?? ($_SESSION['role'] ?? '');
|
|
if (!isset($_SESSION['user_id']) || !in_array($role, ['Administrador', 'admin', 'Control Logistico', 'Logistica'], true)) {
|
|
throw new Exception('No autorizado.');
|
|
}
|
|
|
|
$productId = isset($_POST['product_id']) ? (int)$_POST['product_id'] : 0;
|
|
$ean = isset($_POST['ean']) ? preg_replace('/\s+/', '', trim($_POST['ean'])) : '';
|
|
|
|
if ($productId <= 0) {
|
|
throw new Exception('Producto inválido.');
|
|
}
|
|
|
|
if ($ean !== '' && !preg_match('/^[0-9]{1,32}$/', $ean)) {
|
|
throw new Exception('El EAN solo debe contener números.');
|
|
}
|
|
|
|
$eanToSave = $ean !== '' ? $ean : null;
|
|
$stmt = db()->prepare('UPDATE products SET ean = :ean WHERE id = :id');
|
|
$stmt->bindValue(':ean', $eanToSave, $eanToSave === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
|
|
$stmt->bindValue(':id', $productId, PDO::PARAM_INT);
|
|
$stmt->execute();
|
|
|
|
if ($stmt->rowCount() === 0) {
|
|
$check = db()->prepare('SELECT id FROM products WHERE id = :id');
|
|
$check->bindValue(':id', $productId, PDO::PARAM_INT);
|
|
$check->execute();
|
|
if (!$check->fetchColumn()) {
|
|
throw new Exception('Producto no encontrado.');
|
|
}
|
|
}
|
|
|
|
echo json_encode(['success' => true, 'ean' => $eanToSave ?? '']);
|
|
} catch (Exception $e) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
|
|
}
|