<?php
$root = dirname(__DIR__);
$version = json_decode(file_get_contents($root . '/DDB_VERSION.json'), true);
$config = file_get_contents($root . '/config/app.php');
$repo = file_get_contents($root . '/app/Repositories/RevenueRepository.php');
$sql = file_get_contents($root . '/database/revenue_monthly_summary_layer.sql');
$job = file_get_contents($root . '/database/revenue_summary_job_integration.sql');
$tool = file_get_contents($root . '/tools/revenue-summary-foundation.php');

$checks = [
    'version' => ($version['version'] ?? '') === '11.0.11.63',
    'phase' => ($version['phase'] ?? '') === 'H11.0-P11.1-R45-P3',
    'feature_flag_default_off' => strpos($config, "USE_REVENUE_SUMMARY', '0'") !== false,
    'freshness_gate' => strpos($repo, 'revenueSummaryStatus') !== false
        && strpos($repo, 'revenue_summary_max_age_hours') !== false,
    'fallback' => strpos($repo, 'batch_fallback') !== false,
    'summary_reader' => strpos($repo, 'DASH_REVENUE_MONTHLY_SUMMARY') !== false,
    'run_control' => strpos($sql, 'DASH_REVENUE_SUMMARY_RUN') !== false,
    'staging' => strpos($sql, 'DASH_REVENUE_MONTHLY_STAGE') !== false,
    'published_summary' => strpos($sql, 'DASH_REVENUE_MONTHLY_SUMMARY') !== false,
    'refresh_procedure' => strpos($sql, 'DASH_REFRESH_REV_MONTH_SUM') !== false,
    'numeric_reconciliation' => strpos($sql, 'Revenue Summary numeric reconciliation failed') !== false,
    'summary_month_count_is_separate' => strpos($sql, 'V_SUMMARY_MONTH_COUNT') !== false,
    'atomic_publish_order' => strpos($sql, "STATUS = 'VALIDATING'") < strpos($sql, "DELETE FROM DASH_REVENUE_MONTHLY_SUMMARY")
        && strpos($sql, "DELETE FROM DASH_REVENUE_MONTHLY_SUMMARY") < strpos($sql, "STATUS = 'READY'"),
    'source_not_modified' => strpos($sql, 'DELETE FROM T_INP_OUTP_REVENUE_BATCH') === false
        && strpos($sql, 'UPDATE T_INP_OUTP_REVENUE_BATCH') === false
        && strpos($sql, 'INSERT INTO T_INP_OUTP_REVENUE_BATCH') === false,
    'job_after_source_procedure' => strpos($job, 'DASH_REFRESH_REV_MONTH_SUM') !== false,
    'installer_php7_compatible' => strpos($tool, 'str_contains(') === false,
];

$failed = [];
foreach ($checks as $name => $ok) {
    if (!$ok) $failed[] = $name;
}
$result = [
    'schema' => 'R45_P3_QA',
    'checks' => $checks,
    'passed' => count($checks) - count($failed),
    'failed' => $failed,
];
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), PHP_EOL;
exit(count($failed) === 0 ? 0 : 1);
