<?php

declare(strict_types=1);

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

use App\Services\AdmissionCategoryParityService;

$root = dirname(__DIR__);
$format = strtolower((string)($_GET['format'] ?? 'text'));
$runLive = (string)($_GET['run_live'] ?? '1') !== '0';
if ($format === 'json') {
    ini_set('display_errors', '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. H11.0-P3 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;
$fromDate = (string)($_GET['from_date'] ?? sprintf('%04d-01-01', $year));
$toDate = (string)($_GET['to_date'] ?? sprintf('%04d-03-31', $year));

$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 : [];
}

$currentSource = is_file($root . '/app/Repositories/VisitsRepository.php') ? (string)file_get_contents($root . '/app/Repositories/VisitsRepository.php') : '';
$legacySource = is_file($root . '/app/Repositories/LegacyPatientActivityRepository.php') ? (string)file_get_contents($root . '/app/Repositories/LegacyPatientActivityRepository.php') : '';
$serviceSource = is_file($root . '/app/Services/AdmissionCategoryParityService.php') ? (string)file_get_contents($root . '/app/Services/AdmissionCategoryParityService.php') : '';
$controllerSource = is_file($root . '/app/Controllers/OperationsController.php') ? (string)file_get_contents($root . '/app/Controllers/OperationsController.php') : '';
$viewSource = is_file($root . '/app/Views/operations/module.php') ? (string)file_get_contents($root . '/app/Views/operations/module.php') : '';
$i18nSource = is_file($root . '/config/i18n.php') ? (string)file_get_contents($root . '/config/i18n.php') : '';

$installedRelease = (string)($version['release'] ?? '');
$add('target_release_compatible', $installedRelease !== '' && version_compare($installedRelease, '11.0.3', '>='), $installedRelease);

$add('exact_legacy_body_recovered',
    strpos($legacySource, 'Legacy acty / get_admission_category_type') !== false
    && strpos($legacySource, 'c.pat_cat_type = pt.cat_type_id (+)') !== false
    && strpos($legacySource, 'v.classcode = 1') !== false,
    'Historical dispatcher body recovered');

$add('current_repository_implementation',
    strpos($currentSource, 'public function admissionCategoryMix(') !== false
    && strpos($currentSource, 'LEFT JOIN stp_patcat_type') !== false,
    'VisitsRepository::admissionCategoryMix');

$add('exact_category_mapping',
    strpos($currentSource, "pt.cat_type = 1 THEN 'cash'") !== false
    && strpos($currentSource, "pt.cat_type = 2 THEN 'credit'") !== false
    && strpos($currentSource, "pt.cat_type = 3 THEN 'insurance'") !== false,
    '1=Cash, 2=Credit, 3=Insurance');

$add('exact_join_contract',
    strpos($currentSource, 'v.hosp_id = c.hosp_id') !== false
    && strpos($currentSource, 'v.financlassid = c.financlassid') !== false
    && strpos($currentSource, 'v.patcatid = c.patcatid') !== false
    && strpos($currentSource, 'v.main_patcatid = c.main_patcatid') !== false,
    'RCP_VISIT to REG_COMP_CATEGORY');

$add('year_and_date_range_modes',
    strpos($currentSource, 'acty_year') !== false
    && strpos($currentSource, 'acty_from_date') !== false
    && strpos($currentSource, 'acty_to_date') !== false,
    'year + inclusive date range');

$add('legacy_branch_and_admission_rules',
    strpos($legacySource, 'v.hosp_id IN (1)') !== false
    && strpos($legacySource, 'v.classcode = 1') !== false,
    'HOSP_ID=1; CLASSCODE=1');

$add('real_visits_workspace_integration',
    strpos($controllerSource, 'admissionCategoryMix(') !== false
    && strpos($viewSource, 'data-legacy-function="acty"') !== false,
    'Visits workspace');

$add('bilingual_business_wording',
    strpos($i18nSource, "'visits.admission_category_title' => 'Admissions by payer category'") !== false
    && strpos($i18nSource, "'visits.admission_category_title' => 'حالات التنويم حسب فئة السداد'") !== false,
    'EN + AR');

$writeText = strtolower($currentSource . "\n" . $legacySource . "\n" . $serviceSource);
$hasWrite = preg_match('/\b(insert\s+into|update\s+[a-z0-9_]+\s+set|delete\s+from|create\s+table|alter\s+table)\b/i', $writeText) === 1;
$add('oracle_write_operations_none', !$hasWrite, 'SELECT only');

$parity = null;
$liveError = '';

if ($runLive) {
    try {
        $parity = (new AdmissionCategoryParityService($hospital))->run($year, $fromDate, $toDate);
        $yearResult = $parity['modes']['year']['function'] ?? [];
        $rangeResult = $parity['modes']['date_range']['function'] ?? [];

        $add('live_year_mode_exact_parity',
            ($yearResult['status'] ?? '') === 'PASS'
            && (float)($yearResult['max_difference'] ?? -1) === 0.0,
            'max_difference=' . (string)($yearResult['max_difference'] ?? 'missing'));

        $add('live_date_range_exact_parity',
            ($rangeResult['status'] ?? '') === 'PASS'
            && (float)($rangeResult['max_difference'] ?? -1) === 0.0,
            'max_difference=' . (string)($rangeResult['max_difference'] ?? 'missing'));

        $add('live_two_of_two',
            (int)($parity['functions_checked'] ?? 0) === 2
            && (int)($parity['failures'] ?? 1) === 0,
            (string)($parity['functions_checked'] ?? 0) . '/2');

        $add('full_historical_source_boundary',
            ($parity['source_evidence_boundary'] ?? '') === 'FULL_HISTORICAL_FUNCTION_BODY_RECOVERED',
            (string)($parity['source_evidence_boundary'] ?? 'missing'));

        $add('live_read_only',
            ($parity['write_operations'] ?? '') === 'NONE',
            (string)($parity['write_operations'] ?? 'unknown'));
    } catch (Throwable $e) {
        $liveError = $e->getMessage();
        $add('live_year_mode_exact_parity', false, 'Execution error');
        $add('live_date_range_exact_parity', false, 'Execution error');
        $add('live_two_of_two', false, '0/2');
        $add('full_historical_source_boundary', true, 'FULL_HISTORICAL_FUNCTION_BODY_RECOVERED');
        $add('live_read_only', true, 'NONE');
    }
}

$failures = count(array_filter($checks, static function (array $check): bool {
    return $check['status'] === 'FAIL';
}));

$result = [
    'schema_version' => '1.0',
    'phase' => 'H11.0-P3',
    'title' => 'Admission Category Type Legacy Recovery',
    'hospital' => strtoupper($hospital),
    'year' => $year,
    'range_from' => $fromDate,
    'range_to' => $toDate,
    'run_live' => $runLive,
    'source_evidence_boundary' => 'FULL_HISTORICAL_FUNCTION_BODY_RECOVERED',
    '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 "Admission Category Type Legacy Recovery QA\n";
echo "Phase: H11.0-P3\n";
echo "Hospital: " . strtoupper($hospital) . "\n";
echo "Write operations: NONE\n\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";
