<?php
/**
 * Demo Oracle — point de donnees du rapport temps reel (JSON).
 *
 * Appele par report.php quand ?format=json, AVANT toute mise en page.
 * Portage de la branche JSON de modules/oracle/_report_realtime.php.
 *
 * Les filtres passent par DemoOracleRealtimeFilters::parse(), qui plafonne :
 * une URL forgee (?window=90&state=all&dim=sql_id) rend la meme chose qu'un
 * clic normal. Griser les boutons cote page ne suffirait pas — ce fichier est
 * atteignable directement.
 *
 * Variables disponibles : $oraDb, $db, $currentUser, $settings.
 * Se termine par exit.
 */
require_once __DIR__ . '/lib/DemoOracleOciConnect.php';
require_once __DIR__ . '/lib/DemoOracleAshSource.php';
require_once __DIR__ . '/lib/DemoOracleRealtimeFilters.php';
require_once __DIR__ . '/lib/DemoOracleRealtimeRepository.php';

$f = DemoOracleRealtimeFilters::parse();

/*
 * Cache disque court, repris du module complet. Le rafraichissement est de
 * 10 s cote navigateur ; sans cache, plusieurs visiteurs simultanes de la
 * demonstration lanceraient chacun une douzaine de requetes ASH sur la meme
 * base. La clef inclut tous les filtres qui changent le resultat.
 */
$dbKey = md5(($oraDb['host'] ?? '') . '|' . ($oraDb['service_name'] ?? '')
           . '|' . ($oraDb['username'] ?? ''));
$cacheFile = sys_get_temp_dir() . '/demo_ash_rt_' . $dbKey
           . '_d' . $f['dim']
           . '_xf' . $f['xfDim'] . '_' . substr(md5($f['xfVal']), 0, 8) . '.json';
$cacheTtl = 8;

if (is_file($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTtl) {
    header('X-Cache: HIT');
    readfile($cacheFile);
    exit;
}

$ociError = null;
$conn = demo_oracle_oci_open($oraDb, $db, $ociError, '', 'realtime/data');
if (!$conn) {
    echo json_encode(['error' => $ociError
        ? ('ORA-' . $ociError['code'] . ': ' . $ociError['message'])
        : t('demo_oracle.connect_error')]);
    exit;
}

$src = DemoOracleAshSource::resolve($conn, ($oraDb['conn_type'] ?? '') === 'cloud');
if ($src['source'] === '') {
    oci_close($conn);
    echo json_encode(['error' => 'NO_ASH_SOURCE', 'no_source' => true]);
    exit;
}
$view = $src['view'];

$args = [$conn, $view, $f['window'], $f['svcHash'], $f['svcWhere'],
         $f['stateWhere'], $f['xfWhere'], $f['xfVal'], $f['xfBind']];

$timeline = DemoOracleRealtimeRepository::fetchTimeline(
    $conn, $view, $f['dimExpr'], $f['window'], $f['svcHash'],
    $f['svcWhere'], $f['stateWhere']
);

$topSql         = DemoOracleRealtimeRepository::fetchTopSql(...$args);
$topEvents      = DemoOracleRealtimeRepository::fetchTopEvents(...$args);
$topModules     = DemoOracleRealtimeRepository::fetchTopModules(...$args);
$topActions     = DemoOracleRealtimeRepository::fetchTopActions(...$args);
$topServices    = DemoOracleRealtimeRepository::fetchTopServices(...$args);
$topMachines    = DemoOracleRealtimeRepository::fetchTopMachines(...$args);
$topObjects     = DemoOracleRealtimeRepository::fetchTopObjects(...$args);
$topObjectTypes = DemoOracleRealtimeRepository::fetchTopObjectTypes(...$args);
$topInstances   = DemoOracleRealtimeRepository::fetchTopInstances(...$args);

$topPdbs      = [];
$pdbSupported = DemoOracleRealtimeRepository::isPdbSupported($conn);
if ($pdbSupported) {
    $topPdbs = DemoOracleRealtimeRepository::fetchTopPdbs(...$args);
}

oci_close($conn);

ksort($timeline);
$allDims      = [];
$totalSamples = 0;
foreach ($timeline as $vals) {
    foreach ($vals as $d => $n) {
        $allDims[$d]   = true;
        $totalSamples += $n;
    }
}

$json = json_encode([
    'updated'          => date('H:i:s'),
    'window'           => $f['window'],
    'dim'              => $f['dim'],
    'xf_dim'           => $f['xfDim'],
    'xf_val'           => $f['xfVal'],
    'total_samples'    => $totalSamples,
    'buckets'          => array_keys($timeline),
    'dims'             => array_keys($allDims),
    'timeline'         => $timeline,
    'top_sql'          => $topSql,
    'top_events'       => $topEvents,
    'top_modules'      => $topModules,
    'top_actions'      => $topActions,
    'top_services'     => $topServices,
    'top_machines'     => $topMachines,
    'top_objects'      => $topObjects,
    'top_object_types' => $topObjectTypes,
    'top_instances'    => $topInstances,
    'top_pdbs'         => $topPdbs,
    'pdb_supported'    => $pdbSupported,
    'data_source'      => $src['source'],
]);

@file_put_contents($cacheFile, $json, LOCK_EX);
header('X-Cache: MISS');
echo $json;
exit;
