<?php
/**
 * dashboard-container-stats-block.php — the "Live Container Memory Usage" panel:
 * a collapsible accordion containing a searchable / sortable / paginated
 * whp-table, with an AJAX auto-refresh control (Off / 5s / 10s / 30s) backed by
 * api/dashboard-container-stats.php.
 *
 * Expects in scope: $live_container_stats (array) and $show_user_column (bool).
 * Only one instance renders per page (root XOR per-user branch), so the fixed
 * element IDs are safe.
 */
$lcm_cols = !empty($show_user_column) ? 8 : 7;
?>
<hr class="my-4">
<div class="accordion" id="lcmAccordion">
  <div class="accordion-item">
    <h2 class="accordion-header">
      <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#lcmCollapse"
              aria-expanded="true" aria-controls="lcmCollapse">
        <i class="fa fa-bar-chart me-2" aria-hidden="true"></i> <?php echo htmlspecialchars($lcm_heading ?? 'Live Container Memory Usage'); ?>
      </button>
    </h2>
    <div id="lcmCollapse" class="accordion-collapse collapse show">
      <div class="accordion-body">

        <div class="d-flex justify-content-end align-items-center flex-wrap gap-2 mb-2">
          <span class="small text-muted me-auto" id="lcmUpdated" aria-live="polite"></span>
          <label for="lcmInterval" class="small text-muted mb-0">Auto-refresh</label>
          <select id="lcmInterval" class="form-select form-select-sm" style="width:auto" aria-label="Auto-refresh interval">
            <option value="0" selected>Off</option>
            <option value="5">Every 5s</option>
            <option value="10">Every 10s</option>
            <option value="30">Every 30s</option>
          </select>
          <button type="button" id="lcmRefresh" class="btn btn-sm btn-outline-secondary" title="Refresh now" aria-label="Refresh now">
            <i class="fa fa-refresh" aria-hidden="true"></i>
          </button>
        </div>

        <div class="table-responsive">
          <table class="table table-sm table-hover mb-0" id="lcmTable" data-whp-table data-whp-page-size="15">
            <thead>
              <tr>
                <th>Site</th>
                <th>Container</th>
                <?php if (!empty($show_user_column)): ?><th>User</th><?php endif; ?>
                <th class="text-end">Actual</th>
                <th class="text-end">Cache</th>
                <th class="text-end">Total</th>
                <th class="text-end">Limit</th>
                <th>Usage</th>
              </tr>
            </thead>
            <tbody id="lcmTbody">
              <?php include '/docker/whp/web/includes/dashboard-container-stats-rows.php'; ?>
            </tbody>
          </table>
        </div>
        <small class="text-muted mt-2 d-block">Actual = real process memory | Cache = filesystem cache (reclaimable by kernel) | Usage % = actual vs limit</small>

      </div>
    </div>
  </div>
</div>

<script src="/js/whp-table.js?v=<?php echo htmlspecialchars($whp_css_v); ?>"></script>
<script>
(function () {
    var table   = document.getElementById('lcmTable');
    var tbody   = document.getElementById('lcmTbody');
    var sel     = document.getElementById('lcmInterval');
    var btn     = document.getElementById('lcmRefresh');
    var updated = document.getElementById('lcmUpdated');
    if (!table || !tbody || !sel) { return; }

    var COLS = <?php echo (int) $lcm_cols; ?>;
    var timer = null;
    var loading = false;

    function fetchRows() {
        if (loading) { return; }
        // Self-clean if the dashboard was swapped out (SPA navigation).
        if (!document.body.contains(table)) { if (timer) { clearInterval(timer); timer = null; } return; }
        loading = true;
        fetch('/api/dashboard-container-stats.php', { credentials: 'same-origin', headers: { 'X-WHP-Async': '1' } })
            .then(function (r) { if (!r.ok) { throw new Error('HTTP ' + r.status); } return r.text(); })
            .then(function (html) {
                tbody.innerHTML = html;
                if (window.WhpTable && WhpTable.refresh) { WhpTable.refresh(table); }
                if (updated) { updated.textContent = 'Updated ' + new Date().toLocaleTimeString(); }
                if (window.whpRefreshTimes) { try { window.whpRefreshTimes(); } catch (e) {} }
            })
            .catch(function () { /* keep the existing rows on a transient failure */ })
            .finally(function () { loading = false; });
    }

    function applyInterval() {
        if (timer) { clearInterval(timer); timer = null; }
        var s = parseInt(sel.value, 10);
        if (s > 0) { timer = setInterval(fetchRows, s * 1000); }
    }

    // Restore the saved cadence (per browser).
    try {
        var saved = localStorage.getItem('whp_lcm_interval');
        if (saved !== null && sel.querySelector('option[value="' + saved + '"]')) { sel.value = saved; }
    } catch (e) {}

    sel.addEventListener('change', function () {
        try { localStorage.setItem('whp_lcm_interval', sel.value); } catch (e) {}
        applyInterval();
    });
    if (btn) { btn.addEventListener('click', fetchRows); }

    applyInterval();
})();
</script>
