<?php
/**
 * Log Viewer Page
 * View system logs from admin panel
 */

require_once '../../config/config.php';
require_once '../../includes/functions.php';
require_once '../../includes/sanitize.php';

requireAdmin();

$logFile = isset($_GET['file']) ? sanitizeFilename($_GET['file']) : 'errors.log';
$action = isset($_GET['action']) ? $_GET['action'] : 'view';
$lines = isset($_GET['lines']) ? (int)$_GET['lines'] : 200;

$allowedLogs = ['errors.log', 'access.log', 'ai.log', 'cron.log'];
if (!in_array($logFile, $allowedLogs)) {
    $logFile = 'errors.log';
}

$logPath = __DIR__ . '/../../logs/' . $logFile;
$logContent = '';
$logSize = 0;

if (file_exists($logPath)) {
    $logSize = filesize($logPath);
    
    if ($action == 'download') {
        header('Content-Type: text/plain');
        header('Content-Disposition: attachment; filename="' . $logFile . '"');
        readfile($logPath);
        exit;
    }
    
    if ($action == 'clear' && isset($_GET['confirm'])) {
        file_put_contents($logPath, '');
        $message = "Log file cleared successfully!";
        header("Location: log-viewer.php?file=$logFile&msg=" . urlencode($message));
        exit;
    }
    
    // Get last N lines
    $lines = max(1, min($lines, 5000));
    $logContent = shell_exec("tail -n $lines $logPath");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>System Log Viewer - Admin Panel</title>
    <link href="../../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../../assets/vendor/fontawesome/css/all.min.css" rel="stylesheet">
    <style>
        .log-container {
            background: #1e1e1e;
            color: #d4d4d4;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            padding: 15px;
            border-radius: 8px;
            max-height: 70vh;
            overflow-y: auto;
        }
        .log-line {
            white-space: pre-wrap;
            word-break: break-all;
            border-bottom: 1px solid #333;
            padding: 3px 0;
        }
        .log-line:hover {
            background: #2d2d2d;
        }
        .log-info { color: #4ec9b0; }
        .log-warning { color: #dcdcaa; }
        .log-error { color: #f48771; }
        .log-debug { color: #9cdcfe; }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                <div class="card mt-3">
                    <div class="card-header">
                        <h4><i class="fas fa-history"></i> System Log Viewer</h4>
                    </div>
                    <div class="card-body">
                        <?php if (isset($_GET['msg'])): ?>
                            <div class="alert alert-success"><?php echo htmlspecialchars($_GET['msg']); ?></div>
                        <?php endif; ?>
                        
                        <form method="GET" class="row mb-3">
                            <div class="col-md-3">
                                <label>Log File</label>
                                <select name="file" class="form-control" onchange="this.form.submit()">
                                    <?php foreach ($allowedLogs as $log): ?>
                                        <option value="<?php echo $log; ?>" <?php echo $logFile == $log ? 'selected' : ''; ?>>
                                            <?php echo $log; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label>Lines</label>
                                <select name="lines" class="form-control" onchange="this.form.submit()">
                                    <option value="50" <?php echo $lines == 50 ? 'selected' : ''; ?>>50</option>
                                    <option value="100" <?php echo $lines == 100 ? 'selected' : ''; ?>>100</option>
                                    <option value="200" <?php echo $lines == 200 ? 'selected' : ''; ?>>200</option>
                                    <option value="500" <?php echo $lines == 500 ? 'selected' : ''; ?>>500</option>
                                    <option value="1000" <?php echo $lines == 1000 ? 'selected' : ''; ?>>1000</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label>&nbsp;</label>
                                <a href="?file=<?php echo $logFile; ?>&action=download" class="btn btn-success w-100">
                                    <i class="fas fa-download"></i> Download
                                </a>
                            </div>
                            <div class="col-md-2">
                                <label>&nbsp;</label>
                                <a href="?file=<?php echo $logFile; ?>&action=clear&confirm=1" class="btn btn-danger w-100" 
                                   onclick="return confirm('Clear this log file?')">
                                    <i class="fas fa-trash"></i> Clear
                                </a>
                            </div>
                            <div class="col-md-3">
                                <label>&nbsp;</label>
                                <button type="button" class="btn btn-secondary w-100" onclick="location.reload()">
                                    <i class="fas fa-sync-alt"></i> Refresh
                                </button>
                            </div>
                        </form>
                        
                        <div class="log-container">
                            <?php if ($logContent): ?>
                                <?php
                                $lines = explode("\n", $logContent);
                                foreach ($lines as $line):
                                    $lineClass = '';
                                    if (strpos($line, 'ERROR') !== false) $lineClass = 'log-error';
                                    elseif (strpos($line, 'WARNING') !== false) $lineClass = 'log-warning';
                                    elseif (strpos($line, 'INFO') !== false) $lineClass = 'log-info';
                                    elseif (strpos($line, 'DEBUG') !== false) $lineClass = 'log-debug';
                                ?>
                                    <div class="log-line <?php echo $lineClass; ?>"><?php echo htmlspecialchars($line); ?></div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="text-muted">No log entries found</div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="mt-3 text-muted">
                            <small>File size: <?php echo formatFileSize($logSize); ?> | Location: <?php echo $logPath; ?></small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>