<?php
/**
 * FLOWB0T NEXUS - System Logs Page
 * View and filter system logs
 */

require_once NEXUS_ROOT . '/core/Database.php';
use Flowb0t\Core\Database;

$db = Database::getInstance();
$pdo = $db->getConnection();

// Pagination
$page = max(1, intval($_GET['p'] ?? 1));
$perPage = 100;
$offset = ($page - 1) * $perPage;

// Filters
$levelFilter = $_GET['level'] ?? '';
$categoryFilter = $_GET['category'] ?? '';
$searchFilter = $_GET['search'] ?? '';

// Build query
$where = "1=1";
$params = [];

if ($levelFilter && in_array($levelFilter, ['DEBUG','INFO','WARNING','ERROR','CRITICAL'])) {
    $where .= " AND log_level = ?";
    $params[] = $levelFilter;
}

if ($categoryFilter) {
    $where .= " AND category = ?";
    $params[] = $categoryFilter;
}

if ($searchFilter) {
    $where .= " AND message LIKE ?";
    $params[] = "%{$searchFilter}%";
}

// Get logs
$totalLogs = 0;
$logs = [];
$categories = [];

try {
    // Count
    $countStmt = $pdo->prepare("SELECT COUNT(*) FROM nexus_logs WHERE {$where}");
    $countStmt->execute($params);
    $totalLogs = (int) $countStmt->fetchColumn();

    // Get logs
    $sql = "SELECT id, job_id, log_level, category, message, context, created_at
            FROM nexus_logs
            WHERE {$where}
            ORDER BY created_at DESC
            LIMIT {$perPage} OFFSET {$offset}";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $logs = $stmt->fetchAll();

    // Get unique categories
    $stmt = $pdo->query("SELECT DISTINCT category FROM nexus_logs ORDER BY category");
    $categories = $stmt->fetchAll(\PDO::FETCH_COLUMN);
} catch (Exception $e) {
    // Table might not exist
}

$totalPages = ceil($totalLogs / $perPage);

// Level counts
$levelCounts = ['DEBUG' => 0, 'INFO' => 0, 'WARNING' => 0, 'ERROR' => 0, 'CRITICAL' => 0];
try {
    $stmt = $pdo->query("SELECT log_level, COUNT(*) as count FROM nexus_logs GROUP BY log_level");
    foreach ($stmt->fetchAll() as $row) {
        $levelCounts[$row['log_level']] = $row['count'];
    }
} catch (Exception $e) {}
?>

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-0">System Logs</h2>
        <small class="text-muted"><?= number_format($totalLogs) ?> log entries</small>
    </div>
    <div class="btn-group">
        <button class="btn btn-outline-warning" onclick="clearLogs('old')">
            <i class="bi bi-trash me-2"></i>Clear Old Logs
        </button>
        <button class="btn btn-outline-danger" onclick="clearLogs('all')">
            <i class="bi bi-trash-fill me-2"></i>Clear All
        </button>
    </div>
</div>

<!-- Level Stats -->
<div class="row g-4 mb-4">
    <div class="col">
        <a href="?page=logs&level=DEBUG" class="stat-card d-block text-decoration-none <?= $levelFilter === 'DEBUG' ? 'border border-secondary' : '' ?>">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <div class="value text-muted"><?= number_format($levelCounts['DEBUG']) ?></div>
                    <div class="label">Debug</div>
                </div>
                <i class="bi bi-bug text-muted" style="font-size: 1.5rem;"></i>
            </div>
        </a>
    </div>
    <div class="col">
        <a href="?page=logs&level=INFO" class="stat-card d-block text-decoration-none <?= $levelFilter === 'INFO' ? 'border border-info' : '' ?>">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <div class="value text-info"><?= number_format($levelCounts['INFO']) ?></div>
                    <div class="label">Info</div>
                </div>
                <i class="bi bi-info-circle text-info" style="font-size: 1.5rem;"></i>
            </div>
        </a>
    </div>
    <div class="col">
        <a href="?page=logs&level=WARNING" class="stat-card d-block text-decoration-none <?= $levelFilter === 'WARNING' ? 'border border-warning' : '' ?>">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <div class="value text-warning"><?= number_format($levelCounts['WARNING']) ?></div>
                    <div class="label">Warning</div>
                </div>
                <i class="bi bi-exclamation-triangle text-warning" style="font-size: 1.5rem;"></i>
            </div>
        </a>
    </div>
    <div class="col">
        <a href="?page=logs&level=ERROR" class="stat-card d-block text-decoration-none <?= $levelFilter === 'ERROR' ? 'border border-danger' : '' ?>">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <div class="value text-danger"><?= number_format($levelCounts['ERROR']) ?></div>
                    <div class="label">Error</div>
                </div>
                <i class="bi bi-x-circle text-danger" style="font-size: 1.5rem;"></i>
            </div>
        </a>
    </div>
    <div class="col">
        <a href="?page=logs&level=CRITICAL" class="stat-card d-block text-decoration-none <?= $levelFilter === 'CRITICAL' ? 'border border-danger' : '' ?>">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <div class="value" style="color: #ff0000;"><?= number_format($levelCounts['CRITICAL']) ?></div>
                    <div class="label">Critical</div>
                </div>
                <i class="bi bi-exclamation-octagon" style="font-size: 1.5rem; color: #ff0000;"></i>
            </div>
        </a>
    </div>
