<?php
/**
 * Demo Oracle — DemoOracleMemoryRepository.
 *
 * Portage de modules/oracle/lib/OracleMemoryRepository.php : requetes de LECTURE
 * uniquement.
 *
 * Convention conservee du module complet : classe sans etat, $conn (ressource
 * OCI8) en premier argument, retour systematique en array — vide en cas
 * d'echec OCI, jamais false, jamais d'exception. La page appelante affiche
 * l'erreur globale.
 */

if (class_exists('DemoOracleMemoryRepository')) return;

class DemoOracleMemoryRepository
{
    public static function fetchSgaInfo($conn): array
    {
        $sql = 'SELECT name, bytes, resizeable FROM V$SGAINFO ORDER BY bytes DESC';
        $rows = [];
        $stm = oci_parse($conn, $sql);
        if (!$stm) return $rows;
        if (@oci_execute($stm, OCI_NO_AUTO_COMMIT)) {
            while ($r = oci_fetch_assoc($stm)) {
                $rows[] = [
                    'name'       => (string)$r['NAME'],
                    'bytes'      => (int)$r['BYTES'],
                    'resizeable' => (string)$r['RESIZEABLE'],
                ];
            }
        }
        oci_free_statement($stm);
        return $rows;
    }

    public static function fetchSgaDynamicComponents($conn): array
    {
        $sql = 'SELECT component, current_size, min_size, max_size, '
             . '       user_specified_size, oper_count, last_oper_type, last_oper_mode '
             . 'FROM   V$SGA_DYNAMIC_COMPONENTS '
             . 'WHERE  current_size > 0 '
             . 'ORDER  BY current_size DESC';
        $rows = [];
        $stm = oci_parse($conn, $sql);
        if (!$stm) return $rows;
        if (@oci_execute($stm, OCI_NO_AUTO_COMMIT)) {
            while ($r = oci_fetch_assoc($stm)) {
                $rows[] = [
                    'component' => (string)$r['COMPONENT'],
                    'current'   => (int)$r['CURRENT_SIZE'],
                    'min'       => (int)$r['MIN_SIZE'],
                    'max'       => (int)$r['MAX_SIZE'],
                    'specified' => (int)$r['USER_SPECIFIED_SIZE'],
                    'ops'       => (int)$r['OPER_COUNT'],
                    'last_type' => (string)$r['LAST_OPER_TYPE'],
                    'last_mode' => (string)$r['LAST_OPER_MODE'],
                ];
            }
        }
        oci_free_statement($stm);
        return $rows;
    }

    public static function fetchPgaStats($conn): array
    {
        $sql = 'SELECT name, value, unit FROM V$PGASTAT';
        $rows = [];
        $stm = oci_parse($conn, $sql);
        if (!$stm) return $rows;
        if (@oci_execute($stm, OCI_NO_AUTO_COMMIT)) {
            while ($r = oci_fetch_assoc($stm)) {
                $rows[(string)$r['NAME']] = [
                    'value' => (float)$r['VALUE'],
                    'unit'  => (string)$r['UNIT'],
                ];
            }
        }
        oci_free_statement($stm);
        return $rows;
    }
}
