<?php
/**
 * View: Oracle SGA & PGA memory report.
 *
 * Variables injected by _report_memory.php via View::display():
 * @var object $settings
 * @var string|null $fetchError
 * @var int    $sgaTotalBytes
 * @var int    $sgaFreeBytes
 * @var int    $sgaBufferBytes
 * @var int    $sgaSharedBytes
 * @var array  $sgaTreemapRows
 * @var array  $sgaDynamic
 * @var array  $pgaStats
 * @var int    $pgaTarget
 * @var int    $pgaAutoTarget
 * @var int    $pgaAllocated
 * @var int    $pgaInuse
 * @var int    $pgaFreeable
 * @var int    $pgaMaxAlloc
 * @var int    $pgaOverAlloc
 * @var float  $cacheHitPct
 * @var string $cacheHitClass
 * @var int    $processCount
 * @var int    $maxProcesses
 * @var int    $bytesProc
 * @var int    $extraBytes
 * @var int    $pgaForAuto
 * @var int    $pgaForManual
 * @var string $sgaTreemapJson
 * @var array  $pgaChartLabels
 * @var array  $pgaChartValues
 */

// Helper needed by view (defined in controller scope)
if (!function_exists('_demo_mem_fmtBytes')) {
    function _demo_mem_fmtBytes(int $b): string {
        if ($b <= 0)          return '0 B';
        if ($b >= 1073741824) return round($b / 1073741824, 2) . ' GB';
        if ($b >= 1048576)    return round($b / 1048576, 1) . ' MB';
        if ($b >= 1024)       return round($b / 1024, 1) . ' KB';
        return $b . ' B';
    }
}
?>

<div class="page-header" style="margin-bottom:.35rem">
    <h1 style="margin:0">&#x1F9E0; <?= t('demo_oracle.mem_title') ?></h1>
</div>

<?php if ($fetchError): ?>
<div class="alert alert-error"><?= htmlspecialchars($fetchError) ?></div>
<?php else: ?>

<!-- ══════════════════════════════════════════════════════════
     SGA — Shared Global Area
