<?php

declare(strict_types=1);

require_once dirname(__DIR__) . '/app/bootstrap.php';

use App\Services\RevenueParityService;

$format = strtolower((string)($_GET['format'] ?? 'text'));
if ($format === 'json') {
    ini_set('display_errors', '0');
}
$runLive = (string)($_GET['run_live'] ?? '1') !== '0';
$hospital = strtolower(trim((string)($_GET['hospital'] ?? 'njch')));
$hospitals = config('hospitals', []);
if (!is_array($hospitals) || !array_key_exists($hospital, $hospitals)) {
    $hospital = 'njch';
}

$remote = (string)($_SERVER['REMOTE_ADDR'] ?? '');
$isLocal = in_array($remote, ['127.0.0.1', '::1', 'localhost', ''], true);
$providedToken = (string)($_GET['token'] ?? '');
$expectedToken = trim((string)env('DDB_QA_TOKEN', ''));
$tokenOk = $expectedToken !== '' && hash_equals($expectedToken, $providedToken);
if (!$isLocal && !$tokenOk) {
    http_response_code(403);
    header('Content-Type: text/plain; charset=UTF-8');
    echo "Forbidden. Phase 10.9 QA is local-only unless DDB_QA_TOKEN is configured.\n";
    exit;
}

$currentYear = (int)date('Y');
$year = filter_var($_GET['year'] ?? null, FILTER_VALIDATE_INT);
$year = $year !== false && $year !== null ? (int)$year : $currentYear - 1;
$compareYear = filter_var($_GET['compare_year'] ?? null, FILTER_VALIDATE_INT);
$compareYear = $compareYear !== false && $compareYear !== null ? (int)$compareYear : $year - 1;
$fromDate = (string)($_GET['from_date'] ?? sprintf('%04d-01-01', $year));
$toDate = (string)($_GET['to_date'] ?? sprintf('%04d-03-31', $year));

$root = dirname(__DIR__);
$checks = [];
$add = static function (string $name, bool $ok, string $detail = '') use (&$checks): void {
    $checks[] = ['name' => $name, 'status' => $ok ? 'PASS' : 'FAIL', 'detail' => $detail];
};

$version = [];
if (is_file($root . '/DDB_VERSION.json')) {
    $decoded = json_decode((string)file_get_contents($root . '/DDB_VERSION.json'), true);
    $version = is_array($decoded) ? $decoded : [];
}

$controllerSource = is_file($root . '/app/Controllers/RevenueController.php') ? (string)file_get_contents($root . '/app/Controllers/RevenueController.php') : '';
$repoSource = is_file($root . '/app/Repositories/RevenueRepository.php') ? (string)file_get_contents($root . '/app/Repositories/RevenueRepository.php') : '';
$legacySource = is_file($root . '/app/Repositories/LegacyRevenueRepository.php') ? (string)file_get_contents($root . '/app/Repositories/LegacyRevenueRepository.php') : '';
$viewSource = is_file($root . '/app/Views/revenue/index.php') ? (string)file_get_contents($root . '/app/Views/revenue/index.php') : '';
$cssSource = is_file($root . '/public/assets/css/revenue-executive-parity.css') ? (string)file_get_contents($root . '/public/assets/css/revenue-executive-parity.css') : '';

$installedRelease = (string)($version['release'] ?? '');
$releaseCompatible = $installedRelease !== '' && version_compare($installedRelease, '10.9.1', '>=');
$add('release_version_compatible', $releaseCompatible, $installedRelease !== '' ? $installedRelease : 'missing');
$add('five_legacy_revenue_functions_mapped',
    strpos($legacySource, 'monthlyRevenue(') !== false && strpos($legacySource, 'monthlyProfitLoss(') !== false,
    'total + cash + insurance + MOH + profit/loss');
$add('year_mode_supported', strpos($viewSource, 'value="year"') !== false && strpos($controllerSource, "['year', 'range']") !== false, 'year');
$add('date_range_mode_supported', strpos($viewSource, 'value="range"') !== false && strpos($repoSource, 'monthlyRevenueRange') !== false, 'from_date + to_date');
$add('same_year_legacy_contract_enforced', strpos($controllerSource, "\$from->format('Y') !== \$to->format('Y')") !== false, 'From and To must be in the same year');
$add('compare_year_supported', strpos($controllerSource, 'compare_year') !== false && strpos($repoSource, 'compareYear') !== false, 'compare_year');
$add('branch_context_supported', strpos($controllerSource, "Request::get('hospital', Auth::hospital())") !== false, 'hospital context');
$add('revenue_permission_enforced', strpos($controllerSource, 'dashboard_role_revenue') !== false && strpos($controllerSource, 'http_response_code(403)') !== false, 'dashboard_role_revenue');
$add('independent_legacy_execution_path', strpos($legacySource, 'RevenueRepository::shiftDateToYear') !== false && strpos($legacySource, 'Database::fetchAll') !== false, 'LegacyRevenueRepository');
$add('executive_typography_standard', strpos($cssSource, 'font-size: 16px') !== false && strpos($cssSource, 'font-size: 17px') !== false, '16px EN / 17px AR');
$add('executive_information_density', strpos($viewSource, 'revenue109-period-strip') !== false && strpos($viewSource, 'revenue109-kpis') !== false, 'status period + 5 primary financial views');
$add('no_oracle_write_operations', stripos($repoSource . $legacySource, 'insert into') === false && stripos($repoSource . $legacySource, 'update ') === false && stripos($repoSource . $legacySource, 'delete from') === false, 'SELECT only');

