<?php
declare(strict_types=1);

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

use App\Core\Database;

function out(array $payload, int $exit = 0): void {
    echo json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), PHP_EOL;
    exit($exit);
}

$command = strtolower((string)($argv[1] ?? 'status'));
$hospital = strtolower((string)($argv[2] ?? 'njch'));
$branchId = (int)($argv[3] ?? 1);
$fromDate = (string)($argv[4] ?? date('Y-m-01', strtotime('-36 months')));
$toDate = (string)($argv[5] ?? date('Y-m-t'));
$mohCode = (string)($argv[6] ?? '365');

try {
    if ($command === 'install') {
        $sql = file_get_contents(dirname(__DIR__) . '/database/revenue_monthly_summary_layer.sql');
        if ($sql === false) {
            throw new RuntimeException('Foundation SQL file not found.');
        }

        $blocks = preg_split('/^\s*\/\s*$/m', $sql);
        $executed = 0;
        foreach ($blocks as $block) {
            $block = trim((string)$block);
            if ($block === '' || strpos($block, '-- R45-P3') === 0 && substr_count($block, "\n") < 2) {
                continue;
            }
            $lines = preg_split('/\R/', $block);
            $clean = [];
            foreach ($lines as $line) {
                if (preg_match('/^\s*--/', $line)) continue;
                $clean[] = $line;
            }
            $statement = trim(implode("\n", $clean));
            if ($statement === '') continue;
            Database::execute($hospital, $statement);
            $executed++;
        }
        out(['status' => 'PASS', 'command' => 'install', 'executed_blocks' => $executed]);
    }

    if ($command === 'refresh') {
        Database::execute($hospital, "
            BEGIN
                DASH_REFRESH_REV_MONTH_SUM(
                    P_BRANCH_ID => :branch_id,
                    P_FROM_DATE => TO_DATE(:from_date, 'YYYY-MM-DD'),
                    P_TO_DATE => TO_DATE(:to_date, 'YYYY-MM-DD'),
                    P_MOH_CUSTOMER_CODE => :moh_code
                );
            END;
        ", [
            'branch_id' => $branchId,
            'from_date' => $fromDate,
            'to_date' => $toDate,
            'moh_code' => $mohCode,
        ]);
    }

    $objects = Database::fetchAll($hospital, "
        SELECT OBJECT_NAME, OBJECT_TYPE, STATUS
        FROM USER_OBJECTS
        WHERE OBJECT_NAME IN (
            'DASH_REVENUE_SUMMARY_RUN_SEQ',
            'DASH_REVENUE_SUMMARY_RUN',
            'DASH_REVENUE_MONTHLY_STAGE',
            'DASH_REVENUE_MONTHLY_SUMMARY',
            'DASH_REFRESH_REV_MONTH_SUM'
        )
        ORDER BY OBJECT_TYPE, OBJECT_NAME
    ");

    $latest = null;
    try {
        $latest = Database::fetchOne($hospital, "
            SELECT * FROM (
                SELECT RUN_ID, BRANCH_ID, STATUS, FROM_DATE, TO_DATE,
                       SOURCE_ROW_COUNT, SUMMARY_ROW_COUNT,
                       SOURCE_TOTAL, SUMMARY_TOTAL,
                       SOURCE_CASH, SUMMARY_CASH,
                       SOURCE_INSURANCE, SUMMARY_INSURANCE,
                       SOURCE_MOH, SUMMARY_MOH,
                       STARTED_AT, FINISHED_AT, ERROR_MESSAGE
                FROM DASH_REVENUE_SUMMARY_RUN
                WHERE BRANCH_ID = :branch_id
                ORDER BY RUN_ID DESC
            ) WHERE ROWNUM = 1
        ", ['branch_id' => $branchId]);
    } catch (Throwable $ignore) {}

    $parity = null;
    if ($command === 'refresh' && is_array($latest)) {
        $parity = [
            'status' => (($latest['status'] ?? '') === 'READY') ? 'PASS' : 'FAIL',
            'row_count_equal' => (float)($latest['source_row_count'] ?? -1) === (float)($latest['summary_row_count'] ?? -2),
            'total_diff' => abs((float)($latest['source_total'] ?? 0) - (float)($latest['summary_total'] ?? 0)),
            'cash_diff' => abs((float)($latest['source_cash'] ?? 0) - (float)($latest['summary_cash'] ?? 0)),
            'insurance_diff' => abs((float)($latest['source_insurance'] ?? 0) - (float)($latest['summary_insurance'] ?? 0)),
            'moh_diff' => abs((float)($latest['source_moh'] ?? 0) - (float)($latest['summary_moh'] ?? 0)),
        ];
    }

    out([
        'schema' => 'R45_P3_REVENUE_SUMMARY_FOUNDATION',
        'status' => 'PASS',
        'command' => $command,
        'hospital' => $hospital,
        'branch_id' => $branchId,
        'from_date' => $fromDate,
        'to_date' => $toDate,
        'objects' => $objects,
        'latest_run' => $latest,
        'parity' => $parity,
        'oracle_writes' => in_array($command, ['install','refresh'], true)
            ? 'DASH_REVENUE_* ONLY'
            : 'NONE',
    ]);
} catch (Throwable $e) {
    out([
        'schema' => 'R45_P3_REVENUE_SUMMARY_FOUNDATION',
        'status' => 'FAIL',
        'command' => $command,
        'error' => $e->getMessage(),
    ], 1);
}
