<?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';

$action = $_REQUEST['action'] ?? '';

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();

if ($action === 'list') {
  $idDet = isset($_GET['idVentaDetalle']) ? (int)$_GET['idVentaDetalle'] : 0;
  if (!$idDet) {
    http_response_code(400);
    echo json_encode([]);
    exit;
  }

  $url = $base . '/api/ventas/detalle/' . urlencode((string)$idDet) . '/servicios';
  $r = cpn_node_request('GET', $url, $token);
  if (!isset($r['ok']) || $r['ok'] !== true) {
    http_response_code($r['_http'] ?? 500);
    echo json_encode([]);
    exit;
  }
  $data = $r['data'] ?? [];
  if (!is_array($data)) $data = [];
  echo json_encode($data);
  exit;
}

if ($action === 'add') {
  $idDet = isset($_POST['idVentaDetalle']) ? (int)$_POST['idVentaDetalle'] : 0;
  if (!$idDet) {
    http_response_code(400);
    echo json_encode(['success' => false]);
    exit;
  }

  $url = $base . '/api/ventas/detalle/' . urlencode((string)$idDet) . '/servicios';
  $payload = [
    'idServicioTipo' => $_POST['idServicioTipo'] ?? null,
    'nombre' => $_POST['nombre'] ?? '',
    'precioVentaAntesImpuestos' => $_POST['precioVentaAntesImpuestos'] ?? 0,
    'observaciones' => $_POST['observaciones'] ?? '',
  ];
  $r = cpn_node_request('POST', $url, $token, $payload);
  if (!isset($r['ok']) || $r['ok'] !== true) {
    http_response_code($r['_http'] ?? 500);
    echo json_encode(['success' => false, 'error' => ($r['error']['message'] ?? 'Error')]);
    exit;
  }

  echo json_encode(['success' => true]);
  exit;
}

if ($action === 'delete') {
  $idReg = isset($_POST['idRegistro']) ? (int)$_POST['idRegistro'] : 0;
  if (!$idReg) {
    http_response_code(400);
    echo json_encode(['success' => false]);
    exit;
  }

  $url = $base . '/api/ventas/servicios/' . urlencode((string)$idReg);
  $r = cpn_node_request('DELETE', $url, $token);
  if (!isset($r['ok']) || $r['ok'] !== true) {
    http_response_code($r['_http'] ?? 500);
    echo json_encode(['success' => false, 'error' => ($r['error']['message'] ?? 'Error')]);
    exit;
  }
  echo json_encode(['success' => true]);
  exit;
}

echo json_encode(['error' => 'Acción inválida']);
$det->bind_param('i', $idDet);
