<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<div class="mb-3">
    <h1 class="h3 mb-1">Activity Log</h1>
    <p class="text-muted mb-0">Track all activities and actions performed in the system.</p>
</div>

<?php if ($filterUser): ?>
<div class="alert alert-info d-flex justify-content-between align-items-center py-2 small">
    <span>Showing activity for <strong><?= esc($filterUser->full_name) ?></strong> only.</span>
    <a href="<?= site_url('activity-log') ?>" class="text-decoration-none">Clear filter</a>
</div>
<?php endif; ?>

<div class="row g-3 mb-3">
    <div class="col-6 col-lg-3">
        <div class="card h-100"><div class="card-body d-flex align-items-center gap-3">
            <div class="rounded-3 bg-primary-subtle text-primary d-flex align-items-center justify-content-center flex-shrink-0" style="width: 44px; height: 44px;"><i class="bi bi-calendar-day fs-5"></i></div>
            <div>
                <div class="text-muted small">Today</div>
                <div class="fs-4 fw-bold"><?= number_format($stats['today']) ?></div>
                <div class="text-muted small">Activities</div>
            </div>
        </div></div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card h-100"><div class="card-body d-flex align-items-center gap-3">
            <div class="rounded-3 bg-success-subtle text-success d-flex align-items-center justify-content-center flex-shrink-0" style="width: 44px; height: 44px;"><i class="bi bi-calendar-week fs-5"></i></div>
            <div>
                <div class="text-muted small">This Week</div>
                <div class="fs-4 fw-bold"><?= number_format($stats['this_week']) ?></div>
                <div class="text-muted small">Activities</div>
            </div>
        </div></div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card h-100"><div class="card-body d-flex align-items-center gap-3">
            <div class="rounded-3 bg-info-subtle text-info d-flex align-items-center justify-content-center flex-shrink-0" style="width: 44px; height: 44px;"><i class="bi bi-calendar3 fs-5"></i></div>
            <div>
                <div class="text-muted small">This Month</div>
                <div class="fs-4 fw-bold"><?= number_format($stats['this_month']) ?></div>
                <div class="text-muted small">Activities</div>
            </div>
        </div></div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card h-100"><div class="card-body d-flex align-items-center gap-3">
            <div class="rounded-3 bg-warning-subtle text-warning d-flex align-items-center justify-content-center flex-shrink-0" style="width: 44px; height: 44px;"><i class="bi bi-clock-history fs-5"></i></div>
            <div>
                <div class="text-muted small">All Time</div>
                <div class="fs-4 fw-bold"><?= number_format($stats['all_time']) ?></div>
                <div class="text-muted small">Activities</div>
            </div>
        </div></div>
    </div>
</div>

<div class="card shadow-sm mb-3">
    <div class="card-body">
        <form action="<?= site_url('activity-log') ?>" method="get" class="row g-2 align-items-center">
            <div class="col-md-3">
                <div class="input-group input-group-sm">
                    <span class="input-group-text bg-white"><i class="bi bi-calendar3"></i></span>
                    <input type="date" class="form-control" name="date_from" value="<?= esc($filters['date_from']) ?>" title="From">
                    <input type="date" class="form-control" name="date_to" value="<?= esc($filters['date_to']) ?>" title="To">
                </div>
            </div>
            <div class="col-md-3 col-6">
                <select class="form-select form-select-sm" name="user_id">
                    <option value="">All Users</option>
                    <?php foreach ($users as $u): ?>
                        <option value="<?= $u->id ?>" <?= $filters['user_id'] === $u->id ? 'selected' : '' ?>><?= esc($u->full_name) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2 col-6">
                <select class="form-select form-select-sm" name="module">
                    <option value="">All Modules</option>
                    <?php foreach ($modules as $key => $label): ?>
                        <option value="<?= esc($key) ?>" <?= $filters['module'] === $key ? 'selected' : '' ?>><?= esc($label) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2 col-6">
                <select class="form-select form-select-sm" name="action">
                    <option value="">All Actions</option>
                    <?php foreach ($actionTags as $tag): ?>
                        <option value="<?= esc($tag) ?>" <?= $filters['action'] === $tag ? 'selected' : '' ?>><?= esc($tag) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-1 col-6">
                <button type="submit" class="btn btn-sm btn-outline-primary w-100"><i class="bi bi-funnel"></i></button>
            </div>
            <div class="col-md-1 col-6">
                <a href="<?= site_url('activity-log/export.csv?' . http_build_query($filters)) ?>" class="btn btn-sm btn-outline-secondary w-100" title="Export CSV"><i class="bi bi-download"></i></a>
            </div>
        </form>
    </div>
</div>

