<?php
$pageTitle = 'Error Logs';
require_once __DIR__ . '/includes/header.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'clear') {
    $csrf = new CSRF();
    if (!$csrf->verify($_POST['csrf_token'] ?? '')) {
        jsonResponse(false, 'Invalid CSRF token.');
    }
    $logFile = LOG_PATH . DIRECTORY_SEPARATOR . 'error.log';
    if (file_exists($logFile)) {
        file_put_contents($logFile, '');
    }
    jsonResponse(true, 'Error logs cleared.');
}

$logFile = LOG_PATH . DIRECTORY_SEPARATOR . 'error.log';
$logEntries = [];

if (file_exists($logFile)) {
    $content = file_get_contents($logFile);
    if (!empty($content)) {
        $lines = explode("\n", $content);
        foreach ($lines as $line) {
            $line = trim($line);
            if (!empty($line)) {
                $logEntries[] = $line;
            }
        }
    }
}

$logEntries = array_reverse($logEntries);
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h6 class="mb-0">Error Log (<?php echo count($logEntries); ?> entries)</h6>
    <div>
        <a href="?refresh=1" class="btn btn-sm btn-outline-primary"><i class="fas fa-sync me-1"></i>Refresh</a>
        <button type="button" class="btn btn-sm btn-danger" id="clearLogsBtn"><i class="fas fa-trash me-1"></i>Clear Logs</button>
    </div>
</div>

<div class="table-card">
    <div class="card-body">
        <?php if (empty($logEntries)): ?>
            <div class="empty-state">
                <i class="fas fa-check-circle text-success"></i>
                <p>No error logs found. System is running smoothly.</p>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-sm table-hover datatable">
                    <thead class="table-light">
                        <tr><th>#</th><th>Date & Time</th><th>Level</th><th>Message</th></tr>
                    </thead>
                    <tbody>
                        <?php foreach ($logEntries as $idx => $entry): ?>
                        <tr>
                            <td><?php echo $idx + 1; ?></td>
                            <td style="white-space:nowrap;">
                                <?php
                                if (preg_match('/^\[([\d\-]+ [\d:]+)\]/', $entry, $m)) {
                                    echo sanitize($m[1]);
                                } else {
                                    echo '-';
                                }
                                ?>
                            </td>
                            <td>
                                <?php
                                $level = 'info';
                                if (stripos($entry, 'error') !== false || stripos($entry, 'fatal') !== false) { $level = 'danger'; }
                                elseif (stripos($entry, 'warning') !== false || stripos($entry, 'warn') !== false) { $level = 'warning'; }
                                elseif (stripos($entry, 'notice') !== false) { $level = 'info'; }
                                ?>
                                <span class="badge bg-<?php echo $level; ?>"><?php echo strtoupper($level); ?></span>
                            </td>
                            <td style="max-width:700px;word-break:break-all;"><code style="font-size:12px;"><?php echo sanitize($entry); ?></code></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
document.getElementById('clearLogsBtn').addEventListener('click', function() {
    if (confirm('Are you sure you want to clear all error logs?')) {
        ajaxPost(BASE_URL + '/admin/error_logs.php', 'action=clear&csrf_token=' + encodeURIComponent(CSRF_TOKEN), function(data) {
            if (data.success) {
                showAlert('success', data.message);
                setTimeout(function() { location.reload(); }, 1000);
            } else {
                showAlert('danger', data.message);
            }
        });
    }
});
</script>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
