<?php
// admin/monitor.php
session_start();
if (!($_SESSION['admin_logged_in'] ?? false)) {
    header('Location: login.php');
    exit;
}

require_once __DIR__ . '/../lib/Logger.php';
require_once __DIR__ . '/../lib/Monitor.php';

$config = require __DIR__ . '/../config.php';
$pdo = new PDO(
    "mysql:host={$config['db_host']};dbname={$config['db_name']};charset=utf8mb4",
    $config['db_user'],
    $config['db_pass'],
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);

$monitor = new Monitor($pdo);
$health = $monitor->checkSystemHealth();
$recent_logs = Logger::getRecentLogs(50);
?>
<!DOCTYPE html>
<html>
<head>
    <title>Мониторинг системы</title>
    <meta charset="utf-8">
    <style>
        body { font-family: sans-serif; padding: 20px; background: #f5f5f5; }
        .status-card { background: white; padding: 20px; margin: 15px 0; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
        .status-healthy { border-left: 4px solid #27ae60; }
        .status-warning { border-left: 4px solid #f39c12; }
        .status-error { border-left: 4px solid #e74c3c; }
        .status-stale { border-left: 4px solid #e67e22; }
        .log-entry { padding: 8px; border-bottom: 1px solid #eee; font-family: monospace; font-size: 0.9em; }
        .log-error { background: #fee; }
        .log-warning { background: #ffeaa7; }
    </style>
</head>
<body>
    <h1>📊 Мониторинг системы</h1>
    
    <div class="status-card">
        <h2>Здоровье системы</h2>
        <?php foreach ($health as $component => $status): ?>
            <?php 
            $status_class = 'unknown';
            if (is_array($status)) {
                $status_class = $status['status'] ?? 'unknown';
            }
            ?>
            <div class="status-<?= htmlspecialchars($status_class) ?>">
                <strong><?= ucfirst(htmlspecialchars($component)) ?>:</strong> 
                <?php if (is_array($status)): ?>
                    <?= htmlspecialchars(json_encode($status, JSON_UNESCAPED_UNICODE)) ?>
                <?php else: ?>
                    <?= htmlspecialchars($status) ?>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
    </div>
    
    <div class="status-card">
        <h2>Последние логи (50 записей)</h2>
        <?php if (empty($recent_logs)): ?>
            <div class="log-entry">Нет записей в логе</div>
        <?php else: ?>
            <?php foreach ($recent_logs as $log): ?>
                <div class="log-entry <?= strpos($log, '[ERROR]') !== false ? 'log-error' : (strpos($log, '[WARNING]') !== false ? 'log-warning' : '') ?>">
                    <?= htmlspecialchars($log) ?>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
    
    <a href="index.php">← Назад к админке</a>
</body>
</html>