$parity = null;
$liveError = '';
if ($runLive) {
    try {
        $parity = (new RevenueParityService($hospital))->run($year, $compareYear, $fromDate, $toDate);
        $add('live_year_mode_parity', (($parity['modes']['year']['functions'] ?? []) !== []) && count(array_filter($parity['modes']['year']['functions'], static function (array $r): bool { return ($r['status'] ?? '') !== 'PASS'; })) === 0, '5/5 functions');
        $add('live_date_range_parity', (($parity['modes']['date_range']['functions'] ?? []) !== []) && count(array_filter($parity['modes']['date_range']['functions'], static function (array $r): bool { return ($r['status'] ?? '') !== 'PASS'; })) === 0, '5/5 functions');
        $add('live_parity_total_functions', (int)($parity['functions_checked'] ?? 0) === 10, (string)($parity['functions_checked'] ?? 0) . ' / 10');
        $add('live_parity_write_operations_none', ($parity['write_operations'] ?? '') === 'NONE', (string)($parity['write_operations'] ?? 'unknown'));
    } catch (Throwable $e) {
        $liveError = $e->getMessage();
        $add('live_year_mode_parity', false, 'Execution error');
        $add('live_date_range_parity', false, 'Execution error');
        $add('live_parity_total_functions', false, '0 / 10');
        $add('live_parity_write_operations_none', true, 'NONE');
    }
}

$failures = count(array_filter($checks, static function (array $c): bool { return $c['status'] === 'FAIL'; }));
$result = [
    'schema_version' => '1.0',
    'phase' => '10.9.1',
    'title' => 'Revenue Parity QA JSON Integrity Hotfix',
    'hospital' => strtoupper($hospital),
    'run_live' => $runLive,
    'write_operations' => 'NONE',
    'checks' => $checks,
    'parity' => $parity,
    'live_error' => $liveError,
    'pass_gates' => count($checks) - $failures,
    'fail_gates' => $failures,
    'status' => $failures === 0 ? 'PASS' : 'FAIL',
];

if ($format === 'json') {
    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

header('Content-Type: text/plain; charset=UTF-8');
echo "Revenue Legacy Functional Parity QA\n";
echo "Phase: 10.9.1 - Revenue Parity QA JSON Integrity Hotfix\n";
echo 'Hospital: ' . strtoupper($hospital) . "\n";
echo "Executive standard: Executive Leadership UI Standard v1.0\n";
echo "Write operations: NONE\n\n";
echo "QA Gates:\n";
foreach ($checks as $check) {
    echo '[' . $check['status'] . '] ' . str_pad($check['name'], 42) . ' | ' . $check['detail'] . "\n";
}
if (is_array($parity)) {
    echo "\nParity Summary:\n";
    foreach (['year' => 'YEAR', 'date_range' => 'DATE RANGE'] as $modeKey => $modeLabel) {
        foreach (($parity['modes'][$modeKey]['functions'] ?? []) as $fn) {
            echo '[' . ($fn['status'] ?? 'FAIL') . '] ' . str_pad($modeLabel . ' / ' . (string)($fn['legacy_function'] ?? ''), 48)
                . ' | current diff=' . number_format((float)($fn['current_total_difference'] ?? 0), 2, '.', '')
                . ' | compare diff=' . number_format((float)($fn['compare_total_difference'] ?? 0), 2, '.', '')
                . "\n";
        }
    }
}
if ($liveError !== '') {
    echo "\nLive execution error: " . $liveError . "\n";
}
echo "\nQA result: " . $result['status'] . "\n";
echo 'PASS gates: ' . $result['pass_gates'] . "\n";
echo 'FAIL gates: ' . $result['fail_gates'] . "\n";
echo "QA is read-only. No Oracle row, review row, governance row or audit row is modified.\n";
