<?php

namespace App\Api\V1\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB;
use PDO;

class SoapIntegrationController extends Controller
{
    public function sendSoapRequest(Request $request)
    {
        try {
            // Get the SOAP request data from the request
            $soapRequest = $request->input('soap_request');

            // Set the SOAP endpoint URL
            $url = $request->input('url');

            // Create a SOAP client
            $client = new \SoapClient(null, [
                'location' => $url,
                'uri' => $url,
            ]);

            // Send the SOAP request and get the response
            $response = $client->__doRequest($soapRequest, $url, 'YourSOAPAction', SOAP_1_2);

            // Display the response
            return response($response, 200)->header('Content-Type', 'text/xml');
        } catch (\Exception $ex) {
            return response()->json(['error' => 'An error occurred: ' . $ex->getMessage()], 500);
        }
    }
  

    public function postInsertSoapRequest(Request $request)
    {

        $soapRequest = $request->input('soap_request');
        $spName= $request->input('stored_procedure');
        try {
            // Get the PDO connection
            $pdo = DB::connection('sqlsrv3')->getPdo();
        
            // Prepare the SQL statement for executing the stored procedure
            $sql = "exec ".$spName." ?";
            $stmt = $pdo->prepare($sql);
        
            // Bind the input parameter
            $stmt->bindParam(1, $soapRequest, PDO::PARAM_STR);
        
            // Execute the stored procedure
            $stmt->execute();
        
            // Fetch the results
            $results = [];
            do {
            // Check if the current result set has fields
            if ($stmt->columnCount() > 0) {
                $resultSet = [];
                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    $resultSet[] = $row;
                }
            if (!empty($resultSet)) {
                    $results[] = $resultSet;
                    }
                }
            } while ($stmt->nextRowset());
    
            return response()->json([
                'status' => 'ok',
                'result' => $results
            ]);
        } catch (PDOException $e) {
            return response()->json([
                'sql'=>$sql,
                'xml'=>$soaprquest,
                'error' => 'An error occurred: ' . $e->getMessage()], 500
            );
        }
    }       
        
}