══════════════════════════════════════════════════════════ -->
<div class="card">
    <h2 style="margin:0 0 .5rem;font-size:1rem"><?= t('demo_oracle.mem_sga_title') ?></h2>

    <!-- KPI row -->
    <div class="mem-kpi-grid">
        <div class="mem-kpi-card">
            <div class="mem-kpi-label"><?= t('demo_oracle.mem_sga_total') ?></div>
            <div class="mem-kpi-value"><?= _demo_mem_fmtBytes($sgaTotalBytes) ?></div>
        </div>
        <?php if ($sgaBufferBytes > 0): ?>
        <div class="mem-kpi-card">
            <div class="mem-kpi-label">Buffer Cache</div>
            <div class="mem-kpi-value"><?= _demo_mem_fmtBytes($sgaBufferBytes) ?></div>
            <?php if ($sgaTotalBytes > 0): ?>
            <div class="mem-kpi-sub"><?= round($sgaBufferBytes / $sgaTotalBytes * 100) ?>%</div>
            <?php endif; ?>
        </div>
        <?php endif; ?>
        <?php if ($sgaSharedBytes > 0): ?>
        <div class="mem-kpi-card">
            <div class="mem-kpi-label">Shared Pool</div>
            <div class="mem-kpi-value"><?= _demo_mem_fmtBytes($sgaSharedBytes) ?></div>
            <?php if ($sgaTotalBytes > 0): ?>
            <div class="mem-kpi-sub"><?= round($sgaSharedBytes / $sgaTotalBytes * 100) ?>%</div>
            <?php endif; ?>
        </div>
        <?php endif; ?>
        <?php if ($sgaFreeBytes >= 0): ?>
        <div class="mem-kpi-card">
            <div class="mem-kpi-label"><?= t('demo_oracle.mem_sga_free') ?></div>
            <div class="mem-kpi-value <?= $sgaTotalBytes > 0 && $sgaFreeBytes / $sgaTotalBytes < 0.05 ? 'text-warning' : '' ?>">
                <?= _demo_mem_fmtBytes($sgaFreeBytes) ?>
            </div>
            <?php if ($sgaTotalBytes > 0): ?>
            <div class="mem-kpi-sub"><?= round($sgaFreeBytes / $sgaTotalBytes * 100) ?>%</div>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>

    <!-- SGA Treemap -->
    <h3 style="font-size:.95rem;margin:0 0 .35rem"><?= t('demo_oracle.mem_sga_composition') ?></h3>
    <?php if (empty($sgaTreemapRows)): ?>
    <p style="color:var(--color-text-muted)"><?= t('demo_oracle.ts_no_data') ?></p>
    <?php else: ?>
    <div class="ora-chart-container" id="chart-sga-treemap"></div>
    <?php endif; ?>

    <!-- Dynamic components table -->
    <?php if (!empty($sgaDynamic)): ?>
    <h3 style="font-size:.95rem;margin:.75rem 0 .35rem"><?= t('demo_oracle.mem_sga_dynamic') ?></h3>
    <div style="overflow-x:auto">
    <table class="data-table">
        <thead>
            <tr>
                <th><?= t('demo_oracle.mem_col_component') ?></th>
                <th class="text-right"><?= t('demo_oracle.mem_col_specified') ?></th>
                <th class="text-right"><?= t('demo_oracle.mem_col_current') ?></th>
                <th class="text-right"><?= t('demo_oracle.mem_col_min') ?></th>
                <th class="text-right"><?= t('demo_oracle.mem_col_max') ?></th>
                <th class="text-right"><?= t('demo_oracle.mem_col_resizes') ?></th>
                <th><?= t('demo_oracle.mem_col_last_op') ?></th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($sgaDynamic as $c): ?>
            <tr>
                <td><strong><?= htmlspecialchars($c['component']) ?></strong></td>
                <td class="text-right" style="font-family:var(--font-mono,monospace);font-size:.85rem">
                    <?= $c['specified'] > 0 ? _demo_mem_fmtBytes($c['specified']) : '—' ?>
                </td>
                <td class="text-right" style="font-family:var(--font-mono,monospace);font-size:.85rem">
                    <strong><?= _demo_mem_fmtBytes($c['current']) ?></strong>
                </td>
                <td class="text-right" style="font-family:var(--font-mono,monospace);font-size:.85rem;color:var(--color-text-muted)">
                    <?= _demo_mem_fmtBytes($c['min']) ?>
                </td>
                <td class="text-right" style="font-family:var(--font-mono,monospace);font-size:.85rem;color:var(--color-text-muted)">
                    <?= _demo_mem_fmtBytes($c['max']) ?>
                </td>
                <td class="text-right"><?= $c['ops'] ?></td>
                <td>
                    <?php if ($c['last_type'] === 'STATIC'): ?>
                    <span class="badge badge-info" style="font-size:.72em"><?= htmlspecialchars($c['last_type']) ?></span>
                    <?php elseif ($c['last_type'] === 'GROW'): ?>
                    <span class="badge badge-success" style="font-size:.72em"><?= htmlspecialchars($c['last_type']) ?></span>
                    <?php elseif ($c['last_type'] === 'SHRINK'): ?>
                    <span class="badge badge-warning" style="font-size:.72em"><?= htmlspecialchars($c['last_type']) ?></span>
                    <?php else: ?>
                    <span style="font-size:.8rem;color:var(--color-text-muted)"><?= htmlspecialchars($c['last_type']) ?></span>
                    <?php endif; ?>
                    <?php if ($c['last_mode'] && $c['last_mode'] !== 'STATIC'): ?>
                    <span style="font-size:.72em;color:var(--color-text-muted)"><?= htmlspecialchars($c['last_mode']) ?></span>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>
    <?php endif; ?>
</div>

<!-- ══════════════════════════════════════════════════════════
     PGA — Program Global Area
