<?php
/**
 * Demo Oracle — diagnostic ORA-01555 (snapshot too old) (section « diag/ora1555 »).
 *
 * Portage de modules/oracle/_report_diag_ora01555.php, sans retrait :
 * ce rapport est une lecture pure, et le module complet n'y propose aucune
 * action. La demonstration le sert donc a l'identique.
 *
 * Inclus par report.php. Variables : $oraDb, $db, $currentUser, $settings.
 */

require_once __DIR__ . '/lib/DemoOracleOciConnect.php';
require_once __DIR__ . '/lib/DemoOracleDiagRepository.php';

/** @var array      $oraDb       */
/** @var Database   $db          */
/** @var array|null $currentUser */

$ociError   = null;
$fetchError = null;
$conn       = demo_oracle_oci_open($oraDb, $db, $ociError, '', 'diag/ora01555');
$params     = [];
$rows       = [];
$summary    = ['ssolderr_total' => 0, 'nospaceerr_total' => 0, 'maxquerylen_max' => 0];

if (!$conn) {
    $fetchError = $ociError
        ? ('ORA-' . $ociError['code'] . ': ' . $ociError['message'])
        : t('demo_oracle.connect_error');
} else {
    $params = DemoOracleDiagRepository::ora1555GetUndoParams($conn);
    $rows   = DemoOracleDiagRepository::ora1555GetUndoStats($conn, 50);

    foreach ($rows as $r) {
        $summary['ssolderr_total']   += (int)($r['SSOLDERRCNT']   ?? 0);
        $summary['nospaceerr_total'] += (int)($r['NOSPACEERRCNT'] ?? 0);
        $mql = (int)($r['MAXQUERYLEN'] ?? 0);
        if ($mql > $summary['maxquerylen_max']) {
            $summary['maxquerylen_max'] = $mql;
        }
    }

    oci_close($conn);
}

$fmtDur = function (int $sec): string {
    if ($sec <= 0)   return '—';
    if ($sec < 60)   return $sec . 's';
    if ($sec < 3600) return floor($sec / 60) . 'min ' . ($sec % 60) . 's';
    $h = floor($sec / 3600);
    $m = floor(($sec % 3600) / 60);
    return $h . 'h ' . ($m < 10 ? '0' : '') . $m . 'min';
};
View::display(__DIR__ . '/views/report/diag_ora01555.php', [
    'fetchError' => $fetchError,
    'params'     => $params,
    'rows'       => $rows,
    'summary'    => $summary,
    'fmtDur'     => $fmtDur,
]);
