<?php
/**
 * View log files - System Admin only
 */

require_once __DIR__ . '/../../includes/auth.php';
requireAuth();
requireSystemAdmin();

$pageTitle = 'System Logs';
$currentPage = 'system';

$logDir = __DIR__ . '/../../logs';
$logFile = $_GET['file'] ?? null;
$searchTerm = trim($_GET['search'] ?? '');
$linesLimit = (int) ($_GET['lines'] ?? 1000);
$content = '';
$filteredContent = '';

if ($logFile && preg_match('/^[a-zA-Z0-9._-]+\.log$/', $logFile)) {
    $filePath = $logDir . '/' . $logFile;
    if (file_exists($filePath) && is_readable($filePath)) {
        $content = file_get_contents($filePath);
        // Limit to last N lines for performance
        $lines = explode("\n", $content);
        if (count($lines) > $linesLimit) {
            $content = implode("\n", array_slice($lines, -$linesLimit));
            $lines = explode("\n", $content);
        }
        
        // Apply search filter if provided
        if ($searchTerm) {
            $filteredLines = array_filter($lines, function($line) use ($searchTerm) {
                return stripos($line, $searchTerm) !== false;
            });
            $filteredContent = implode("\n", $filteredLines);
        } else {
            $filteredContent = $content;
        }
    }
}

$logFiles = [];
$totalLogSize = 0;
if (is_dir($logDir)) {
    $files = glob($logDir . '/*.log');
    foreach ($files as $file) {
        $size = filesize($file);
        $totalLogSize += $size;
        $logFiles[] = [
            'name' => basename($file),
            'size' => $size,
            'modified' => filemtime($file),
        ];
    }
    usort($logFiles, function($a, $b) {
        return $b['modified'] - $a['modified'];
    });
}

require_once __DIR__ . '/../../includes/system-header.php';
?>

<div class="header">
    <h1>System Logs</h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/system" class="link-muted">← Dashboard</a>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>

<!-- Summary Stats -->
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 1.5rem;">
    <div class="card" style="background: #f8fafc;">
        <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.5rem;">Total Log Files</div>
        <div style="font-size: 1.75rem; font-weight: 600; color: #1e293b;"><?= count($logFiles) ?></div>
    </div>
    <div class="card" style="background: #f8fafc;">
        <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.5rem;">Total Size</div>
        <div style="font-size: 1.75rem; font-weight: 600; color: #1e293b;"><?= number_format($totalLogSize / 1024, 2) ?> KB</div>
    </div>
    <?php if ($logFile && !empty($filteredContent)): ?>
    <div class="card" style="background: #f8fafc;">
        <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.5rem;">Lines Displayed</div>
        <div style="font-size: 1.75rem; font-weight: 600; color: #1e293b;"><?= number_format(count(explode("\n", $filteredContent))) ?></div>
    </div>
    <?php endif; ?>
</div>

<div class="card">
    <h2 style="margin-top: 0; margin-bottom: 1rem;">Log Files</h2>
    <?php if (empty($logFiles)): ?>
    <p class="text-muted">No log files found.</p>
    <?php else: ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>File</th>
                    <th style="text-align: right;">Size</th>
                    <th>Last Modified</th>
                    <th style="text-align: center;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($logFiles as $log): ?>
                <tr <?= $logFile === $log['name'] ? 'style="background: #f0f9ff;"' : '' ?>>
                    <td>
                        <div style="display: flex; align-items: center; gap: 0.5rem;">
                            <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24" style="color: #94a3b8;">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
                            </svg>
                            <span style="font-weight: <?= $logFile === $log['name'] ? '600' : '400' ?>;"><?= htmlspecialchars($log['name']) ?></span>
                        </div>
                    </td>
                    <td style="text-align: right; color: #64748b;"><?= number_format($log['size'] / 1024, 2) ?> KB</td>
                    <td style="color: #64748b;"><?= date('Y-m-d H:i:s', $log['modified']) ?></td>
                    <td style="text-align: center;">
                        <a href="<?= BASE_PATH ?>/system/logs?file=<?= urlencode($log['name']) ?>" class="btn btn-sm btn-outline">View</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<?php if ($logFile && !empty($filteredContent)): ?>
<div class="card">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem; flex-wrap: wrap; gap: 1rem;">
        <h2 style="margin: 0;"><?= htmlspecialchars($logFile) ?></h2>
        <div style="display: flex; gap: 0.5rem; align-items: center; flex-wrap: wrap;">
            <form method="get" style="display: flex; gap: 0.5rem; align-items: center;">
                <input type="hidden" name="file" value="<?= htmlspecialchars($logFile) ?>">
                <input type="text" name="search" placeholder="Search logs..." value="<?= htmlspecialchars($searchTerm) ?>" 
                    style="padding: 0.5rem; border: 1px solid var(--border); border-radius: 4px; font-size: 0.875rem; min-width: 200px;">
                <button type="submit" class="btn btn-sm">Search</button>
                <?php if ($searchTerm): ?>
                <a href="<?= BASE_PATH ?>/system/logs?file=<?= urlencode($logFile) ?>" class="btn btn-sm btn-ghost">Clear</a>
                <?php endif; ?>
            </form>
            <form method="get" style="display: flex; gap: 0.5rem; align-items: center;">
                <input type="hidden" name="file" value="<?= htmlspecialchars($logFile) ?>">
                <?php if ($searchTerm): ?>
                <input type="hidden" name="search" value="<?= htmlspecialchars($searchTerm) ?>">
                <?php endif; ?>
                <select name="lines" onchange="this.form.submit()" style="padding: 0.5rem; border: 1px solid var(--border); border-radius: 4px; font-size: 0.875rem;">
                    <option value="500" <?= $linesLimit === 500 ? 'selected' : '' ?>>Last 500 lines</option>
                    <option value="1000" <?= $linesLimit === 1000 ? 'selected' : '' ?>>Last 1,000 lines</option>
                    <option value="2000" <?= $linesLimit === 2000 ? 'selected' : '' ?>>Last 2,000 lines</option>
                    <option value="5000" <?= $linesLimit === 5000 ? 'selected' : '' ?>>Last 5,000 lines</option>
                </select>
            </form>
        </div>
    </div>
    <?php if ($searchTerm): ?>
    <div style="padding: 0.75rem; background: #fef3c7; border: 1px solid #fbbf24; border-radius: 6px; margin-bottom: 1rem;">
        <strong>Filtered results:</strong> Showing lines containing "<?= htmlspecialchars($searchTerm) ?>"
    </div>
    <?php endif; ?>
    <pre id="logContent" style="background: #1e293b; color: #e2e8f0; padding: 1.5rem; border-radius: 6px; overflow-x: auto; font-size: 0.8125rem; line-height: 1.6; max-height: 600px; overflow-y: auto; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;"><?= htmlspecialchars($filteredContent) ?></pre>
    <div style="margin-top: 1rem; padding-top: 1rem; border-top: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; font-size: 0.875rem; color: #64748b;">
        <span><?= number_format(count(explode("\n", $filteredContent))) ?> lines displayed</span>
        <button onclick="copyLogContent()" class="btn btn-sm btn-outline">Copy to Clipboard</button>
    </div>
</div>
<script>
function copyLogContent() {
    const content = document.getElementById('logContent').textContent;
    navigator.clipboard.writeText(content).then(function() {
        alert('Log content copied to clipboard!');
    });
}
</script>
<?php elseif ($logFile): ?>
<div class="card">
    <p class="text-muted">Log file not found or not readable.</p>
</div>
<?php endif; ?>

<?php require_once __DIR__ . '/../../includes/system-footer.php'; ?>
