<?php
/**
 * View: Oracle tablespaces & redo-log report.
 *
 * Variables injected by _report_tablespaces.php via View::display():
 * @var object $settings
 * @var array  $oraDb
 * @var string|null $fetchError
 * @var array  $tsRows
 * @var array  $tmpRows
 * @var array  $tmpUsage
 * @var array  $logRows
 * @var array  $lfByGroup
 * @var int    $logThreads
 * @var int    $logGroups
 * @var int    $logMembersPerGrp
 * @var int    $logSizeBytes
 * @var int|null $redoSwitches24h
 * @var string $tsJson
 * @var string $tmpJson
 * @var array  $tsRecommendations
 * @var array  $redoRecommendations
 * @var array  $inactiveThreadGroups
 * @var bool   $hasRecommendations
 * @var array  $jsLabels
 */

// Helpers needed by recommendations section (defined in controller scope)
if (!function_exists('_demo_fmtSize')) {
    function _demo_fmtSize(float $bytes): string {
        if ($bytes >= 1099511627776) return round($bytes / 1099511627776, 1) . ' To';
        if ($bytes >= 1073741824)    return round($bytes / 1073741824, 1) . ' Go';
        if ($bytes >= 1048576)       return round($bytes / 1048576) . ' Mo';
        return $bytes . ' o';
    }
}
?>

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

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

<!-- ── Section 1 : Data tablespaces ──────────────────────────────────────── -->
<?php if (empty($tsRows)): ?>
<h2 class="section-title" style="margin-top:.5rem;margin-bottom:.25rem"><?= t('demo_oracle.ts_data_title') ?></h2>
<div class="alert alert-info"><?= t('demo_oracle.ts_no_data') ?></div>
<?php else: ?>
<div style="display:flex;align-items:center;gap:.75rem;flex-wrap:wrap;margin:.5rem 0 .35rem">
    <h2 style="margin:0;font-size:1rem;flex-shrink:0"><?= t('demo_oracle.ts_data_title') ?></h2>
    <?php /* Le tri du graphique est fige sur la taille totale. Les trois boutons
             restent visibles, desactives : masquer le choix laisserait croire
             qu'il n'existe pas. */ ?>
    <div class="ts-sort-bar" style="margin:0;opacity:.55">
        <span class="ts-sort-label"><?= t('demo_oracle.ts_sort_by') ?></span>
        <button class="btn-sort active" data-sort="total" data-target="chart-ts"<?= DemoOracleDemo::disabled() ?>><?= t('demo_oracle.ts_sort_total') ?></button>
        <button class="btn-sort" data-sort="name"  data-target="chart-ts"<?= DemoOracleDemo::disabled() ?>><?= t('demo_oracle.ts_sort_name')  ?></button>
        <button class="btn-sort" data-sort="free"  data-target="chart-ts"<?= DemoOracleDemo::disabled() ?>><?= t('demo_oracle.ts_sort_free')  ?></button>
    </div>
    <?= DemoOracleDemo::badge(t('demo_oracle.ts_sort_hint')) ?>
</div>
<div class="card" style="padding:.75rem">
    <div id="chart-ts" class="ora-chart-container"></div>
</div>
<?php endif; ?>

<!-- ── Section 2 : Temp tablespaces ──────────────────────────────────────── -->
<?php if (empty($tmpRows)): ?>
<h2 class="section-title" style="margin-top:1rem;margin-bottom:.25rem"><?= t('demo_oracle.ts_temp_title') ?></h2>
<div class="alert alert-info"><?= t('demo_oracle.ts_no_data') ?></div>
<?php else: ?>
<div style="display:flex;align-items:center;gap:.75rem;flex-wrap:wrap;margin:1rem 0 .35rem">
    <h2 style="margin:0;font-size:1rem;flex-shrink:0"><?= t('demo_oracle.ts_temp_title') ?></h2>
    <?php /* Le tri du graphique est fige sur la taille totale. Les trois boutons
             restent visibles, desactives : masquer le choix laisserait croire
             qu'il n'existe pas. */ ?>
    <div class="ts-sort-bar" style="margin:0;opacity:.55">
        <span class="ts-sort-label"><?= t('demo_oracle.ts_sort_by') ?></span>
        <button class="btn-sort active" data-sort="total" data-target="chart-tmp"<?= DemoOracleDemo::disabled() ?>><?= t('demo_oracle.ts_sort_total') ?></button>
        <button class="btn-sort" data-sort="name"  data-target="chart-tmp"<?= DemoOracleDemo::disabled() ?>><?= t('demo_oracle.ts_sort_name')  ?></button>
        <button class="btn-sort" data-sort="free"  data-target="chart-tmp"<?= DemoOracleDemo::disabled() ?>><?= t('demo_oracle.ts_sort_free')  ?></button>
    </div>
    <?= DemoOracleDemo::badge(t('demo_oracle.ts_sort_hint')) ?>
