<?php
use GuzzleHttp\Client;

$app->get('/', function( $req, $res, $args){
  $res->getBody()->write('Silencio!!!');
  return $res;
});

$app->post('/soap-romis', function ( $req, $resp, array $args) {

  // Crear cliente Guzzle
  $client = new Client();

  function stock($client, $Prdid){

    $headers = [
      'SOAPAction' => 'SIGE_VSaction/AXWSPRECIOPRODUCTOEMPRESA.Execute',
      'Content-Type' => 'application/xml',
      'Authorization' => 'Basic d2ViOmRBKHIpLlckJGluMTIz',
      'Cookie' => 'JSESSIONID=229A77C51DDA806BD187C37143171A00'
    ];
    $body = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sige="SIGE_VS">
       <soapenv:Header/>
       <soapenv:Body>
          <sige:xWSStockProducto.Execute>
             <sige:Prdid>'.$Prdid.'</sige:Prdid>
             <sige:Depid>Y1</sige:Depid>
          </sige:xWSStockProducto.Execute>
       </soapenv:Body>
    </soapenv:Envelope>';

    // Realiza la petición HTTP con Guzzle
    $soapResponse = $client->post('http://190.64.64.43/SIGE_VS_E_WS/servlet/axwsstockproducto?wsdl', [
        'headers' => $headers,
        'body' => $body,
    ]);
    $bodyContent = $soapResponse->getBody()->getContents();

    try {
      $xml = simplexml_load_string($bodyContent, 'SimpleXMLElement', LIBXML_NOWARNING);

      if ($xml === false) {
        foreach (libxml_get_errors() as $error) { echo "\t", $error->message; }
      } else {

        $namespace = 'SIGE_VS';
        $body = $xml->children('SOAP-ENV', true)->Body->children($namespace);

        if(isset($body)){
          $st = $body->{'xWSStockProducto.ExecuteResponse'}->Saldo;
          $stock = trim($st[0]);
          return (string) $stock;
        }

      }

    } catch (Exception $e) {
      echo 'Error: ' . $e->getMessage();
    }
  }

  // Headers para la consulta SOAP
  $headers = [
      'SOAPAction' => 'SIGE_VSaction/AXWSPRECIOPRODUCTOEMPRESA.Execute',
      'Content-Type' => 'application/xml',
      'Authorization' => 'Basic d2ViOmRBKHIpLlckJGluMTIz',
      'Cookie' => 'JSESSIONID=5BFDD29138DCB535CD47A0461E1F10F8'
  ];

  // Cuerpo del mensaje SOAP
  $body = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sige="SIGE_VS">
      <soapenv:Header/>
      <soapenv:Body>
          <sige:XWSPreciosRomis.Execute/>
      </soapenv:Body>
  </soapenv:Envelope>';

  try {
    // Realiza la petición HTTP con Guzzle
    $soapResponse = $client->post('http://190.64.64.43/SIGE_VS_E_WS/servlet/axwspreciosromis', [
        'headers' => $headers,
        'body' => $body,
    ]);
    $bodyContent = $soapResponse->getBody()->getContents();

    try {
      $xml = simplexml_load_string($bodyContent, 'SimpleXMLElement', LIBXML_NOWARNING);

      if ($xml === false) {
        foreach (libxml_get_errors() as $error) { echo "\t", $error->message; }
      } else {
        $namespace = 'SIGE_VS';
        $body = $xml->children('SOAP-ENV', true)->Body->children($namespace);

        $result = [];

        if (isset($body)) {
          $precios = $body->{'XWSPreciosRomis.ExecuteResponse'}->Sdtprecioromis->SDTPrecioRomis;
          foreach ($precios as $p) {
            $prdId = (string) $p->PrdId;
            $prdUniPub = (string) $p->PrdUniPub;
            $prdUniDis = (string) $p->PrdUniDis;

            $stock = stock($client, $prdId);

						$result[] = [
              'prdId' => $prdId,
              'prdUniPub' => $prdUniPub,
              'prdUniDis' => $prdUniDis,
              'stock' => $stock
            ];
          }

        } else {
            echo "No se encontró Sdtprecioromis en la respuesta.";
        }

        }
    } catch (Exception $e) {
      echo 'Error: ' . $e->getMessage();
    }

    $jsonResponse = [
      'success' => true,
      'data' => $result
    ];

    $resp->getBody()->write(json_encode($jsonResponse));
    return $resp->withHeader('Content-Type', 'application/json');

  } catch (\GuzzleHttp\Exception\RequestException $e) {
    // Manejo de errores
    $errorResponse = [
      'success' => false,
      'message' => 'Error: ' . $e->getMessage()
    ];

    $resp->getBody()->write(json_encode($errorResponse));
    return $resp->withHeader('Content-Type', 'application/json')->withStatus(500);
  }
});