<?php
/**
 * Test File: SOAP XML Parser + PDF Download Debugging
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

// Test mode seçimi
$testMode = $_GET['mode'] ?? 'parser';

if ($testMode === 'pdf') {
    echo "<h1>PDF Download Test (Raporu Getir)</h1>";
    echo "<pre style='background:#f0f0f0;padding:15px;'>\n";
    
    // Load debug file
    $debugFile = dirname(dirname(__DIR__)) . '/public/uploads/lab_reports/debug_rapor_10960867_1766873342.xml';
    
    if (!file_exists($debugFile)) {
        echo "❌ Debug file not found: $debugFile\n";
        exit;
    }
    
    $response = file_get_contents($debugFile);
    echo "✓ Loaded debug file: " . strlen($response) . " bytes\n\n";
    
    echo "=== TEST 1: Parse with new parser ===\n";
    
    $nl_to_utf8 = static function(string $s): string {
        $s = preg_replace('/^\xEF\xBB\xBF/', '', $s);
        if (function_exists('mb_check_encoding') && !mb_check_encoding($s, 'UTF-8')) {
            $s = mb_convert_encoding($s, 'UTF-8', 'UTF-8,ISO-8859-9,Windows-1254,ISO-8859-1');
        }
        return $s;
    };

    $nl_parse_hasta_root = static function(string $raw) use ($nl_to_utf8): ?SimpleXMLElement {
        libxml_use_internal_errors(true);
        libxml_clear_errors();
        
        $raw = trim($nl_to_utf8($raw));
        if (empty($raw)) return null;

        if (strpos($raw, '<?xml') === false) {
            $raw = '<?xml version="1.0" encoding="utf-8"?>' . $raw;
        }

        $dom = new DOMDocument();
        if (!$dom->loadXML($raw)) {
            libxml_clear_errors();
            return null;
        }

        $xpath = new DOMXPath($dom);
        $xpath->registerNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/');
        $xpath->registerNamespace('tn', 'http://tenay.com.tr/');

        $resultNodes = $xpath->query('//soap:Body/tn:HastaSonucSorgulaOrnekNoResponse/tn:HastaSonucSorgulaOrnekNoResult');
        
        if ($resultNodes->length === 0) {
            $resultNodes = $xpath->query('//soap:Body/tn:HastaSonucSorgulaReferansResponse/tn:HastaSonucSorgulaReferansResult');
        }

        if ($resultNodes->length === 0) {
            libxml_clear_errors();
            return null;
        }

        $resultNode = $resultNodes->item(0);
        $xml = simplexml_import_dom($resultNode);
        
        libxml_clear_errors();
        return $xml;
    };

    $root = $nl_parse_hasta_root($response);
    
    if (!$root) {
        echo "❌ Parser failed\n";
        exit;
    }
    
    echo "✓ Parser SUCCESS\n";
    $kod = (string)$root->Kod;
    echo "Kod: $kod\n\n";
    
    if ($kod !== '1') {
        echo "❌ Service error (Kod != 1)\n";
        exit;
    }
    
    echo "=== TEST 2: Extract Rapor64 with DOMDocument ===\n";
    
    // DOMDocument ile Rapor64 çek
    libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    $dom->loadXML($response);
    libxml_use_internal_errors(false);
    
    $xpath = new DOMXPath($dom);
    $xpath->registerNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/');
    $xpath->registerNamespace('tn', 'http://tenay.com.tr/');
    
    $rapor64 = '';
    
    // Rapor64 ara
    $rapor64Nodes = $xpath->query('//tn:Rapor64');
    echo "Rapor64 nodes found: " . $rapor64Nodes->length . "\n";
    
    if ($rapor64Nodes->length > 0) {
        $rapor64 = trim($rapor64Nodes->item(0)->nodeValue);
        echo "✓ Rapor64 extracted: " . strlen($rapor64) . " chars\n";
    } else {
        echo "❌ No Rapor64 node found\n";
        
        // Try without namespace
        $rapor64NoNs = $xpath->query('//Rapor64');
        echo "Rapor64 (no namespace) nodes found: " . $rapor64NoNs->length . "\n";
        
        if ($rapor64NoNs->length > 0) {
            $rapor64 = trim($rapor64NoNs->item(0)->nodeValue);
            echo "✓ Rapor64 extracted (no ns): " . strlen($rapor64) . " chars\n";
        }
    }
    
    if (empty($rapor64)) {
        echo "\n❌ Rapor64 is empty\n";
        
        // Debug: Show all element names
        echo "\nAll elements in Result node:\n";
        $allNodes = $xpath->query('//tn:HastaSonucSorgulaOrnekNoResult/*');
        for ($i = 0; $i < min(20, $allNodes->length); $i++) {
            echo "  - " . $allNodes->item($i)->nodeName . "\n";
        }
        exit;
    }
    
    echo "\n=== TEST 3: Decode Base64 ===\n";
    
    $pdf = base64_decode($rapor64, true);
    if (!$pdf) {
        echo "❌ Base64 decode failed\n";
        echo "First 100 chars of rapor64: " . substr($rapor64, 0, 100) . "\n";
        exit;
    }
    
    echo "✓ PDF decoded: " . strlen($pdf) . " bytes\n";
    
    // Check PDF header
    $header = substr($pdf, 0, 5);
    echo "PDF header: " . $header . " (hex: " . bin2hex($header) . ")\n";
    
    if (strpos($pdf, '%PDF') === 0) {
        echo "✓ Valid PDF header\n\n";
        echo "=== SUCCESS! PDF is ready ===\n";
        
        // Save test PDF
        $testFile = dirname(dirname(__DIR__)) . '/public/uploads/lab_reports/test_output.pdf';
        if (file_put_contents($testFile, $pdf)) {
            echo "✓ Test PDF saved: $testFile\n";
            echo "File size: " . filesize($testFile) . " bytes\n";
        }
    } else {
        echo "❌ Invalid PDF header\n";
    }
    
    echo "</pre>\n";
    exit;
}

// Default: Parser test
echo "<h1>SOAP Parser Test</h1>";
echo "<p><a href='?mode=pdf&ornekNo=10956390'>➜ Test PDF Download (Raporu Getir)</a></p>";
echo "<pre style='background:#f0f0f0;padding:15px;'>\n";

// Load the debug XML file
$xmlFile = dirname(dirname(__DIR__)) . '/public/uploads/lab_reports/debug_detail_full_10956390_1766872449.xml';

if (!file_exists($xmlFile)) {
    echo "❌ Debug file not found: $xmlFile\n";
    exit;
}

$raw = file_get_contents($xmlFile);
echo "✓ Loaded file: " . strlen($raw) . " bytes\n\n";

// ===== TEST 1: SimpleXML (direct) =====
echo "=== TEST 1: SimpleXML (simplexml_load_string) ===\n";
libxml_use_internal_errors(true);
libxml_clear_errors();
$xml1 = simplexml_load_string($raw);
echo "Result: " . ($xml1 ? "✓ SUCCESS" : "❌ FAILED") . "\n";
if (!$xml1) {
    $errors = libxml_get_errors();
    echo "Errors: " . count($errors) . "\n";
    foreach ($errors as $err) {
        echo "  - " . trim($err->message) . "\n";
    }
}
libxml_clear_errors();

// ===== TEST 2: DOMDocument =====
echo "\n=== TEST 2: DOMDocument (load from file) ===\n";
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$loadResult = $dom->load($xmlFile);
libxml_use_internal_errors(false);
echo "Result: " . ($loadResult ? "✓ SUCCESS" : "❌ FAILED") . "\n";
if ($loadResult) {
    echo "Root element: " . $dom->documentElement->nodeName . "\n";
}

// ===== TEST 3: simplexml_import_dom (DOMDocument → SimpleXML) =====
echo "\n=== TEST 3: simplexml_import_dom (DOMDocument → SimpleXML) ===\n";
if ($loadResult) {
    $xml2 = simplexml_import_dom($dom);
    echo "Result: " . ($xml2 ? "✓ SUCCESS" : "❌ FAILED") . "\n";
    
    if ($xml2) {
        echo "Root: " . $xml2->getName() . "\n";
        
        // Try xpath
        $result = $xml2->xpath('//*[local-name()="HastaSonucSorgulaOrnekNoResult"]');
        echo "XPath HastaSonucSorgulaOrnekNoResult: " . (isset($result[0]) ? "✓ FOUND" : "❌ NOT FOUND") . "\n";
        
        if (isset($result[0])) {
            echo "  Kod: " . (string)$result[0]->Kod . "\n";
            echo "  OrnekNo: " . (string)$result[0]->OrnekNo . "\n";
            echo "  HastaBilgileri/Adi: " . (string)$result[0]->HastaBilgileri->Adi . "\n";
        }
    }
}

// ===== TEST 4: New Parser Function =====
echo "\n=== TEST 4: New Parser Function (DOMDocument + DOMXPath) ===\n";

$nl_to_utf8 = static function(string $s): string {
    $s = preg_replace('/^\xEF\xBB\xBF/', '', $s);
    if (function_exists('mb_check_encoding') && !mb_check_encoding($s, 'UTF-8')) {
        $s = mb_convert_encoding($s, 'UTF-8', 'UTF-8,ISO-8859-9,Windows-1254,ISO-8859-1');
    }
    return $s;
};

/**
 * Parse SOAP response using DOMDocument (namespace-aware)
 * Returns SimpleXMLElement for compatibility with existing code
 */
