<?php
require_once '../config/config.php';
requireLogin();
if (!isSuperAdmin() && !isInstitutionAdmin()) redirect(SITE_URL . '/index.php');

$pageTitle = 'Audit Logs';

$search = $_GET['search'] ?? '';
$action = $_GET['action'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 50;
$offset = ($page - 1) * $perPage;

$db = getDB();
$where = ["1=1"];
$params = [];

if (!empty($search)) {
    $where[] = "(al.action LIKE ? OR al.table_name LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if (!empty($action)) {
    $where[] = "al.action = ?";
    $params[] = $action;
}

$whereClause = implode(' AND ', $where);

$stmt = $db->prepare("SELECT COUNT(*) FROM audit_logs al WHERE $whereClause");
$stmt->execute($params);
$totalLogs = $stmt->fetchColumn();
$totalPages = ceil($totalLogs / $perPage);

$stmt = $db->prepare("
    SELECT al.*, u.first_name, u.last_name
    FROM audit_logs al
    LEFT JOIN users u ON al.user_id = u.id
    WHERE $whereClause
    ORDER BY al.created_at DESC
    LIMIT $perPage OFFSET $offset
");
$stmt->execute($params);
$logs = $stmt->fetchAll();

include '../templates/admin-header.php';
?>

<div class="container-fluid">
    <div class="row">
        <?php include 'sidebar.php'; ?>
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <?php include 'header-bar.php'; ?>

            <div class="card shadow mb-4">
                <div class="card-body">
                    <form method="GET" class="row g-3">
                        <div class="col-md-5">
                            <input type="text" class="form-control" name="search" value="<?php echo e($search); ?>" placeholder="Search...">
                        </div>
                        <div class="col-md-3">
                            <select class="form-select" name="action">
                                <option value="">All Actions</option>
                                <option value="user_login" <?php echo $action === 'user_login' ? 'selected' : ''; ?>>User Login</option>
                                <option value="user_registered" <?php echo $action === 'user_registered' ? 'selected' : ''; ?>>User Registered</option>
                                <option value="study_created" <?php echo $action === 'study_created' ? 'selected' : ''; ?>>Study Created</option>
                                <option value="study_updated" <?php echo $action === 'study_updated' ? 'selected' : ''; ?>>Study Updated</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <button type="submit" class="btn btn-primary w-100"><i class="fas fa-search"></i> Filter</button>
                        </div>
                        <div class="col-md-2">
                            <a href="audit-logs.php" class="btn btn-outline-secondary w-100"><i class="fas fa-redo"></i> Reset</a>
                        </div>
                    </form>
                </div>
            </div>

            <div class="card shadow">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-sm table-hover">
                            <thead>
                                <tr>
                                    <th>Time</th>
                                    <th>User</th>
                                    <th>Action</th>
                                    <th>Table</th>
                                    <th>Record ID</th>
                                    <th>IP Address</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($logs as $log): ?>
                                <tr>
                                    <td><?php echo date('M d, Y H:i:s', strtotime($log['created_at'])); ?></td>
                                    <td><?php echo $log['first_name'] ? e($log['first_name'] . ' ' . $log['last_name']) : 'System'; ?></td>
                                    <td><code><?php echo e($log['action']); ?></code></td>
                                    <td><?php echo e($log['table_name'] ?? 'N/A'); ?></td>
                                    <td><?php echo $log['record_id'] ?? 'N/A'; ?></td>
                                    <td><?php echo e($log['ip_address'] ?? 'N/A'); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <?php if ($totalPages > 1): ?>
                    <nav>
                        <ul class="pagination justify-content-center">
                            <?php for ($i = 1; $i <= min($totalPages, 10); $i++): ?>
                            <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                                <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&action=<?php echo $action; ?>">
                                    <?php echo $i; ?>
                                </a>
                            </li>
                            <?php endfor; ?>
                        </ul>
                    </nav>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</div>

<?php include '../templates/footer.php'; ?>
