<?php
/**
 * System Logs Viewer
 * View and manage system logs
 */

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

requireAdmin();

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

// Whitelist allowed log files
$allowedLogs = ['errors.log', 'access.log', 'ai.log', 'cron.log'];

if (!in_array($logFile, $allowedLogs)) {
    $logFile = 'errors.log';
}

// Handle actions
if ($action == 'clear' && isset($_GET['confirm'])) {
    if ($logger->clearLog($logFile)) {
        $message = "Log file cleared successfully!";
    } else {
        $error = "Failed to clear log file";
    }
} elseif ($action == 'download') {
    $logPath = __DIR__ . '/../../logs/' . $logFile;
    if (file_exists($logPath)) {
        header('Content-Type: text/plain');
        header('Content-Disposition: attachment; filename="' . $logFile . '"');
        readfile($logPath);
        exit;
    }
}

$logs = $logger->getLogs($logFile, $lines);
$stats = $logger->getStats();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>System Logs - 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>
        .sidebar {
            min-height: 100vh;
            background: #2c3e50;
        }
        .sidebar .nav-link {
            color: #ecf0f1;
            padding: 12px 20px;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover {
            background: #34495e;
            padding-left: 25px;
        }
        .sidebar .nav-link.active {
            background: #3498db;
        }
        .sidebar .nav-link i {
            margin-right: 10px;
            width: 20px;
        }
        .main-content {
            background: #f8f9fa;
            min-height: 100vh;
        }
        .top-navbar {
            background: white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 15px 20px;
        }
        .log-entry {
            font-family: 'Courier New', monospace;
            font-size: 12px;
            border-bottom: 1px solid #eee;
            padding: 8px 12px;
        }
        .log-level-DEBUG { color: #6c757d; }
        .log-level-INFO { color: #28a745; }
        .log-level-WARNING { color: #ffc107; }
        .log-level-ERROR { color: #dc3545; }
        .log-level-CRITICAL { color: #721c24; background: #f8d7da; }
        .log-timestamp { color: #6c757d; font-size: 11px; }
        .log-message { word-break: break-all; }
        .stats-card {
            background: white;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            text-align: center;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .stats-number {
            font-size: 24px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-2 p-0 sidebar">
                <div class="text-center py-4">
                    <h4 class="text-white">🏥 Admin Panel</h4>
                    <small class="text-muted">System Logs</small>
                </div>
                <nav class="nav flex-column">
                    <a class="nav-link" href="../dashboard.php">
                        <i class="fas fa-tachometer-alt"></i> Dashboard
                    </a>
                    <a class="nav-link" href="../doctors/index.php">
                        <i class="fas fa-user-md"></i> Doctors
                    </a>
                    <a class="nav-link" href="../subscriptions/index.php">
                        <i class="fas fa-credit-card"></i> Subscriptions
                    </a>
                    <a class="nav-link" href="../rubrics/index.php">
                        <i class="fas fa-tree"></i> Rubrics
                    </a>
                    <a class="nav-link" href="../remedies/index.php">
                        <i class="fas fa-capsules"></i> Remedies
                    </a>
                    <a class="nav-link" href="../settings/index.php">
                        <i class="fas fa-cog"></i> Settings
                    </a>
                    <a class="nav-link active" href="logs.php">
                        <i class="fas fa-history"></i> System Logs
                    </a>
                    <a class="nav-link" href="../profile.php">
                        <i class="fas fa-user"></i> My Profile
                    </a>
                    <hr>
                    <a class="nav-link" href="../../logout.php">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </a>
                </nav>
            </div>
            
            <!-- Main Content -->
            <div class="col-md-10 main-content">
                <div class="top-navbar">
                    <div class="d-flex justify-content-between">
                        <h4 class="mb-0"><i class="fas fa-history"></i> System Logs</h4>
                    </div>
                </div>
                
                <div class="p-4">
                    <?php if (isset($message)): ?>
                        <div class="alert alert-success"><?php echo $message; ?></div>
                    <?php endif; ?>
                    
                    <?php if (isset($error)): ?>
                        <div class="alert alert-danger"><?php echo $error; ?></div>
                    <?php endif; ?>
                    
                    <!-- Log Statistics -->
                    <div class="row mb-4">
                        <?php foreach($stats as $file => $stat): ?>
                        <div class="col-md-3">
                            <div class="stats-card">
                                <div class="stats-number"><?php echo $stat['exists'] ? formatFileSize($stat['size']) : '0 B'; ?></div>
                                <div class="text-muted small"><?php echo $file; ?></div>
                                <?php if($stat['modified']): ?>
                                    <div class="small">Updated: <?php echo date('d-m-Y H:i', $stat['modified']); ?></div>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <!-- Log Viewer Controls -->
                    <div class="card mb-4">
                        <div class="card-body">
                            <form method="GET" class="row g-3">
                                <div class="col-md-3">
                                    <label>Log File</label>
                                    <select name="file" class="form-control" onchange="this.form.submit()">
                                        <?php foreach($allowedLogs as $file): ?>
                                            <option value="<?php echo $file; ?>" <?php echo $logFile == $file ? 'selected' : ''; ?>>
                                                <?php echo $file; ?>
                                            </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>
                    </div>
                    
                    <!-- Log Entries -->
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0"><i class="fas fa-file-alt"></i> <?php echo $logFile; ?></h5>
                        </div>
                        <div class="card-body p-0">
                            <?php if (empty($logs)): ?>
                                <div class="text-center text-muted py-5">
                                    <i class="fas fa-inbox fa-3x mb-3"></i>
                                    <p>No log entries found</p>
                                </div>
                            <?php else: ?>
                                <div class="log-entries">
                                    <?php foreach($logs as $log): ?>
                                        <div class="log-entry log-level-<?php echo $log['level']; ?>">
                                            <span class="log-timestamp">[<?php echo $log['timestamp']; ?>]</span>
                                            <span class="log-level">[<?php echo $log['level']; ?>]</span>
                                            <span class="log-message"><?php echo htmlspecialchars($log['message']); ?></span>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <style>
        .log-entries {
            max-height: 600px;
            overflow-y: auto;
        }
        .log-entry:hover {
            background: #f8f9fa;
        }
    </style>
</body>
</html>