$nl_parse_hasta_root = static function(string $raw) use ($nl_to_utf8): ?SimpleXMLElement {
    $raw = trim($nl_to_utf8($raw));
    if (empty($raw)) return null;

    // Add XML declaration if missing
    if (strpos($raw, '<?xml') === false) {
        $raw = '<?xml version="1.0" encoding="utf-8"?>' . $raw;
    }

    libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    
    // Try to load from string
    $success = $dom->loadXML($raw);
    libxml_use_internal_errors(false);
    
    if (!$success) {
        echo "  ❌ DOMDocument::loadXML failed\n";
        return null;
    }
    
    echo "  ✓ DOMDocument::loadXML SUCCESS\n";
    
    // Create XPath for namespace queries
    $xpath = new DOMXPath($dom);
    
    // Register namespaces for XPath
    $xpath->registerNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/');
    $xpath->registerNamespace('tn', 'http://tenay.com.tr/');
    
    // Look for HastaSonucSorgulaOrnekNoResult or HastaSonucSorgulaReferansResult
    $resultNodes = $xpath->query('//soap:Body/tn:HastaSonucSorgulaOrnekNoResponse/tn:HastaSonucSorgulaOrnekNoResult');
    
    if ($resultNodes->length === 0) {
        $resultNodes = $xpath->query('//soap:Body/tn:HastaSonucSorgulaReferansResponse/tn:HastaSonucSorgulaReferansResult');
    }
    
    if ($resultNodes->length === 0) {
        echo "  ❌ No result node found via XPath\n";
        return null;
    }
    
    echo "  ✓ Found result node\n";
    
    // Get the first result node and convert to SimpleXML
    $resultNode = $resultNodes->item(0);
    $xml = simplexml_import_dom($resultNode);
    
    if (!$xml) {
        echo "  ⚠️  simplexml_import_dom failed, using DOMElement directly\n";
        // Return the DOM node as-is for now
        return null; // For this test, show failure
    }
    
    echo "  ✓ Converted to SimpleXML\n";
    return $xml;
};

