<?php

declare(strict_types=1);

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

use App\Repositories\RevenueRepository;
use App\Services\ChartDataService;

$root = dirname(__DIR__);
$format = strtolower((string)($_GET['format'] ?? 'text'));
$browserMode = (string)($_GET['browser'] ?? '0') === '1';
$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.2.1 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;
$compareYear = filter_var($_GET['compare_year'] ?? null, FILTER_VALIDATE_INT);
$compareYear = $compareYear !== false && $compareYear !== null ? (int)$compareYear : $year - 1;
$hospitalConfig = $hospitals[$hospital] ?? [];

$layoutSource = is_file($root . '/app/Views/layouts/main.php') ? (string)file_get_contents($root . '/app/Views/layouts/main.php') : '';
$viewSource = is_file($root . '/app/Views/revenue/index.php') ? (string)file_get_contents($root . '/app/Views/revenue/index.php') : '';
$chartsSource = is_file($root . '/public/assets/js/charts.js') ? (string)file_get_contents($root . '/public/assets/js/charts.js') : '';
$cssSource = is_file($root . '/public/assets/css/revenue-executive-parity.css') ? (string)file_get_contents($root . '/public/assets/css/revenue-executive-parity.css') : '';
$i18nSource = is_file($root . '/config/i18n.php') ? (string)file_get_contents($root . '/config/i18n.php') : '';
$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 : [];
}

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

$installedRelease = (string)($version['release'] ?? '');
$releaseCompatible = $installedRelease !== '' && version_compare($installedRelease, '10.9.2', '>=');
$add('release_version_compatible', $releaseCompatible, $installedRelease !== '' ? $installedRelease : 'missing');
$add('chart_runtime_asset_loaded', strpos($layoutSource, 'assets/js/charts.js?v=phase10-9-2-revenue-chart-runtime') !== false, 'defer charts.js');
$add('chart_runtime_no_silent_failure', strpos($chartsSource, "data-chart-rendered', 'true") !== false && strpos($chartsSource, 'return {') !== false, 'renderer confirms completion');
$add('five_chart_shells_use_render_state', strpos($viewSource, 'data-revenue-chart-shell') !== false && strpos($viewSource, 'data-chart-render-state') !== false, 'pending/rendered/empty/error');
$add('chart_empty_state_contract', strpos($viewSource, 'data-revenue-chart-empty') !== false && strpos($i18nSource, 'revenue.chart_empty_title') !== false, 'no blank chart when no data');
$add('chart_error_state_contract', strpos($viewSource, 'data-revenue-chart-error') !== false && strpos($i18nSource, 'revenue.chart_error_title') !== false, 'monthly table remains available');
$add('chart_canvas_has_minimum_visual_height', strpos($cssSource, 'min-height: 400px') !== false, '400px desktop');
$add('executive_header_has_no_revenue_technical_copy', strpos($layoutSource, "\$activePage === 'revenue' ? t('revenue.layout_description')") !== false, 'revenue-specific user-facing description');
$add('executive_insight_is_data_driven', strpos($viewSource, 'phase1092_executive_insights') !== false && strpos($viewSource, 'data-executive-insight-source="selected-period-data"') !== false, 'selected period + comparison');
$add('revenue_chart_gate_exposed', strpos($viewSource, 'data-revenue-chart-gate') !== false && strpos($viewSource, '__DDB_REVENUE_CHART_GATE__') !== false, 'browser-readable gate');
$add('legacy_revenue_logic_unchanged', is_file($root . '/app/Repositories/LegacyRevenueRepository.php') && is_file($root . '/app/Services/RevenueParityService.php'), 'parity components preserved');
$add('oracle_write_operations_none', stripos($viewSource . $chartsSource, 'insert into') === false && stripos($viewSource . $chartsSource, 'update ') === false && stripos($viewSource . $chartsSource, 'delete from') === false, 'presentation only');

$payloads = [];
$liveError = '';
if ($runLive || $browserMode) {
    try {
        $repo = new RevenueRepository($hospital);
        $chartService = new ChartDataService();
        $sets = [
            'total' => $repo->monthlyRevenue($year, $compareYear, 'total'),
            'cash' => $repo->monthlyRevenue($year, $compareYear, 'cash'),
            'insurance' => $repo->monthlyRevenue($year, $compareYear, 'insurance'),
            'moh' => $repo->monthlyRevenue($year, $compareYear, 'moh', (string)($hospitalConfig['moh_customer_code'] ?? '')),
            'profit_loss' => $repo->monthlyProfitLoss($year, $compareYear, (int)($hospitalConfig['profit_loss_company_id'] ?? 0)),
        ];
        foreach ($sets as $key => $rows) {
            $payloads[$key] = $chartService->comparePayload($rows, $key, $year, $compareYear);
        }
        $nonEmpty = 0;
        foreach ($payloads as $payload) {
            if (($payload['labels'] ?? []) !== [] && count((array)($payload['series'] ?? [])) >= 2) {
                $nonEmpty++;
            }
        }
        $add('live_five_chart_payloads_available', $nonEmpty === 5, $nonEmpty . ' / 5');
    } catch (Throwable $e) {
        $liveError = $e->getMessage();
        $add('live_five_chart_payloads_available', false, 'Execution error');
    }
}

