<?php
/**
 * Admin - Activity log (role changes, suspend/unsuspend, verify)
 * PHP User Registration - https://rskworld.in
 * Developer: Molla Samser | RSK World
 * Contact: help@rskworld.in | +91 93305 39277
 * Year: 2026
 */

require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../includes/functions.php';

requireAdmin();
$baseHref = '..';

$pdo = getDbConnection();
$page = max(1, (int) ($_GET['page'] ?? 1));
$perPage = 30;
$total = 0;
$logs = [];

try {
    $total = (int) $pdo->query('SELECT COUNT(*) FROM admin_activity_log')->fetchColumn();
} catch (PDOException $e) {
    if ($e->getCode() === '42S02') {
        $pdo->exec("CREATE TABLE IF NOT EXISTS admin_activity_log (
            id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            admin_user_id INT UNSIGNED NOT NULL,
            action VARCHAR(50) NOT NULL,
            target_user_id INT UNSIGNED NULL,
            details VARCHAR(500) NULL,
            ip_address VARCHAR(45) NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_admin (admin_user_id),
            INDEX idx_created (created_at)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    }
}
$totalPages = max(1, (int) ceil($total / $perPage));
$page = min($page, $totalPages);
$offset = ($page - 1) * $perPage;
try {
    $stmt = $pdo->prepare('SELECT a.id, a.admin_user_id, a.action, a.target_user_id, a.details, a.ip_address, a.created_at FROM admin_activity_log a ORDER BY a.created_at DESC LIMIT ? OFFSET ?');
    $stmt->execute([$perPage, $offset]);
    $logs = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    // table just created
}

// Resolve admin and target names
$userIds = [];
foreach ($logs as $l) {
    if (!empty($l['admin_user_id'])) $userIds[(int) $l['admin_user_id']] = true;
    if (!empty($l['target_user_id'])) $userIds[(int) $l['target_user_id']] = true;
}
$names = [];
if (!empty($userIds)) {
    $ids = array_keys($userIds);
    $placeholders = implode(',', array_fill(0, count($ids), '?'));
    $stmt = $pdo->prepare("SELECT id, name, email FROM users WHERE id IN ($placeholders)");
    $stmt->execute($ids);
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $names[(int) $row['id']] = $row['name'] . ' (' . $row['email'] . ')';
    }
}

$pageTitle = 'Admin - Activity Log';
require_once __DIR__ . '/../includes/header.php';
?>

<div class="page-content admin-content">
    <h1><i class="fas fa-history"></i> Activity Log</h1>
    <p class="subtitle">PHP User Registration — <a href="https://rskworld.in" target="_blank">rskworld.in</a></p>

    <div class="table-wrap">
        <table class="admin-table">
            <thead>
                <tr>
                    <th>Time</th>
                    <th>Admin</th>
                    <th>Action</th>
                    <th>Target user</th>
                    <th>Details</th>
                    <th>IP</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($logs as $l): ?>
                <tr>
                    <td><?= !empty($l['created_at']) ? date('M j, Y g:i A', strtotime($l['created_at'])) : '—' ?></td>
                    <td><?= htmlspecialchars($names[(int) ($l['admin_user_id'] ?? 0)] ?? '#' . ($l['admin_user_id'] ?? '')) ?></td>
                    <td><span class="badge badge-primary"><?= htmlspecialchars($l['action'] ?? '') ?></span></td>
                    <td><?= htmlspecialchars($names[(int) ($l['target_user_id'] ?? 0)] ?? ($l['target_user_id'] ? '#' . $l['target_user_id'] : '—')) ?></td>
                    <td><?= htmlspecialchars($l['details'] ?? '—') ?></td>
                    <td><?= htmlspecialchars($l['ip_address'] ?? '—') ?></td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($logs)): ?>
                <tr><td colspan="6" class="text-muted">No activity recorded yet.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <?php if ($totalPages > 1): ?>
    <div class="pagination">
        <?php if ($page > 1): ?>
            <a href="activity.php?page=<?= $page - 1 ?>">« Previous</a>
        <?php endif; ?>
        <span class="pagination-info">Page <?= $page ?> of <?= $totalPages ?> (<?= $total ?> entries)</span>
        <?php if ($page < $totalPages): ?>
            <a href="activity.php?page=<?= $page + 1 ?>">Next »</a>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <p><a href="index.php" class="btn btn-secondary">Back to Admin</a></p>
</div>

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