</div>

<!-- Filters -->
<div class="card mb-4">
    <div class="card-body">
        <form method="GET" class="row g-3">
            <input type="hidden" name="page" value="logs">
            <div class="col-md-2">
                <label class="form-label">Level</label>
                <select name="level" class="form-select">
                    <option value="">All Levels</option>
                    <option value="DEBUG" <?= $levelFilter === 'DEBUG' ? 'selected' : '' ?>>Debug</option>
                    <option value="INFO" <?= $levelFilter === 'INFO' ? 'selected' : '' ?>>Info</option>
                    <option value="WARNING" <?= $levelFilter === 'WARNING' ? 'selected' : '' ?>>Warning</option>
                    <option value="ERROR" <?= $levelFilter === 'ERROR' ? 'selected' : '' ?>>Error</option>
                    <option value="CRITICAL" <?= $levelFilter === 'CRITICAL' ? 'selected' : '' ?>>Critical</option>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">Category</label>
                <select name="category" class="form-select">
                    <option value="">All Categories</option>
                    <?php foreach ($categories as $cat): ?>
                        <option value="<?= htmlspecialchars($cat) ?>" <?= $categoryFilter === $cat ? 'selected' : '' ?>>
                            <?= htmlspecialchars($cat) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-5">
                <label class="form-label">Search Message</label>
                <input type="text" name="search" class="form-control" placeholder="Search in log messages..."
                       value="<?= htmlspecialchars($searchFilter) ?>">
            </div>
            <div class="col-md-2 d-flex align-items-end gap-2">
                <button type="submit" class="btn btn-primary flex-grow-1">
                    <i class="bi bi-search"></i> Filter
                </button>
                <a href="?page=logs" class="btn btn-outline-secondary">
                    <i class="bi bi-x"></i>
                </a>
            </div>
        </form>
    </div>
</div>

<!-- Logs Table -->
<div class="card">
    <div class="card-body p-0">
        <?php if (empty($logs)): ?>
            <div class="text-center py-5 text-muted">
                <i class="bi bi-journal-text display-4"></i>
                <p class="mt-3">No logs found</p>
            </div>
        <?php else: ?>
            <div class="log-viewer" style="max-height: none;">
                <?php foreach ($logs as $log): ?>
                    <div class="log-entry d-flex">
                        <span class="log-time me-2" style="white-space: nowrap;">
                            <?= date('Y-m-d H:i:s', strtotime($log['created_at'])) ?>
                        </span>
                        <span class="log-level-<?= $log['log_level'] ?> me-2" style="white-space: nowrap;">
                            [<?= $log['log_level'] ?>]
                        </span>
                        <span class="text-muted me-2" style="white-space: nowrap;">
                            [<?= htmlspecialchars($log['category']) ?>]
                        </span>
                        <span class="flex-grow-1">
                            <?= htmlspecialchars($log['message']) ?>
                            <?php if ($log['context']): ?>
                                <button class="btn btn-sm btn-link text-muted p-0 ms-2" onclick="showContext(<?= $log['id'] ?>)">
                                    <i class="bi bi-info-circle"></i>
                                </button>
                                <pre id="context-<?= $log['id'] ?>" class="d-none mt-2 p-2 bg-dark rounded small"><?= htmlspecialchars(json_encode(json_decode($log['context']), JSON_PRETTY_PRINT)) ?></pre>
                            <?php endif; ?>
                        </span>
                        <?php if ($log['job_id']): ?>
                            <a href="?page=job-detail&id=<?= $log['job_id'] ?>" class="text-muted ms-2">
                                <i class="bi bi-box-arrow-up-right"></i>
                            </a>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            </div>

            <!-- Pagination -->
            <?php if ($totalPages > 1): ?>
                <div class="card-footer d-flex justify-content-between align-items-center">
                    <div class="text-muted">
                        Page <?= $page ?> of <?= number_format($totalPages) ?>
                    </div>
                    <nav>
                        <ul class="pagination pagination-sm mb-0">
                            <?php if ($page > 1): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=logs&p=<?= $page - 1 ?>&level=<?= $levelFilter ?>&category=<?= urlencode($categoryFilter) ?>&search=<?= urlencode($searchFilter) ?>">
                                        <i class="bi bi-chevron-left"></i>
                                    </a>
                                </li>
                            <?php endif; ?>

                            <?php if ($page < $totalPages): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=logs&p=<?= $page + 1 ?>&level=<?= $levelFilter ?>&category=<?= urlencode($categoryFilter) ?>&search=<?= urlencode($searchFilter) ?>">
                                        <i class="bi bi-chevron-right"></i>
                                    </a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
</div>

<script>
function showContext(id) {
    const el = document.getElementById('context-' + id);
    el.classList.toggle('d-none');
}

function clearLogs(type) {
    const msg = type === 'all' ? 'Delete ALL logs?' : 'Delete logs older than 14 days?';
    if (confirm(msg)) {
        NEXUS.api('clear_logs', {type: type}).then(r => {
            if (r.success) {
                NEXUS.toast('Logs cleared', 'success');
                location.reload();
            }
        });
    }
}
</script>
