<?php
/**
 * Validate Generated XML
 * Shows the XML structure to identify issues
 */

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

echo "\n========================================\n";
echo "   XML Structure Validator\n";
echo "========================================\n\n";

// Find latest invoice
$invoices_dir = __DIR__ . '/invoices';
$folders = array_filter(glob($invoices_dir . '/*'), 'is_dir');

if (empty($folders)) {
    echo "❌ No invoices found. Run test_invoice.php first.\n\n";
    exit(1);
}

usort($folders, function($a, $b) {
    return filemtime($b) - filemtime($a);
});

$latest = basename($folders[0]);
$folder = $folders[0];

echo "Latest Invoice: $latest\n";
echo "Folder: $folder\n\n";

// Check which files exist
$files = [
    '3_final.xml' => 'Final XML (sent to ZATCA)',
    '2_signed.xml' => 'Signed XML (before QR)',
    '1_base.xml' => 'Base XML (before signing)'
];

echo "Available files:\n";
foreach ($files as $file => $desc) {
    if (file_exists("$folder/$file")) {
        echo "  ✅ $file - $desc\n";
    } else {
        echo "  ❌ $file - Missing\n";
    }
}

// Load and analyze final XML
$finalXmlPath = "$folder/3_final.xml";

if (!file_exists($finalXmlPath)) {
    echo "\n❌ Final XML not found!\n\n";
    exit(1);
}

echo "\n========================================\n";
echo "   Analyzing Final XML\n";
echo "========================================\n\n";

$xml = file_get_contents($finalXmlPath);

// Parse XML
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;

if (!@$doc->loadXML($xml)) {
    echo "❌ XML is not well-formed!\n";
    echo "Error: " . error_get_last()['message'] . "\n\n";
    exit(1);
}

echo "✅ XML is well-formed\n\n";

// Check structure
$xpath = new DOMXPath($doc);
$xpath->registerNamespace('cac', 'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2');
$xpath->registerNamespace('cbc', 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2');
$xpath->registerNamespace('ext', 'urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2');
$xpath->registerNamespace('ds', 'http://www.w3.org/2000/09/xmldsig#');

echo "Checking ZATCA Required Elements:\n";
echo "-----------------------------------\n";

$checks = [
    'Invoice root element' => '//Invoice',
    'UBLExtensions' => '//ext:UBLExtensions',
    'ProfileID' => '//cbc:ProfileID',
    'UUID' => '//cbc:UUID',
    'IssueDate' => '//cbc:IssueDate',
    'IssueTime' => '//cbc:IssueTime',
    'InvoiceTypeCode' => '//cbc:InvoiceTypeCode',
    'AdditionalDocumentReference (ICV)' => '//cac:AdditionalDocumentReference[cbc:ID="ICV"]',
    'AdditionalDocumentReference (PIH)' => '//cac:AdditionalDocumentReference[cbc:ID="PIH"]',
    'AdditionalDocumentReference (QR)' => '//cac:AdditionalDocumentReference[cbc:ID="QR"]',
    'Signature element' => '//cac:Signature',
    'Digital Signature' => '//ds:Signature',
    'AccountingSupplierParty' => '//cac:AccountingSupplierParty',
    'AccountingCustomerParty' => '//cac:AccountingCustomerParty',
    'TaxTotal' => '//cac:TaxTotal',
    'LegalMonetaryTotal' => '//cac:LegalMonetaryTotal',
    'InvoiceLine' => '//cac:InvoiceLine'
];

$errors = 0;
foreach ($checks as $name => $query) {
    $nodes = $xpath->query($query);
    if ($nodes->length > 0) {
        echo "  ✅ $name: " . $nodes->length . " found\n";
    } else {
        echo "  ❌ $name: MISSING\n";
        $errors++;
    }
}

echo "\n";

// Check for common ZATCA issues
echo "Checking Common ZATCA Issues:\n";
echo "-----------------------------\n";

// Issue 1: Signature position
$sigPosition = $xpath->query('//cac:Signature');
$supplierPosition = $xpath->query('//cac:AccountingSupplierParty');

if ($sigPosition->length > 0 && $supplierPosition->length > 0) {
    $sigNode = $sigPosition->item(0);
    $supplierNode = $supplierPosition->item(0);
    
    // Check if Signature comes before Supplier
    $comparison = $sigNode->compareDocumentPosition($supplierNode);
    
    if ($comparison & DOMNode::DOCUMENT_POSITION_FOLLOWING) {
        echo "  ✅ Signature position: Before supplier (correct)\n";
    } else {
        echo "  ❌ Signature position: After supplier (WRONG)\n";
        echo "     ZATCA requires: Signature must come before AccountingSupplierParty\n";
        $errors++;
    }
}

// Issue 2: Check InvoiceTypeCode format
$typeCode = $xpath->query('//cbc:InvoiceTypeCode')->item(0);
if ($typeCode) {
    $code = $typeCode->nodeValue;
    $name = $typeCode->getAttribute('name');
    
    if (strlen($name) == 7) {
        echo "  ✅ InvoiceTypeCode name: $name (7 digits)\n";
    } else {
        echo "  ❌ InvoiceTypeCode name: $name (should be 7 digits like 0200000)\n";
        $errors++;
    }
}

// Issue 3: Check namespaces
$rootElement = $doc->documentElement;
$requiredNS = [
    'xmlns' => 'urn:oasis:names:specification:ubl:schema:xsd:Invoice-2',
    'xmlns:cac' => 'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2',
    'xmlns:cbc' => 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2',
    'xmlns:ext' => 'urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2'
];

$nsErrors = 0;
foreach ($requiredNS as $prefix => $uri) {
    if ($rootElement->hasAttribute($prefix)) {
        $actualUri = $rootElement->getAttribute($prefix);
        if ($actualUri === $uri) {
            echo "  ✅ Namespace $prefix: correct\n";
        } else {
            echo "  ❌ Namespace $prefix: wrong URI\n";
            $nsErrors++;
        }
    } else {
        echo "  ❌ Namespace $prefix: MISSING\n";
        $nsErrors++;
    }
}

if ($nsErrors > 0) {
    $errors += $nsErrors;
}

echo "\n";

// Show first 100 lines of XML
echo "========================================\n";
echo "   First 100 Lines of XML\n";
echo "========================================\n\n";

$lines = explode("\n", $doc->saveXML());
$preview = array_slice($lines, 0, 100);
echo implode("\n", $preview);
if (count($lines) > 100) {
    echo "\n\n... (" . (count($lines) - 100) . " more lines)\n";
}

echo "\n\n========================================\n";
echo "              SUMMARY\n";
echo "========================================\n\n";

if ($errors == 0) {
    echo "✅ No obvious issues found\n\n";
    echo "The XML structure looks correct.\n";
    echo "The XSD validation error might be due to:\n";
    echo "1. Missing optional but recommended fields\n";
    echo "2. Incorrect data format in some fields\n";
    echo "3. Certificate/signature format issues\n\n";
} else {
    echo "❌ Found $errors issue(s)\n\n";
    echo "Fix these issues and regenerate the invoice.\n\n";
}

echo "Files location:\n";
echo "  $folder\n\n";

echo "To view full XML:\n";
echo "  cat \"$folder/3_final.xml\"\n\n";

echo "========================================\n\n";
?>