<?php
require 'vendor/autoload.php'; // Asegúrate de incluir el autoload de Composer

use GuzzleHttp\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();
    }
}

// Inicialización del cliente Guzzle
$client = new Client();

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

$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 {
    $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();
    }

    // Configuración de la respuesta JSON
    header('Content-Type: application/json');
    $jsonResponse = [
        'success' => true,
        'data' => $result
    ];

    echo json_encode($jsonResponse);

} catch (\GuzzleHttp\Exception\RequestException $e) {
    // Manejo de errores
    header('Content-Type: application/json');
    $jsonResponse = [
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ];
    echo json_encode($jsonResponse);
}