══════════════════════════════════════════════════════════ -->
<div class="card" style="margin-top:.75rem">
    <h2 style="margin:0 0 .5rem;font-size:1rem"><?= t('demo_oracle.mem_pga_title') ?></h2>

    <?php if ($pgaTarget === 0 && !empty($pgaStats)): ?>
    <p class="ora-chart-note">&#x26A0; <?= t('demo_oracle.mem_pga_disabled') ?></p>
    <?php endif; ?>

    <!-- KPI row -->
    <?php if (!empty($pgaStats)): ?>
    <div class="mem-kpi-grid">
        <?php if ($pgaTarget > 0): ?>
        <div class="mem-kpi-card">
            <div class="mem-kpi-label"><?= t('demo_oracle.mem_pga_target') ?></div>
            <div class="mem-kpi-value"><?= _demo_mem_fmtBytes($pgaTarget) ?></div>
            <?php if ($pgaAutoTarget > 0): ?>
            <div class="mem-kpi-sub"><?= t('demo_oracle.mem_pga_auto_target') ?>: <?= _demo_mem_fmtBytes($pgaAutoTarget) ?></div>
            <?php endif; ?>
        </div>
        <?php endif; ?>
        <div class="mem-kpi-card">
            <div class="mem-kpi-label"><?= t('demo_oracle.mem_pga_allocated') ?></div>
            <div class="mem-kpi-value"><?= _demo_mem_fmtBytes($pgaAllocated) ?></div>
            <?php if ($pgaFreeable > 0): ?>
            <div class="mem-kpi-sub"><?= t('demo_oracle.mem_pga_freeable') ?>: <?= _demo_mem_fmtBytes($pgaFreeable) ?></div>
            <?php endif; ?>
        </div>
        <div class="mem-kpi-card">
            <div class="mem-kpi-label"><?= t('demo_oracle.mem_pga_inuse') ?></div>
            <div class="mem-kpi-value"><?= _demo_mem_fmtBytes($pgaInuse) ?></div>
            <?php if ($pgaAllocated > 0): ?>
            <div class="mem-kpi-sub"><?= round($pgaInuse / $pgaAllocated * 100) ?>% <?= t('demo_oracle.mem_pga_allocated') ?></div>
            <?php endif; ?>
        </div>
        <?php if ($cacheHitPct > 0): ?>
        <div class="mem-kpi-card">
            <div class="mem-kpi-label"><?= t('demo_oracle.mem_pga_cache_hit') ?></div>
            <div class="mem-kpi-value <?= $cacheHitClass ?>"><?= number_format($cacheHitPct, 1) ?>%</div>
            <div class="mem-kpi-sub"><?= $processCount ?> <?= t('demo_oracle.mem_pga_processes') ?></div>
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <!-- PGA bar chart -->
    <?php if (!empty($pgaStats)): ?>
    <h3 style="font-size:.95rem;margin:.35rem 0 .35rem"><?= t('demo_oracle.mem_pga_allocated') ?> / <?= t('demo_oracle.mem_pga_inuse') ?></h3>
    <div class="ora-chart-container" id="chart-pga"></div>
    <?php endif; ?>

    <!-- PGA additional stats -->
    <?php if (!empty($pgaStats)): ?>
    <h3 style="font-size:.95rem;margin:.75rem 0 .35rem"><?= t('demo_oracle.mem_pga_title') ?> — détails</h3>
    <div style="overflow-x:auto">
    <table class="data-table" style="max-width:700px">
        <tbody>
            <?php
            $pgaTable = [
                ['oracle.mem_pga_max',        $pgaMaxAlloc,   'bytes'],
                ['oracle.mem_pga_for_auto',   $pgaForAuto,    'bytes'],
                ['oracle.mem_pga_for_manual', $pgaForManual,  'bytes'],
                ['oracle.mem_pga_bytes_proc', $bytesProc,     'bytes'],
                ['oracle.mem_pga_extra_bytes',$extraBytes,    'bytes'],
                ['oracle.mem_pga_processes',  $processCount,  'count'],
                ['oracle.mem_pga_over_alloc', $pgaOverAlloc,  'count'],
            ];
            foreach ($pgaTable as [$key, $val, $unit]):
                if ($val <= 0) continue;
            ?>
            <tr>
                <th style="width:55%;font-weight:normal"><?= t($key) ?></th>
                <td style="font-family:var(--font-mono,monospace);font-size:.88rem">
                    <?php if ($unit === 'bytes'): ?>
                        <strong><?= _demo_mem_fmtBytes($val) ?></strong>
                        <span style="color:var(--color-text-muted);font-size:.8rem">
                            (<?= number_format($val) ?> B)
                        </span>
                    <?php else: ?>
                        <strong <?= ($key === 'oracle.mem_pga_over_alloc' && $val > 0) ? 'class="text-danger"' : '' ?>>
                            <?= number_format($val) ?>
                        </strong>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    </div>
    <?php endif; ?>
</div>

<?php endif; // end fetchError check ?>

<!-- ── Data for JS + CDN scripts ─────────────────────────────────────────── -->
<script>
window.DemoOracleReport = window.DemoOracleReport || {};
window.DemoOracleReport.memory = {
    sgaRows:        <?= $sgaTreemapJson ?>,
    pgaChartLabels: <?= json_encode($pgaChartLabels) ?>,
    pgaChartValues: <?= json_encode($pgaChartValues) ?>
};
</script>
<script src="<?= htmlspecialchars($settings->get('cdn_d3_js',   '')) ?>"></script>
<script src="<?= htmlspecialchars($settings->get('cdn_plot_js', '')) ?>"></script>
<script src="/modules/demo_oracle/assets/js/report-memory.js?v=<?= filemtime(__DIR__ . '/../../assets/js/report-memory.js') ?>"></script>
