<?php
include 'db_connection.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Método no permitido']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);

if (!isset($data['id']) || !isset($data['field']) || !isset($data['value'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Datos incompletos']);
    exit;
}

$id = intval($data['id']);
$field = $data['field'];
$value = floatval($data['value']);

$allowed_fields = [
    'PrecioVentaUnidad',
    'PrecioVentaBlister',
    'PrecioVentaMayor',
    'PrecioVentaMixto'
];

if (!in_array($field, $allowed_fields)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Campo no válido']);
    exit;
}

$sql = "UPDATE productos SET $field = ? WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('di', $value, $id);

if ($stmt->execute()) {
    echo json_encode(['success' => true]);
} else {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error al actualizar el precio']);
}

$stmt->close();
$conn->close();