<?php

/**
 * NGauge Monitor Dashboard
 *
 * @var yii\web\View $this
 * @var array $data Full MonitorService::all() result
 * @var \PortalPeople\monitor\services\MonitorService $service
 */

use yii\helpers\Html;

$this->title = 'System Monitor';

$statusBadge = static function (string $status): string {
    $map = ['healthy' => 'success', 'ok' => 'success', 'degraded' => 'danger', 'warn' => 'warning', 'error' => 'danger', 'optional' => 'secondary', 'unavailable' => 'danger', 'unknown' => 'secondary'];
    $bs  = $map[$status] ?? 'secondary';
    return '<span class="badge badge-' . $bs . '">' . Html::encode($status) . '</span>';
};
?>

<div class="row body-content">
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h2 class="mb-0">System Monitor</h2>
            <div>
                <small class="text-muted mr-3">Last checked: <span id="monitor-timestamp"><?= Html::encode($data['timestamp']) ?></span></small>
                <?= $statusBadge($data['status']) ?>
                <button class="btn btn-sm btn-outline-secondary ml-2" onclick="refreshDashboard()">Refresh</button>
            </div>
        </div>
    </div>

    <!-- Modules -->
    <div class="col-12 col-lg-6 mb-4">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <strong>API Modules</strong>
                <?php
                $mOk   = count(array_filter($data['modules'], fn($c) => $c['status'] === 'ok'));
                $mFail = count(array_filter($data['modules'], fn($c) => $c['status'] === 'unavailable'));
                echo $statusBadge($mFail > 0 ? 'degraded' : 'healthy');
                ?>
            </div>
            <div class="card-body p-0">
                <table class="table table-sm table-striped mb-0">
                    <thead><tr><th>Module</th><th>Status</th><th>Note</th></tr></thead>
                    <tbody>
                    <?php foreach ($data['modules'] as $moduleId => $m): ?>
                        <tr>
                            <td><code><?= Html::encode($moduleId) ?></code></td>
                            <td><?= $statusBadge($m['status']) ?></td>
                            <td><small><?= Html::encode($m['message']) ?></small></td>
                        </tr>
                    <?php endforeach ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Queues -->
    <div class="col-12 col-lg-6 mb-4">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <strong>Queues</strong>
                <?php
                $qWarn = count(array_filter($data['queues'], fn($q) => in_array($q['status'], ['warn', 'error'], true)));
                echo $statusBadge($qWarn > 0 ? 'degraded' : 'healthy');
                ?>
            </div>
            <div class="card-body p-0">
                <table class="table table-sm table-striped mb-0">
                    <thead>
                        <tr><th>Component</th><th>Channel</th><th class="text-right">Waiting</th><th class="text-right">Reserved</th><th class="text-right">Stalled</th><th>Oldest</th><th>Status</th></tr>
                    </thead>
                    <tbody>
                    <?php foreach ($data['queues'] as $componentId => $q): ?>
                        <tr class="<?= in_array($q['status'], ['warn', 'error'], true) ? 'table-warning' : '' ?>">
                            <td><code><?= Html::encode($componentId) ?></code></td>
                            <td><?= Html::encode($q['channel']) ?></td>
                            <td class="text-right"><?= $q['waiting'] ?></td>
                            <td class="text-right"><?= $q['reserved'] ?></td>
                            <td class="text-right <?= $q['stalled'] > 0 ? 'text-danger font-weight-bold' : '' ?>"><?= $q['stalled'] ?></td>
                            <td><small><?= $q['oldest_waiting_sec'] !== null ? Html::encode($service->humanDuration($q['oldest_waiting_sec'])) : '—' ?></small></td>
                            <td><?= $statusBadge($q['status']) ?></td>
                        </tr>
                    <?php endforeach ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Database -->
    <div class="col-12 col-md-4 mb-4">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <strong>Database</strong>
                <?= $statusBadge($data['database']['ok'] ? 'healthy' : 'degraded') ?>
            </div>
            <div class="card-body">
                <p class="mb-0"><?= Html::encode($data['database']['message']) ?></p>
            </div>
        </div>
    </div>

    <!-- Disk -->
    <div class="col-12 col-md-4 mb-4">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <strong>Disk Usage</strong>
                <?php
                $dWarn = count(array_filter($data['disk'], fn($d) => $d['status'] === 'warn'));
                echo $statusBadge($dWarn > 0 ? 'degraded' : 'healthy');
                ?>
            </div>
            <div class="card-body p-0">
                <table class="table table-sm mb-0">
                    <?php foreach ($data['disk'] as $label => $d): ?>
                        <tr class="<?= $d['status'] === 'warn' ? 'table-warning' : '' ?>">
                            <td><strong><?= Html::encode($label) ?></strong></td>
                            <td>
                                <?php if ($d['used_percent'] !== null): ?>
                                    <div class="progress" style="height:16px;min-width:80px">
                                        <div class="progress-bar <?= $d['used_percent'] >= 80 ? 'bg-danger' : 'bg-success' ?>"
                                             style="width:<?= $d['used_percent'] ?>%">
                                            <?= $d['used_percent'] ?>%
                                        </div>
                                    </div>
                                <?php endif ?>
                            </td>
                            <td><small><?= Html::encode($d['message']) ?></small></td>
                        </tr>
                    <?php endforeach ?>
                </table>
            </div>
        </div>
    </div>

    <!-- Errors -->
    <div class="col-12 col-md-4 mb-4">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <strong>Log Errors</strong>
                <?= $statusBadge($data['errors']['error_count'] > 0 ? 'warn' : 'healthy') ?>
            </div>
            <div class="card-body">
                <?php if (!$data['errors']['found']): ?>
                    <p class="text-muted mb-0">No log file found.</p>
                <?php else: ?>
                    <p class="mb-2">
                        <span class="badge badge-danger"><?= $data['errors']['error_count'] ?> errors</span>
                        <span class="badge badge-warning"><?= $data['errors']['warning_count'] ?> warnings</span>
                    </p>
                    <?php if ($data['errors']['recent_errors'] !== []): ?>
                        <div class="small">
                            <?php foreach ($data['errors']['recent_errors'] as $line): ?>
                                <div class="text-danger text-truncate mb-1" title="<?= Html::encode($line) ?>">
                                    <?= Html::encode(substr($line, 0, 120)) ?>
                                </div>
                            <?php endforeach ?>
                        </div>
                    <?php endif ?>
                <?php endif ?>
            </div>
        </div>
    </div>
</div>

<script>
function refreshDashboard() {
    fetch('<?= \yii\helpers\Url::to(['/ngauge-monitor/web/monitor/all']) ?>')
        .then(r => r.json())
        .then(d => {
            document.getElementById('monitor-timestamp').textContent = d.timestamp;
            window.location.reload();
        })
        .catch(e => console.error('Monitor refresh failed:', e));
}
</script>