</div>
<?php if (!$tmpUsage): ?>
<p class="ora-chart-note"><?= t('demo_oracle.ts_temp_no_usage') ?></p>
<?php endif; ?>
<div class="card" style="padding:.75rem">
    <div id="chart-tmp" class="ora-chart-container"></div>
</div>
<?php endif; ?>

<!-- ── Section 3 : Redo logs ─────────────────────────────────────────────── -->
<div style="display:flex;align-items:center;gap:.75rem;flex-wrap:wrap;margin:1rem 0 .35rem">
    <h2 style="margin:0;font-size:1rem;flex-shrink:0"><?= t('demo_oracle.ts_redo_title') ?></h2>
</div>

<?php if (empty($logRows)): ?>
<div class="alert alert-info"><?= t('demo_oracle.ts_no_data') ?></div>
<?php else: ?>

<!-- Summary cards -->
<div class="stat-grid" style="margin-bottom:.75rem">
    <div class="stat-card">
        <div class="stat-value"><?= $logThreads ?></div>
        <div class="stat-label"><?= t('demo_oracle.redo_threads') ?></div>
    </div>
    <div class="stat-card">
        <div class="stat-value"><?= $logGroups ?></div>
        <div class="stat-label"><?= t('demo_oracle.redo_groups') ?></div>
    </div>
    <div class="stat-card">
        <div class="stat-value"><?= $logMembersPerGrp ?></div>
        <div class="stat-label"><?= t('demo_oracle.redo_members_per_group') ?></div>
    </div>
    <div class="stat-card">
        <div class="stat-value"><?= $logSizeBytes >= 1048576 ? round($logSizeBytes / 1048576) . ' Mo' : $logSizeBytes . ' o' ?></div>
        <div class="stat-label"><?= t('demo_oracle.redo_log_size') ?></div>
    </div>
    <?php if ($redoSwitches24h !== null): ?>
    <div class="stat-card">
        <div class="stat-value"><?= $redoSwitches24h ?></div>
        <div class="stat-label"><?= t('demo_oracle.redo_switches_24h') ?></div>
    </div>
    <div class="stat-card">
        <div class="stat-value"><?= round($redoSwitches24h / 24, 1) ?>/h</div>
        <div class="stat-label"><?= t('demo_oracle.redo_switches_per_hour') ?></div>
    </div>
    <?php endif; ?>
</div>

<!-- Log groups table -->
<div class="card" style="padding:0;overflow-x:auto">
<table class="data-table">
    <thead>
        <tr>
            <th class="text-center"><?= t('demo_oracle.redo_col_thread') ?></th>
            <th class="text-center"><?= t('demo_oracle.redo_col_group') ?></th>
            <th class="text-right"><?= t('demo_oracle.redo_col_size') ?></th>
            <th class="text-center"><?= t('demo_oracle.redo_col_members') ?></th>
            <th class="text-center"><?= t('demo_oracle.redo_col_status') ?></th>
            <th class="text-center"><?= t('demo_oracle.redo_col_archived') ?></th>
            <th><?= t('demo_oracle.redo_col_files') ?></th>
        </tr>
    </thead>
    <tbody>
    <?php foreach ($logRows as $lg):
        $gn       = (int)$lg['GROUP_NUM'];
        $status   = $lg['STATUS'] ?? '—';
        $archived = $lg['ARCHIVED'] ?? '—';
        $members  = $lfByGroup[$gn] ?? [];
        $statusClass = match($status) {
            'CURRENT'  => 'badge-primary',
            'ACTIVE'   => 'badge-warning',
            'INACTIVE' => 'badge-secondary',
            'UNUSED'   => 'badge-secondary',
            default    => 'badge-secondary',
        };
        $sizeBytes = (int)$lg['BYTES'];
        $sizeLabel = $sizeBytes >= 1048576 ? round($sizeBytes / 1048576) . ' Mo' : $sizeBytes . ' o';
    ?>
    <tr>
        <td class="text-center"><?= htmlspecialchars($lg['THREAD_NUM']) ?></td>
        <td class="text-center"><?= $gn ?></td>
        <td class="text-right"><?= $sizeLabel ?></td>
        <td class="text-center"><?= htmlspecialchars($lg['MEMBERS']) ?></td>
        <td class="text-center"><span class="badge <?= $statusClass ?>"><?= htmlspecialchars($status) ?></span></td>
        <td class="text-center">
            <?php if ($archived === 'YES'): ?>
            <span class="badge badge-success">YES</span>
            <?php else: ?>
            <span class="badge badge-secondary">NO</span>
            <?php endif; ?>
        </td>
        <td>
            <?php foreach ($members as $m): ?>
            <div class="redo-member">
                <span class="redo-member-path"><?= htmlspecialchars($m['MEMBER']) ?></span>
                <?php if (!empty($m['STATUS']) && $m['STATUS'] !== null): ?>
                <span class="badge badge-danger" style="font-size:.65em"><?= htmlspecialchars($m['STATUS']) ?></span>
                <?php endif; ?>
                <?php if ($m['TYPE'] === 'STANDBY'): ?>
                <span class="badge badge-info" style="font-size:.65em">STANDBY</span>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </td>
    </tr>
    <?php endforeach; ?>
    </tbody>