if ($browserMode) {
    header('Content-Type: text/html; charset=UTF-8');
    ?><!doctype html>
<html lang="en" data-browser-gate="PENDING">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Revenue Chart Browser Render Gate</title>
<style>
body{font-family:Segoe UI,Tahoma,Arial,sans-serif;margin:20px;background:#f5f7fb;color:#17213a}.gate{padding:12px 16px;border-radius:12px;background:#fff;margin-bottom:14px}.grid{display:grid;gap:14px}.card{background:#fff;border:1px solid #dfe6f1;border-radius:18px;padding:12px}canvas{display:block;width:100%;min-height:260px;border:1px solid #e5eaf2;border-radius:14px}.status{font-weight:800}
</style>
<script src="assets/js/charts.js?v=phase10-9-2-revenue-chart-runtime" defer></script>
</head>
<body>
<div class="gate">Browser render gate: <span class="status" id="gate_status">PENDING</span></div>
<div class="grid">
<?php foreach ($payloads as $key => $payload): ?>
<div class="card" data-browser-chart="<?= e((string)$key) ?>" data-render-state="PENDING">
<canvas id="qa_chart_<?= e((string)$key) ?>" height="188"></canvas>
<script type="application/json" id="qa_data_<?= e((string)$key) ?>"><?= json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?></script>
</div>
<?php endforeach; ?>
</div>
<script>
(function(){
function run(){
 var expected=0, rendered=0, failed=0;
 document.querySelectorAll('[data-browser-chart]').forEach(function(card){
  expected++;
  var key=card.getAttribute('data-browser-chart');
  try{
   var node=document.getElementById('qa_data_'+key);
   var payload=JSON.parse(node.textContent||'{}');
   var result=window.renderBarCompareChart('qa_chart_'+key,payload);
   var canvas=document.getElementById('qa_chart_'+key);
   var ok=!!(result&&result.rendered&&canvas&&canvas.getAttribute('data-chart-rendered')==='true'&&Number(canvas.getAttribute('data-chart-label-count')||0)>0&&Number(canvas.getAttribute('data-chart-series-count')||0)>=2);
   card.setAttribute('data-render-state',ok?'PASS':'FAIL');
   if(ok){rendered++;}else{failed++;}
  }catch(e){card.setAttribute('data-render-state','FAIL');failed++;}
 });
 var pass=expected===5&&rendered===5&&failed===0;
 document.documentElement.setAttribute('data-browser-gate',pass?'PASS':'FAIL');
 document.documentElement.setAttribute('data-browser-expected',String(expected));
 document.documentElement.setAttribute('data-browser-rendered',String(rendered));
 document.documentElement.setAttribute('data-browser-failed',String(failed));
 document.getElementById('gate_status').textContent=pass?'PASS':'FAIL';
}
if(document.readyState==='loading'){document.addEventListener('DOMContentLoaded',run,{once:true});}else{run();}
window.addEventListener('load',function(){if(document.documentElement.getAttribute('data-browser-gate')!=='PASS'){run();}},{once:true});
})();
</script>
</body>
</html><?php
    exit;
}

$failures = count(array_filter($checks, static function (array $c): bool { return $c['status'] === 'FAIL'; }));
$result = [
    'schema_version' => '1.0',
    'phase' => '10.9.2.1',
    'title' => 'Revenue Chart Rendering & Executive UX Closure',
    'hospital' => strtoupper($hospital),
    'year' => $year,
    'compare_year' => $compareYear,
    'write_operations' => 'NONE',
    'checks' => $checks,
    'live_error' => $liveError,
    'pass_gates' => count($checks) - $failures,
    'fail_gates' => $failures,
    'status' => $failures === 0 ? 'PASS' : 'FAIL',
];

if ($format === 'json') {
    ini_set('display_errors', '0');
    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 Chart Rendering & Executive UX Closure QA\n";
echo "Phase: 10.9.2.1\n";
echo 'Hospital: ' . strtoupper($hospital) . "\n";
echo "Write operations: NONE\n\n";
echo "QA Gates:\n";
foreach ($checks as $check) {
    echo '[' . $check['status'] . '] ' . str_pad($check['name'], 48) . ' | ' . $check['detail'] . "\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, review, governance, or audit row is modified.\n";