<div class="card shadow-sm">
    <div class="table-scroll">
        <table class="table table-hover mb-0 align-middle small">
            <thead class="table-light">
                <tr><th>Date &amp; Time</th><th>User</th><th>Module</th><th>Action</th><th>Details</th><th>IP Address</th></tr>
            </thead>
            <tbody>
                <?php if (empty($entries)): ?>
                    <tr><td colspan="6" class="text-center text-muted py-4">No activity matches this search/filter.</td></tr>
                <?php endif; ?>
                <?php foreach ($entries as $entry):
                    $userName = $entry->user_name ?? 'System';
                    $words    = preg_split('/\s+/', trim($userName));
                    $initials = strtoupper(($words[0][0] ?? 'S') . ($words[count($words) - 1][0] ?? ''));
                    $tag      = \App\Models\ActivityLogModel::actionTag($entry->action, $entry->user_name ?? null);
                ?>
                    <tr>
                        <td class="text-nowrap text-muted"><?= esc(date('d M Y, g:i a', strtotime($entry->created_at))) ?></td>
                        <td>
                            <div class="d-flex align-items-center gap-2">
                                <div class="rounded-circle d-flex align-items-center justify-content-center flex-shrink-0" style="width: 26px; height: 26px; background: color-mix(in srgb, var(--brand) 15%, white); color: var(--brand); font-weight: 700; font-size: 0.65rem;"><?= esc($initials) ?></div>
                                <?= esc($userName) ?>
                            </div>
                        </td>
                        <td><span class="badge bg-light text-dark border"><?= esc(ucfirst(str_replace('_', ' ', $entry->module))) ?></span></td>
                        <td><span class="badge bg-primary-subtle text-primary-emphasis"><?= esc($tag) ?></span></td>
                        <td><?= esc($entry->action) ?></td>
                        <td class="text-muted"><?= esc($entry->ip_address ?? '—') ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php if (! empty($entries)): ?>
    <?php
        $current = $pager->getCurrentPage();
        $total   = $pager->getTotal();
        $totalPages = max(1, (int) ceil($total / $perPage));
        $first   = ($current - 1) * $perPage + 1;
        $last    = min($current * $perPage, $total);
        $qs      = array_merge($filters, ['per_page' => $perPage]);
    ?>
    <div class="card-footer bg-white d-flex justify-content-between align-items-center flex-wrap gap-2">
        <span class="text-muted small">Showing <?= $first ?> to <?= $last ?> of <?= number_format($total) ?> activities</span>
        <div class="d-flex align-items-center gap-2">
            <nav>
                <ul class="pagination pagination-sm mb-0">
                    <li class="page-item <?= $current <= 1 ? 'disabled' : '' ?>">
                        <a class="page-link" href="<?= site_url('activity-log?' . http_build_query(array_merge($qs, ['page' => $current - 1]))) ?>"><i class="bi bi-chevron-left"></i></a>
                    </li>
                    <?php
                        $windowStart = max(1, $current - 2);
                        $windowEnd   = min($totalPages, $current + 2);
                    ?>
                    <?php if ($windowStart > 1): ?><li class="page-item"><a class="page-link" href="<?= site_url('activity-log?' . http_build_query(array_merge($qs, ['page' => 1]))) ?>">1</a></li><li class="page-item disabled"><span class="page-link">&hellip;</span></li><?php endif; ?>
                    <?php for ($p = $windowStart; $p <= $windowEnd; $p++): ?>
                        <li class="page-item <?= $p === $current ? 'active' : '' ?>">
                            <a class="page-link" href="<?= site_url('activity-log?' . http_build_query(array_merge($qs, ['page' => $p]))) ?>"><?= $p ?></a>
                        </li>
                    <?php endfor; ?>
                    <?php if ($windowEnd < $totalPages): ?><li class="page-item disabled"><span class="page-link">&hellip;</span></li><li class="page-item"><a class="page-link" href="<?= site_url('activity-log?' . http_build_query(array_merge($qs, ['page' => $totalPages]))) ?>"><?= $totalPages ?></a></li><?php endif; ?>
                    <li class="page-item <?= $current >= $totalPages ? 'disabled' : '' ?>">
                        <a class="page-link" href="<?= site_url('activity-log?' . http_build_query(array_merge($qs, ['page' => $current + 1]))) ?>"><i class="bi bi-chevron-right"></i></a>
                    </li>
                </ul>
            </nav>
            <form action="<?= site_url('activity-log') ?>" method="get" id="perPageForm">
                <?php foreach (['date_from', 'date_to', 'user_id', 'module', 'action'] as $key): ?>
                    <input type="hidden" name="<?= $key ?>" value="<?= esc($filters[$key]) ?>">
                <?php endforeach; ?>
                <select class="form-select form-select-sm" name="per_page" onchange="document.getElementById('perPageForm').submit();" style="width: auto;">
                    <option value="10" <?= $perPage === 10 ? 'selected' : '' ?>>10 per page</option>
                    <option value="25" <?= $perPage === 25 ? 'selected' : '' ?>>25 per page</option>
                    <option value="50" <?= $perPage === 50 ? 'selected' : '' ?>>50 per page</option>
                </select>
            </form>
        </div>
    </div>
    <?php endif; ?>
</div>

<?= $this->endSection() ?>
