<?php
require_once __DIR__ . '/../core/config.php';
require_once __DIR__ . '/../core/database.php';

$root = dirname(__DIR__);
$file = $root . '/services/facto/FactoInboxDocumentsSyncService.php';
$source = is_file($file) ? file_get_contents($file) : '';
$checks = array();
$checks['service file readable'] = $source !== '';
$checks['tax identity resolver installed'] = strpos($source, 'resolveInboxTaxIdentity') !== false;
$checks['XML RUTEmisor fallback installed'] = strpos($source, "extractXmlTag(\$xml, 'RUTEmisor')") !== false;
$checks['XML RUTRecep fallback installed'] = strpos($source, "extractXmlTag(\$xml, 'RUTRecep')") !== false;
$checks['company tax fallback installed'] = strpos($source, 'SELECT company_tax_id FROM system_settings') !== false;
$checks['null-safe duplicate update installed'] = strpos($source, "COALESCE(NULLIF(VALUES(issuer_tax_id_code), ''), issuer_tax_id_code)") !== false;
$checks['approved CxP catch-up preserved'] = strpos($source, 'catchUpApprovedPayable') !== false;

try {
    $pdo = db();
    $stmt = $pdo->query("SELECT COUNT(*) FROM facto_inbox_documents WHERE BINARY environment=BINARY 'production' AND id=1456 AND BINARY inbox_document_id=BINARY '521' AND BINARY document_number=BINARY '13308562' AND document_type_id=9 AND ABS(total_amount-12931.00)<=0.01");
    $checks['Chilexpress target row exists'] = ((int)$stmt->fetchColumn() === 1);
    $stmt = $pdo->query("SELECT COUNT(*) FROM crm_customers WHERE deleted_at IS NULL AND UPPER(REPLACE(REPLACE(REPLACE(customer_tax_id,'.',''),'-',''),' ',''))='967564303'");
    $checks['Chilexpress supplier identity unique'] = ((int)$stmt->fetchColumn() === 1);
} catch (Throwable $e) {
    $checks['database checks'] = false;
}

echo "ICYLAB BILLING INBOX TAX IDENTITY DIAGNOSTIC v6.20.3\n";
echo 'Generated at UTC: ' . gmdate('Y-m-d H:i:s') . "\n\n";
$pass = true;
foreach ($checks as $label => $ok) {
    echo $label . ': ' . ($ok ? 'PASS' : 'FAIL') . "\n";
    if (!$ok) $pass = false;
}
echo "\nRESULT: " . ($pass ? 'PASS' : 'FAIL') . "\n";
exit($pass ? 0 : 1);
