<?php

require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/config/database.php';
require_once __DIR__ . '/../app/helpers/functions.php';
require_once __DIR__ . '/../app/helpers/auth.php';
require_once __DIR__ . '/../app/helpers/settings.php';

require_admin();

$pageTitle = 'Activity Logs';

$logs = $pdo->query("
    SELECT al.*,
           au.full_name,
           au.email
    FROM admin_activity_logs al
    LEFT JOIN admin_users au ON al.admin_id = au.id
    ORDER BY al.id DESC
    LIMIT 300
")->fetchAll();

require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/sidebar.php';
?>

<main class="admin-main">
    <div class="admin-topbar">
        <div>
            <h1>Activity Logs</h1>
            <div class="admin-user">Track admin actions, login activity, updates, and security-related events.</div>
        </div>
    </div>

    <section class="admin-panel">
        <h2>Recent Admin Activity</h2>

        <table class="admin-table">
            <thead>
                <tr>
                    <th>Admin</th>
                    <th>Action</th>
                    <th>Description</th>
                    <th>IP Address</th>
                    <th>User Agent</th>
                    <th>Date</th>
                </tr>
            </thead>

            <tbody>
                <?php if (!$logs): ?>
                    <tr>
                        <td colspan="6">No activity logs yet.</td>
                    </tr>
                <?php endif; ?>

                <?php foreach ($logs as $log): ?>
                    <tr>
                        <td>
                            <?php if (!empty($log['admin_id'])): ?>
                                <strong><?= e($log['full_name'] ?? 'Admin'); ?></strong><br>
                                <small><?= e($log['email'] ?? '-'); ?></small>
                            <?php else: ?>
                                System / Unknown
                            <?php endif; ?>
                        </td>

                        <td><strong><?= e($log['action']); ?></strong></td>

                        <td><?= nl2br(e($log['description'] ?? '-')); ?></td>

                        <td><?= e($log['ip_address'] ?? '-'); ?></td>

                        <td style="max-width:320px;">
                            <small><?= e($log['user_agent'] ?? '-'); ?></small>
                        </td>

                        <td><?= e(date('d M Y, h:i A', strtotime($log['created_at']))); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </section>
</main>

<?php require_once __DIR__ . '/includes/footer.php'; ?>