<?php
/**
 * Activity Log Viewer
 * Admin-only page showing all system activity
 */
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/activity_log.php';

if (!hasRole('admin')) {
    redirect(SITE_URL . '/dashboard.php');
}

$pdo = getPDO();

// Filters
$filter_module = $_GET['module'] ?? '';
$filter_action = $_GET['action'] ?? '';
$filter_user = $_GET['user_id'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));
$per_page = 50;
$offset = ($page - 1) * $per_page;

// Build query
$where = "WHERE 1=1";
$params = [];
if ($filter_module) { $where .= " AND a.module = ?"; $params[] = $filter_module; }
if ($filter_action) { $where .= " AND a.action = ?"; $params[] = $filter_action; }
if ($filter_user) { $where .= " AND a.user_id = ?"; $params[] = $filter_user; }

// Count total
$count_stmt = $pdo->prepare("SELECT COUNT(*) FROM activity_log a $where");
$count_stmt->execute($params);
$total = $count_stmt->fetchColumn();
$total_pages = ceil($total / $per_page);

// Get records
$sql = "SELECT a.*, u.full_name, u.role
        FROM activity_log a
        LEFT JOIN users u ON a.user_id = u.id
        $where ORDER BY a.created_at DESC LIMIT $per_page OFFSET $offset";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$logs = $stmt->fetchAll();

// Get users for filter
$users = $pdo->query("SELECT id, full_name FROM users ORDER BY full_name")->fetchAll();

include __DIR__ . '/../includes/header.php';
?>

<div class="row mb-3">
    <div class="col-12">
        <h2><i class="fas fa-history"></i> Activity Log</h2>
    </div>
</div>

<!-- Filters -->
<div class="card mb-4">
    <div class="card-body">
        <form method="GET" class="row g-3">
            <div class="col-md-3">
                <label class="form-label">Module</label>
                <select name="module" class="form-select">
                    <option value="">All Modules</option>
                    <?php foreach (['dozar','tripper','user','vehicle','driver','project','group','auth'] as $m): ?>
                    <option value="<?php echo $m; ?>" <?php echo $filter_module === $m ? 'selected' : ''; ?>><?php echo ucfirst($m); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">Action</label>
                <select name="action" class="form-select">
                    <option value="">All Actions</option>
                    <?php foreach (['create','update','delete','login','logout','complete','cancel','upload'] as $a): ?>
                    <option value="<?php echo $a; ?>" <?php echo $filter_action === $a ? 'selected' : ''; ?>><?php echo ucfirst($a); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">User</label>
                <select name="user_id" class="form-select">
                    <option value="">All Users</option>
                    <?php foreach ($users as $u): ?>
                    <option value="<?php echo $u['id']; ?>" <?php echo $filter_user == $u['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($u['full_name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">&nbsp;</label>
                <div class="d-flex gap-2">
                    <button type="submit" class="btn btn-primary flex-fill"><i class="fas fa-filter"></i> Filter</button>
                    <a href="index.php" class="btn btn-secondary"><i class="fas fa-undo"></i></a>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Stats -->
<div class="row mb-3">
    <div class="col-12">
        <small class="text-muted">Showing <?php echo count($logs); ?> of <?php echo $total; ?> entries (Page <?php echo $page; ?>/<?php echo max(1, $total_pages); ?>)</small>
    </div>
</div>

<!-- Log Table -->
<div class="card">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover table-sm mb-0">
                <thead>
                    <tr>
                        <th width="160">Time</th>
                        <th>User</th>
                        <th>Action</th>
                        <th>Module</th>
                        <th>Details</th>
                        <th>IP</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($logs)): ?>
                    <tr><td colspan="6" class="text-center text-muted py-4">No activity logged yet</td></tr>
                    <?php else: ?>
                    <?php foreach ($logs as $log): ?>
                    <tr>
                        <td nowrap><small><?php echo date('Y-m-d H:i', strtotime($log['created_at'])); ?></small></td>
                        <td>
                            <strong><?php echo htmlspecialchars($log['full_name'] ?? 'System'); ?></strong>
                            <?php if ($log['role']): ?><br><small class="text-muted"><?php echo ucfirst($log['role']); ?></small><?php endif; ?>
                        </td>
                        <td><?php echo getActivityIcon($log['action']); ?> <?php echo ucfirst($log['action']); ?></td>
                        <td><?php echo getActivityBadge($log['module']); ?></td>
                        <td><small><?php echo htmlspecialchars($log['details']); ?></small></td>
                        <td><small class="text-muted"><?php echo htmlspecialchars($log['ip_address']); ?></small></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Pagination -->
<?php if ($total_pages > 1): ?>
<nav class="mt-3">
    <ul class="pagination justify-content-center">
        <?php if ($page > 1): ?>
        <li class="page-item"><a class="page-link" href="?page=<?php echo $page-1; ?>&module=<?php echo $filter_module; ?>&action=<?php echo $filter_action; ?>&user_id=<?php echo $filter_user; ?>"><i class="fas fa-chevron-left"></i></a></li>
        <?php endif; ?>
        <?php for ($p = max(1, $page-3); $p <= min($total_pages, $page+3); $p++): ?>
        <li class="page-item <?php echo $p == $page ? 'active' : ''; ?>"><a class="page-link" href="?page=<?php echo $p; ?>&module=<?php echo $filter_module; ?>&action=<?php echo $filter_action; ?>&user_id=<?php echo $filter_user; ?>"><?php echo $p; ?></a></li>
        <?php endfor; ?>
        <?php if ($page < $total_pages): ?>
        <li class="page-item"><a class="page-link" href="?page=<?php echo $page+1; ?>&module=<?php echo $filter_module; ?>&action=<?php echo $filter_action; ?>&user_id=<?php echo $filter_user; ?>"><i class="fas fa-chevron-right"></i></a></li>
        <?php endif; ?>
    </ul>
</nav>
<?php endif; ?>

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