</table>
</div>

<?php endif; // end if logRows ?>

<!-- ── Section 4 : Recommendations ─────────────────────────────────────── -->
<?php if ($hasRecommendations): ?>
<h2 class="section-title" style="margin-top:1.25rem;margin-bottom:.35rem"><?= t('demo_oracle.reco_title') ?></h2>

<?php if (!empty($tsRecommendations)): ?>
<h3 style="font-size:.9rem;margin:.75rem 0 .35rem"><?= t('demo_oracle.reco_ts_title') ?></h3>
<div class="card" style="padding:0;overflow-x:auto">
<table class="data-table">
    <thead>
        <tr>
            <th><?= t('demo_oracle.reco_col_tablespace') ?></th>
            <th><?= t('demo_oracle.reco_col_action') ?></th>
            <th><?= t('demo_oracle.reco_col_reason') ?></th>
            <th><?= t('demo_oracle.reco_col_command') ?></th>
        </tr>
    </thead>
    <tbody>
    <?php foreach ($tsRecommendations as $rec): ?>
    <tr>
        <td><strong><?php if (!empty($rec['encrypted'])): ?><i class="fa-solid fa-lock" style="color:var(--color-primary)" title="<?= t('demo_oracle.ts_encrypted') ?>"></i> <?php endif; ?><?= htmlspecialchars($rec['ts']) ?></strong></td>
        <td>
            <?php if ($rec['type'] === 'grow'): ?>
            <span class="badge badge-warning"><?= t('demo_oracle.reco_action_grow') ?></span>
            <?php else: ?>
            <span class="badge badge-info"><?= t('demo_oracle.reco_action_shrink') ?></span>
            <?php endif; ?>
        </td>
        <td><?= htmlspecialchars($rec['reason']) ?></td>
        <td><code class="reco-cmd"><?= htmlspecialchars($rec['cmd']) ?></code></td>
    </tr>
    <?php endforeach; ?>
    </tbody>
</table>
</div>
<?php endif; ?>

<?php if (!empty($redoRecommendations)): ?>
<h3 style="font-size:.9rem;margin:.75rem 0 .35rem"><?= t('demo_oracle.reco_redo_title') ?></h3>
<?php foreach ($redoRecommendations as $rec): ?>
<div class="alert alert-warning" style="margin-bottom:.5rem">
    <strong><?= t('demo_oracle.reco_redo_resize') ?></strong> — <?= htmlspecialchars($rec['reason']) ?>
    <br><?= sprintf(t('demo_oracle.reco_redo_target'), _demo_fmtSize($rec['size'])) ?>
    <div style="margin-top:.4rem">
        <code class="reco-cmd"><?= sprintf(t('demo_oracle.reco_redo_cmd'), _demo_fmtSize($rec['size'])) ?></code>
    </div>
</div>
<?php endforeach; ?>
<?php endif; ?>

<?php if (!empty($inactiveThreadGroups)): ?>
<h3 style="font-size:.9rem;margin:.75rem 0 .35rem"><?= t('demo_oracle.reco_thread_title') ?></h3>
<div class="alert alert-danger" style="margin-bottom:.5rem">
    <strong><?= t('demo_oracle.reco_thread_inactive') ?></strong>
    <p style="margin:.3rem 0"><?= t('demo_oracle.reco_thread_explain') ?></p>
    <?php foreach ($inactiveThreadGroups as $itg): ?>
    <div style="margin-top:.4rem">
        <strong>Thread <?= $itg['thread'] ?></strong> — <?= sprintf(t('demo_oracle.reco_thread_groups'), implode(', ', $itg['groups'])) ?>
        <div style="margin-top:.25rem">
        <?php foreach ($itg['groups'] as $gn): ?>
            <code class="reco-cmd">ALTER DATABASE DROP LOGFILE GROUP <?= $gn ?>;</code><br>
        <?php endforeach; ?>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<p class="ora-chart-note" style="margin-top:.5rem;font-style:italic"><?= t('demo_oracle.reco_disclaimer') ?></p>
<?php endif; // end if hasRecommendations ?>


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

<!-- ── Data for JS + CDN scripts ─────────────────────────────────────────── -->
<script>
window.DemoOracleReport = window.DemoOracleReport || {};
window.DemoOracleReport.tablespaces = {
    tsData:     <?= $tsJson  ?? '[]' ?>,
    tmpData:    <?= $tmpJson ?? '[]' ?>,
    labels:     <?= json_encode($jsLabels) ?>
};
</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-tablespaces.js?v=<?= filemtime(__DIR__ . '/../../assets/js/report-tablespaces.js') ?>"></script>

