<?php
/**
 * Demo Oracle — diagnostic ORA-04031 (shared pool) (section « diag/ora4031 »).
 *
 * Portage de modules/oracle/_report_diag_ora04031.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/ora04031');
$sgaStats   = [];
$shFree     = 0;
$shResFree  = 0;
$libCache   = [];
$highVer    = [];
$params     = [];

if (!$conn) {
    $fetchError = $ociError
        ? ('ORA-' . $ociError['code'] . ': ' . $ociError['message'])
        : t('demo_oracle.connect_error');
} else {
    $params   = DemoOracleDiagRepository::ora4031GetSgaParams($conn);
    $sgaStats = DemoOracleDiagRepository::ora4031GetSharedPoolTop($conn);
    $spFree   = DemoOracleDiagRepository::ora4031GetSharedPoolFree($conn);
    $shFree    = $spFree['free_mem'];
    $shResFree = $spFree['reserved_free'];
    $libCache = DemoOracleDiagRepository::ora4031GetLibraryCache($conn);
    $highVer  = DemoOracleDiagRepository::ora4031GetHighVersionCount($conn);

    oci_close($conn);
}

$fmtBytes = function ($b): string {
    $b = (float)$b;
    if ($b >= 1073741824) return number_format($b / 1073741824, 2, '.', ' ') . ' GB';
    if ($b >= 1048576)    return number_format($b / 1048576,    1, '.', ' ') . ' MB';
    if ($b >= 1024)       return number_format($b / 1024,       1, '.', ' ') . ' KB';
    return number_format($b, 0, '.', ' ') . ' B';
};
View::display(__DIR__ . '/views/report/diag_ora04031.php', [
    'fetchError' => $fetchError,
    'sgaStats'   => $sgaStats,
    'shFree'     => $shFree,
    'shResFree'  => $shResFree,
    'libCache'   => $libCache,
    'highVer'    => $highVer,
    'params'     => $params,
    'fmtBytes'   => $fmtBytes,
]);
