<?php
/**
 * Real-time Error Monitor
 * Access this page to see recent 404 errors and system issues
 */

date_default_timezone_set('Asia/Colombo');
session_start();

// Simple admin check
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$log_file = __DIR__ . '/404_errors.log';
$error_log = __DIR__ . '/error_log';

// Get last 50 lines from 404 log
function getRecentErrors($file, $lines = 50) {
    if (!file_exists($file)) {
        return [];
    }
    
    $content = file($file);
    return array_slice($content, -($lines * 5)); // Each error is ~5 lines
}

$recent_404s = getRecentErrors($log_file);
$recent_errors = getRecentErrors($error_log, 20);

// Check file permissions
$checks = [
    'config.php' => file_exists(__DIR__ . '/config.php'),
    'auth.php' => file_exists(__DIR__ . '/auth.php'),
    'api/enhanced_stats.php' => file_exists(__DIR__ . '/api/enhanced_stats.php'),
    'api/low_stock.php' => file_exists(__DIR__ . '/api/low_stock.php'),
    'products/products.php' => file_exists(__DIR__ . '/products/products.php'),
];

?>
<!DOCTYPE html>
<html>
<head>
    <title>System Monitor - Dilrukshi Tex</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        body { background: #f5f5f5; }
        .monitor-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .status-ok { color: #28a745; }
        .status-error { color: #dc3545; }
        .log-entry {
            font-family: 'Courier New', monospace;
            font-size: 12px;
            background: #f8f9fa;
            padding: 10px;
            border-left: 3px solid #007bff;
            margin-bottom: 10px;
        }
        .error-entry {
            border-left-color: #dc3545;
        }
        .navbar { background: #667eea !important; }
    </style>
    <script>
        // Auto-refresh every 30 seconds
        setTimeout(() => location.reload(), 30000);
    </script>
</head>
<body>
    <nav class="navbar navbar-dark">
        <div class="container">
            <span class="navbar-brand">
                <i class="fas fa-heartbeat"></i> System Monitor
            </span>
            <span class="text-white">
                <i class="fas fa-sync-alt"></i> Auto-refresh in 30s
            </span>
        </div>
    </nav>

    <div class="container mt-4">
        <!-- Quick Stats -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="monitor-card text-center">
                    <h4><?= count($recent_404s) / 5 ?></h4>
                    <small>Recent 404 Errors</small>
                </div>
            </div>
            <div class="col-md-3">
                <div class="monitor-card text-center">
                    <h4><?= count($recent_errors) ?></h4>
                    <small>PHP Errors</small>
                </div>
            </div>
            <div class="col-md-3">
                <div class="monitor-card text-center">
                    <h4><?= session_status() === PHP_SESSION_ACTIVE ? 'Active' : 'Inactive' ?></h4>
                    <small>Session Status</small>
                </div>
            </div>
            <div class="col-md-3">
                <div class="monitor-card text-center">
                    <h4><?= date('H:i:s') ?></h4>
                    <small>Current Time</small>
                </div>
            </div>
        </div>

        <!-- File Existence Checks -->
        <div class="monitor-card">
            <h5><i class="fas fa-check-circle"></i> Critical Files Status</h5>
            <table class="table table-sm">
                <?php foreach ($checks as $file => $exists): ?>
                <tr>
                    <td>
                        <i class="fas fa-<?= $exists ? 'check' : 'times' ?> <?= $exists ? 'status-ok' : 'status-error' ?>"></i>
                        <?= htmlspecialchars($file) ?>
                    </td>
                    <td class="text-end">
                        <span class="badge bg-<?= $exists ? 'success' : 'danger' ?>">
                            <?= $exists ? 'OK' : 'MISSING' ?>
                        </span>
                    </td>
                </tr>
                <?php endforeach; ?>
            </table>
        </div>

        <!-- Recent 404 Errors -->
        <div class="monitor-card">
            <h5><i class="fas fa-exclamation-triangle text-warning"></i> Recent 404 Errors</h5>
            <?php if (empty($recent_404s)): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i> No 404 errors logged!
                </div>
            <?php else: ?>
                <div style="max-height: 400px; overflow-y: auto;">
                    <?php 
                    $entries = implode('', $recent_404s);
                    $entries = explode(str_repeat('-', 80), $entries);
                    foreach (array_reverse($entries) as $entry): 
                        if (trim($entry)):
                    ?>
                    <div class="log-entry">
                        <?= nl2br(htmlspecialchars(trim($entry))) ?>
                    </div>
                    <?php 
                        endif;
                    endforeach; 
                    ?>
                </div>
            <?php endif; ?>
        </div>

        <!-- Recent PHP Errors -->
        <div class="monitor-card">
            <h5><i class="fas fa-bug text-danger"></i> Recent PHP Errors</h5>
            <?php if (empty($recent_errors)): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i> No PHP errors logged!
                </div>
            <?php else: ?>
                <div style="max-height: 400px; overflow-y: auto;">
                    <?php foreach (array_reverse($recent_errors) as $error): ?>
                    <div class="log-entry error-entry">
                        <?= htmlspecialchars($error) ?>
                    </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

        <!-- Session Information -->
        <div class="monitor-card">
            <h5><i class="fas fa-user-circle"></i> Session Information</h5>
            <table class="table table-sm">
                <tr>
                    <td>User ID:</td>
                    <td><?= $_SESSION['user_id'] ?? 'Not set' ?></td>
                </tr>
                <tr>
                    <td>Username:</td>
                    <td><?= $_SESSION['username'] ?? 'Not set' ?></td>
                </tr>
                <tr>
                    <td>Role:</td>
                    <td><?= $_SESSION['role'] ?? 'Not set' ?></td>
                </tr>
                <tr>
                    <td>Session ID:</td>
                    <td><?= session_id() ?></td>
                </tr>
            </table>
        </div>

        <!-- Actions -->
        <div class="monitor-card">
            <h5><i class="fas fa-tools"></i> Quick Actions</h5>
            <div class="btn-group" role="group">
                <a href="dashboard.php" class="btn btn-primary">
                    <i class="fas fa-home"></i> Dashboard
                </a>
                <button onclick="location.reload()" class="btn btn-info">
                    <i class="fas fa-sync"></i> Refresh Now
                </button>
                <a href="?clear_404=1" class="btn btn-warning">
                    <i class="fas fa-trash"></i> Clear 404 Log
                </a>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

<?php
// Handle clear log action
if (isset($_GET['clear_404']) && file_exists($log_file)) {
    file_put_contents($log_file, '');
    header('Location: system_monitor.php');
    exit;
}
?>
