<?php
$root = dirname(__DIR__);
$repo = file_get_contents($root . '/app/Repositories/RevenueRepository.php');
$version = json_decode(file_get_contents($root . '/DDB_VERSION.json'), true);

$productionSignature =
    "WITH rev AS (\n" .
    "                SELECT\n" .
    "                    YEARID,\n" .
    "                    VISIT_MONTH AS MONTHID,\n" .
    "                    SUM(NVL(CREDIT_VALUE, 0) + NVL(CASH_VALUE, 0)) AS TOTAL_AMOUNT";

$badProductionSignature =
    "WITH rev AS (\n" .
    "                SELECT\n" .
    "                    YEARID,\n" .
    "                    TO_NUMBER(TO_CHAR(VISIT_END_DATE, 'MM')) AS MONTHID,\n" .
    "                    SUM(NVL(CREDIT_VALUE, 0) + NVL(CASH_VALUE, 0)) AS TOTAL_AMOUNT";

$checks = [
    'version' => isset($version['version']) && $version['version'] === '11.0.11.62',
    'phase' => isset($version['phase']) && $version['phase'] === 'H11.0-P11.1-R45-P2.2.1.3',
    'production_query_fixed' => strpos($repo, $productionSignature) !== false,
    'production_mismatch_absent' => strpos($repo, $badProductionSignature) === false,
    'group_by_matches_month_expression' => strpos($repo, "GROUP BY YEARID, VISIT_MONTH") !== false,
    'bundle_method_present' => strpos($repo, "function monthlyRevenueBundle(") !== false,
    'php7_compatible' => strpos(file_get_contents(__FILE__), 'str_contains(') === false,
];

$failed = [];
foreach ($checks as $name => $ok) {
    if (!$ok) $failed[] = $name;
}
$result = [
    'schema' => 'R45_P2_2_1_3_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);