$root = $nl_parse_hasta_root($raw);
echo "Final result: " . ($root ? "✓ SUCCESS" : "❌ FAILED") . "\n";

if ($root) {
    echo "Root name: " . $root->getName() . "\n";
    
    // Try to extract data
    $kod = (string)$root->Kod;
    $ornek = (string)$root->OrnekNo;
    $adi = (string)$root->HastaBilgileri->Adi;
    
    echo "\nExtracted data:\n";
    echo "  Kod: " . $kod . "\n";
    echo "  OrnekNo: " . $ornek . "\n";
    echo "  Adi: " . $adi . "\n";
    
    // Count tests
    $tests = $root->Tetkikler->TetkikSonuc;
    if ($tests) {
        $count = count($tests);
        echo "  Tests: " . $count . "\n";
    }
}

// ===== TEST 5: Pure DOMDocument approach (no SimpleXML) =====
echo "\n=== TEST 5: Pure DOMDocument + DOMXPath (namespace-aware) ===\n";

libxml_use_internal_errors(true);
$dom2 = new DOMDocument();
$dom2->loadXML($raw);
libxml_use_internal_errors(false);

$xpath2 = new DOMXPath($dom2);
$xpath2->registerNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/');
$xpath2->registerNamespace('tn', 'http://tenay.com.tr/');

// Get Kod
$kodNodes = $xpath2->query('//tn:HastaSonucSorgulaOrnekNoResult/tn:Kod | //tn:HastaSonucSorgulaReferansResult/tn:Kod');
echo "Kod: " . ($kodNodes->length > 0 ? $kodNodes->item(0)->nodeValue : "NOT FOUND") . "\n";

// Get OrnekNo
$ornekNodes = $xpath2->query('//tn:HastaSonucSorgulaOrnekNoResult/tn:OrnekNo | //tn:HastaSonucSorgulaReferansResult/tn:OrnekNo');
echo "OrnekNo: " . ($ornekNodes->length > 0 ? $ornekNodes->item(0)->nodeValue : "NOT FOUND") . "\n";

// Get patient name
$adiNodes = $xpath2->query('//tn:HastaBilgileri/tn:Adi');
echo "Hastanın Adı: " . ($adiNodes->length > 0 ? $adiNodes->item(0)->nodeValue : "NOT FOUND") . "\n";

// Get test count
$testNodes = $xpath2->query('//tn:TetkikSonuc');
echo "Test Sayısı: " . $testNodes->length . "\n";

echo "</pre>\n";
?>
