<?php
// Direct SOAP test without Laravel bootstrap

echo "=== Direct RMTO SOAP Test ===\n\n";

$username = 'test';
$password = '123456';
$endpoint = 'http://bar-test.rmto.ir/TRNServiceV03.svc';

// Create SOAP request for GetRmtoCurrentDate
$soapRequest = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
   <soapenv:Header/>
   <soapenv:Body>
      <tem:GetRmtoCurrentDate>
         <tem:UserID>{$username}</tem:UserID>
         <tem:Password>{$password}</tem:Password>
      </tem:GetRmtoCurrentDate>
   </soapenv:Body>
</soapenv:Envelope>
XML;

echo "Test: Sending GetRmtoCurrentDate SOAP request...\n";
echo "Endpoint: " . $endpoint . "\n\n";

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL            => $endpoint,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $soapRequest,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => [
        'Content-Type: text/xml; charset=utf-8',
        'SOAPAction: "http://tempuri.org/TRNServiceV03/GetRmtoCurrentDate"',
    ],
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_MAXREDIRS      => 5,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false,
    CURLOPT_TIMEOUT        => 30,
    CURLOPT_VERBOSE        => false,
]);

echo "Sending request...\n";
$response = curl_exec($ch);
$error    = curl_error($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($error) {
    echo "✗ CURL Error: " . $error . "\n";
    exit(1);
}

echo "✓ HTTP Status: " . $httpCode . "\n";

if ($httpCode !== 200) {
    echo "✗ Expected HTTP 200, got " . $httpCode . "\n";
    echo "Response: " . substr($response, 0, 500) . "\n";
    exit(1);
}

echo "✓ Response received (" . strlen($response) . " bytes)\n\n";

// Parse response
echo "Parsing response...\n";
$xmlObj = simplexml_load_string($response);
if ($xmlObj === false) {
    echo "✗ Failed to parse XML\n";
    echo "Response: " . $response . "\n";
    exit(1);
}

echo "✓ XML parsed successfully\n";

// Extract date
$xmlObj->registerXPathNamespace('s', 'http://schemas.xmlsoap.org/soap/envelope/');
$xmlObj->registerXPathNamespace('tem', 'http://tempuri.org/');

$result = $xmlObj->xpath('//tem:GetRmtoCurrentDateResult');

if (isset($result[0])) {
    $date = (string) $result[0];
    echo "✓ Date extracted: " . $date . "\n";
    echo "\n=== Test PASSED! ===\n";
} else {
    echo "✗ Failed to extract date from response\n";
    echo "Full response:\n" . $response . "\n";
    exit(1);
}
