<?php

require_once __DIR__ . '/../core/database.php';
require_once __DIR__ . '/../services/billing/BillingRuntimeGate.php';

$root = dirname(__DIR__);
$serviceFile = $root . '/services/billing/BillingReceivablesService.php';
$source = is_file($serviceFile) ? file_get_contents($serviceFile) : '';
$pdo = db();

$checks = array();
$checks['service file readable'] = $source !== '';
$checks['auto customer resolution before CxC creation'] = strpos($source, '$this->resolveCustomers($environment, (int)$doc[\'id\']);') !== false;
$checks['production customer guard'] = strpos($source, 'La factura emitida no tiene un cliente CRM vinculado; no se creó la cuenta por cobrar.') !== false;
$checks['production income center guard'] = strpos($source, 'La factura emitida no tiene un centro de ingreso; no se creó la cuenta por cobrar.') !== false;
$checks['invoice-only CxC type guard'] = strpos($source, 'array(2, 32, 46)') !== false;

$stmt = $pdo->query("SELECT COUNT(*) FROM facto_documents WHERE BINARY environment=BINARY 'production' AND BINARY document_id=BINARY '866' AND document_number='256' AND CAST(COALESCE(document_type_id,0) AS UNSIGNED)=2 AND receiver_tax_id_code='76792303-1' AND ABS(total_amount-163809.00)<=0.01");
$checks['invoice 866 exact row'] = ((int)$stmt->fetchColumn() === 1);

$stmt = $pdo->query("SELECT COUNT(*) FROM crm_customers WHERE deleted_at IS NULL AND id=11 AND customer_tax_id='76792303-1' AND default_income_center_id=1");
$checks['BYGGVIR exact CRM match and income center'] = ((int)$stmt->fetchColumn() === 1);

$stmt = $pdo->query("SELECT COUNT(*) FROM billing_collections WHERE BINARY environment=BINARY 'production' AND BINARY direction=BINARY 'receivable' AND BINARY facto_document_id=BINARY '866'");
$checks['invoice 866 has no CxC before pilot'] = ((int)$stmt->fetchColumn() === 0);

$stmt = $pdo->query("SELECT COUNT(*) FROM billing_collections c INNER JOIN facto_documents d ON BINARY d.environment=BINARY c.environment AND BINARY d.document_id=BINARY c.facto_document_id WHERE BINARY c.environment=BINARY 'production' AND BINARY c.direction=BINARY 'receivable' AND CAST(COALESCE(d.document_type_id,c.document_type_id,0) AS UNSIGNED) NOT IN (2,32,46) AND c.collection_status <> 'anulado'");
$checks['no active non-invoice CxC after correction'] = ((int)$stmt->fetchColumn() === 0);

$checks['production read allowed'] = billing_runtime_gate_allows('read', 'production') === true;
$checks['production finance blocked before catch-up'] = billing_runtime_gate_allows('finance', 'production') === false;
$checks['production issue blocked'] = billing_runtime_gate_allows('issue', 'production') === false;

$failed = array();
echo "ICYLAB BILLING INVOICE CATCH-UP GUARD DIAGNOSTIC v6.18.1\n";
echo 'Generated at UTC: ' . gmdate('Y-m-d H:i:s') . "\n\n";
foreach ($checks as $label => $ok) {
    echo $label . ': ' . ($ok ? 'PASS' : 'FAIL') . "\n";
    if (!$ok) {
        $failed[] = $label;
    }
}

echo "\nRESULT: " . (empty($failed) ? 'PASS' : 'FAIL') . "\n";
if (!empty($failed)) {
    foreach ($failed as $label) {
        echo '- ' . $label . "\n";
    }
    exit(1);
}
