<?php
header('Content-Type: application/json; charset=utf-8');
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
require __DIR__ . '/../includes/session_control.php';
require_once __DIR__ . '/../cotizaciones/api/_node.php';
require_once __DIR__ . '/../includes/user_activity_log.php';

$id    = isset($_POST['id']) ? (int)$_POST['id'] : 0;
$field = isset($_POST['field']) ? (string)$_POST['field'] : '';
$value = $_POST['value'] ?? null;

if (!$id || $field === '') {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Parámetros inválidos']);
    exit;
}

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();
$url = $base . '/api/ventas/detalle/' . urlencode((string)$id);

$r = cpn_node_request('PATCH', $url, $token, ['field' => $field, 'value' => $value]);
if (!isset($r['ok']) || $r['ok'] !== true) {
    http_response_code($r['_http'] ?? 500);
    $msg = $r['error']['message'] ?? 'Error actualizando detalle.';
    echo json_encode(['success' => false, 'error' => $msg]);
    exit;
}

echo json_encode(['success' => true]);

cpn_activity_log_event(
    'Ventas',
    'ventas.item_update',
    'Actualizó detalle de venta (detalle #' . $id . ')',
    'venta_detalle',
    $id,
    ['field' => $field]
);
