<?php
require_once __DIR__ . '/../includes/functions.php';
startSecureSession();
requireAdmin();

// Handle form submissions
$msg = '';
$err = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrfVerify();
    if (isset($_POST['action'])) {
        if ($_POST['action'] === 'toggle_logging') {
            $currentSettings = getAdminSettings();
            $newStatus = empty($currentSettings['enable_logging']) ? 1 : 0;
            updateAdminSettings(['enable_logging' => $newStatus]);
            $msg = "Logging has been " . ($newStatus ? "enabled" : "disabled") . ".";
            
            // Add a log entry for the action itself (if enabled)
            if ($newStatus) {
                addSystemLog('Admin', 'System logging enabled by admin.');
            }
        } elseif ($_POST['action'] === 'clear_logs') {
            getDB()->exec("TRUNCATE TABLE system_logs");
            $msg = "All system logs have been cleared.";
            addSystemLog('Admin', 'System logs cleared by admin.');
        }
    }
    // Redirect to prevent form resubmission
    header("Location: logs.php?msg=" . urlencode($msg));
    exit;
}

if (isset($_GET['msg'])) {
    $msg = htmlspecialchars($_GET['msg']);
}

$settings = getAdminSettings();
$loggingEnabled = !empty($settings['enable_logging']);

// Fetch logs
$stmt = getDB()->query("SELECT * FROM system_logs ORDER BY id DESC LIMIT 500");
$logs = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php $pageTitle = "System Logs — FamGateway"; include __DIR__ . '/admin-style.php'; ?>
<style>
.log-source { font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:0.5px; padding:2px 6px; border-radius:4px; background:#f1f5f9; color:#475569; display:inline-block; }
.log-source.node { background:#dcfce7; color:#166534; }
.log-source.api { background:#dbeafe; color:#1e40af; }
.log-source.admin { background:#fef3c7; color:#92400e; }
.log-time { font-family:var(--font-mono); font-size:12px; color:var(--color-ink-mute); }
.log-msg { font-size:13.5px; color:var(--color-ink); word-break:break-all; }
.log-container { background:#fff; border:1px solid var(--color-border); border-radius:var(--r-xl); overflow:hidden; }
.log-header { padding:16px 24px; border-bottom:1px solid var(--color-border); display:flex; justify-content:space-between; align-items:center; background:#f8fafc; }
</style>
</head>
<body>
<?php include __DIR__ . '/admin-nav.php'; ?>
    <div class="wrap">
      <div style="display:flex;justify-content:space-between;align-items:flex-end;margin-bottom:24px;flex-wrap:wrap;gap:16px;">
        <div>
          <h1 style="font-size:22px;font-weight:700;color:var(--color-ink);letter-spacing:-0.5px;display:flex;align-items:center;gap:8px;">
            <i data-lucide="terminal" style="color:var(--color-primary);width:24px;height:24px;"></i> System Logs
          </h1>
          <p style="font-size:13px;color:var(--color-ink-mute);margin-top:4px;">Monitor background IMAP daemon and webhook API activity in real-time.</p>
        </div>
        <div style="display:flex;gap:12px;">
            <form method="POST" style="margin:0;">
                <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
                <input type="hidden" name="action" value="toggle_logging">
                <?php if ($loggingEnabled): ?>
                    <button type="submit" class="btn btn-secondary" style="color:#ef4444;border-color:#fca5a5;background:#fef2f2;">
                        <i data-lucide="pause-circle" style="width:16px;height:16px;"></i> Disable Logging
                    </button>
                <?php else: ?>
                    <button type="submit" class="btn btn-secondary" style="color:#10b981;border-color:#6ee7b7;background:#ecfdf5;">
                        <i data-lucide="play-circle" style="width:16px;height:16px;"></i> Enable Logging
                    </button>
                <?php endif; ?>
            </form>
            <form method="POST" style="margin:0;" onsubmit="return confirm('Are you sure you want to clear all logs?');">
                <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
                <input type="hidden" name="action" value="clear_logs">
                <button type="submit" class="btn btn-primary">
                    <i data-lucide="trash-2" style="width:16px;height:16px;"></i> Clear Logs
                </button>
            </form>
        </div>
      </div>

      <?php if ($msg): ?>
      <div style="background:#ecfdf5;border:1px solid #a7f3d0;color:#059669;padding:12px 16px;border-radius:8px;margin-bottom:24px;font-size:14px;font-weight:500;display:flex;align-items:center;gap:8px;">
          <i data-lucide="check-circle-2" style="width:18px;height:18px;"></i> <?= htmlspecialchars($msg) ?>
      </div>
      <?php endif; ?>

      <?php if (!$loggingEnabled): ?>
      <div style="background:#fffbeb;border:1px solid #fde68a;color:#92400e;padding:12px 16px;border-radius:8px;margin-bottom:24px;font-size:14px;font-weight:500;display:flex;align-items:center;gap:8px;">
          <i data-lucide="alert-triangle" style="width:18px;height:18px;"></i> Logging is currently disabled. New events will not be recorded.
      </div>
      <?php endif; ?>

      <div class="log-container">
        <div class="log-header">
            <div style="font-weight:600;font-size:14px;">Latest Logs (Max 500)</div>
            <button onclick="window.location.reload();" class="btn btn-secondary" style="padding:6px 12px;font-size:12px;">
                <i data-lucide="refresh-cw" style="width:14px;height:14px;"></i> Refresh
            </button>
        </div>
        <div class="table-container" style="margin:0;border:none;border-radius:0;">
            <table class="table" style="margin:0;">
                <thead style="background:#f8fafc;">
                    <tr>
                        <th style="width:180px;">Timestamp (IST)</th>
                        <th style="width:120px;">Source</th>
                        <th>Message</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($logs)): ?>
                    <tr>
                        <td colspan="3" style="padding:48px 0;text-align:center;">
                            <div style="color:var(--color-ink-mute);">
                                <i data-lucide="file-text" style="width:32px;height:32px;margin:0 auto 12px;opacity:0.5;"></i>
                                <div style="font-weight:600;font-size:15px;color:var(--color-ink);margin-bottom:4px;">No logs found</div>
                                <div style="font-size:13px;">System is quiet or logging is disabled.</div>
                            </div>
                        </td>
                    </tr>
                    <?php else: foreach ($logs as $log): 
                        $sourceClass = strtolower($log['source']);
                    ?>
                    <tr>
                        <td class="log-time"><?= date('M d, Y H:i:s', strtotime($log['created_at'])) ?></td>
                        <td><span class="log-source <?= htmlspecialchars($sourceClass) ?>"><?= htmlspecialchars($log['source']) ?></span></td>
                        <td class="log-msg"><?= htmlspecialchars($log['message']) ?></td>
                    </tr>
                    <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
      </div>

    </div>
  </main>
</div>
<script>if (window.lucide) { lucide.createIcons(); }</script>
</body>
</html>
