<?php
// ventas_deducciones_api.php
header('Content-Type: application/json');
if (session_status() !== PHP_SESSION_ACTIVE) {
  session_start();
}
require __DIR__ . '/../includes/session_control.php';
require_once __DIR__ . '/../cotizaciones/api/_node.php';

$action  = $_REQUEST['action'] ?? '';
$idVenta = isset($_REQUEST['idVenta']) ? (int)$_REQUEST['idVenta'] : 0;

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();

if ($action === 'list') {
  if (!$idVenta) {
    echo json_encode([]);
    exit;
  }
  $url = $base . '/api/ventas/ordenes/' . urlencode((string)$idVenta) . '/deducciones';
  $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 === 'listsel') {
  $url = $base . '/api/ventas/deducciones/meta';
  $r = cpn_node_request('GET', $url, $token);
  if (!isset($r['ok']) || $r['ok'] !== true) {
    http_response_code($r['_http'] ?? 500);
    echo json_encode(['lista' => []]);
    exit;
  }
  $meta = $r['data'] ?? [];
  echo json_encode(['lista' => $meta['lista'] ?? []]);
  exit;
}

if ($action === 'add') {
  if (!$idVenta) {
    http_response_code(400);
    echo json_encode(['success' => false]);
    exit;
  }
  $url = $base . '/api/ventas/ordenes/' . urlencode((string)$idVenta) . '/deducciones';
  $payload = [
    'fecha' => $_POST['fecha'] ?? null,
    'idDeduccion' => $_POST['idDeduccion'] ?? null,
    'porcentajeDeduccion' => $_POST['porcentajeDeduccion'] ?? 0,
    'valorDeduccion' => $_POST['valorDeduccion'] ?? 0,
    'refPago' => $_POST['refPago'] ?? null,
  ];
  $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') {
  $id = isset($_POST['idRegistro']) ? (int)$_POST['idRegistro'] : 0;
  if (!$id) {
    http_response_code(400);
    echo json_encode(['success' => false]);
    exit;
  }
  $url = $base . '/api/ventas/deducciones/' . urlencode((string)$id);
  $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']);
