<?php
session_start();
include 'layouts/dbconn.php';
include 'includes/menu_config.php';

// Set timezone
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role_name'] ?? 'User';

// Check if user has permission to view activity logs
if ($user_role !== 'Administrator') {
    header('Location: index.php');
    exit();
}

// Fetch user details
$sql_user = "SELECT u.*, ur.role_name FROM users u 
             INNER JOIN user_roles ur ON u.role_id = ur.role_id 
             WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if (!$user_details) {
    header('Location: logout.php');
    exit();
}

// Handle AJAX requests for activity details
if (isset($_GET['get_activity_details']) && $_GET['log_id']) {
    header('Content-Type: application/json');
    
    $log_id = intval($_GET['log_id']);
    $detail_sql = "SELECT al.*, u.full_name, u.username, ur.role_name 
                   FROM activity_log al
                   LEFT JOIN users u ON al.user_id = u.user_id
                   LEFT JOIN user_roles ur ON u.role_id = ur.role_id
                   WHERE al.log_id = ?";
    
    $stmt = $conn->prepare($detail_sql);
    $stmt->bind_param("i", $log_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($activity = $result->fetch_assoc()) {
        echo json_encode(['success' => true, 'data' => $activity]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Activity not found']);
    }
    exit();
}

// Handle AJAX clear logs request
if (isset($_POST['action']) && $_POST['action'] === 'clear_logs') {
    header('Content-Type: application/json');
    
    $days = intval($_POST['days']);
    $cutoff_date = date('Y-m-d H:i:s', strtotime("-{$days} days"));
    
    $delete_sql = "DELETE FROM activity_log WHERE logged_at < ?";
    $stmt = $conn->prepare($delete_sql);
    $stmt->bind_param("s", $cutoff_date);
    
    if ($stmt->execute()) {
        $deleted_count = $stmt->affected_rows;
        
        // Log the cleanup action
        $log_sql = "INSERT INTO activity_log (user_id, action, module, new_values) 
                   VALUES (?, 'DELETE', 'activity_log', ?)";
        $stmt_log = $conn->prepare($log_sql);
        $log_data = json_encode(['deleted_count' => $deleted_count, 'days' => $days]);
        $stmt_log->bind_param("is", $user_id, $log_data);
        $stmt_log->execute();
        
        echo json_encode(['success' => true, 'deleted_count' => $deleted_count]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to clear logs']);
    }
    exit();
}

// Filter parameters
$user_filter = $_GET['user_filter'] ?? '';
$action_filter = $_GET['action'] ?? '';
$module_filter = $_GET['module'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$ip_filter = $_GET['ip_filter'] ?? '';

// Build WHERE clause
$where_conditions = [];
$params = [];
$param_types = '';

if ($user_filter) {
    $where_conditions[] = "(u.full_name LIKE ? OR u.username LIKE ?)";
    $search_param = "%$user_filter%";
    $params[] = $search_param;
    $params[] = $search_param;
    $param_types .= 'ss';
}

if ($action_filter) {
    $where_conditions[] = "al.action = ?";
    $params[] = $action_filter;
    $param_types .= 's';
}

if ($module_filter) {
    $where_conditions[] = "al.module = ?";
    $params[] = $module_filter;
    $param_types .= 's';
}

if ($date_from) {
    $where_conditions[] = "DATE(al.logged_at) >= ?";
    $params[] = $date_from;
    $param_types .= 's';
}

if ($date_to) {
    $where_conditions[] = "DATE(al.logged_at) <= ?";
    $params[] = $date_to;
    $param_types .= 's';
}

if ($ip_filter) {
    $where_conditions[] = "al.ip_address LIKE ?";
    $params[] = "%$ip_filter%";
    $param_types .= 's';
}

$where_clause = empty($where_conditions) ? '' : 'WHERE ' . implode(' AND ', $where_conditions);

// Get activity logs with user details
$sql_activities = "
    SELECT 
        al.*,
        u.full_name,
        u.username,
        ur.role_name,
        CASE 
            WHEN al.action = 'LOGIN' THEN 'success'
            WHEN al.action = 'LOGOUT' THEN 'info'
            WHEN al.action = 'CREATE' THEN 'primary'
            WHEN al.action = 'UPDATE' THEN 'warning'
            WHEN al.action = 'DELETE' THEN 'danger'
            ELSE 'secondary'
        END as action_color
    FROM activity_log al
    LEFT JOIN users u ON al.user_id = u.user_id
    LEFT JOIN user_roles ur ON u.role_id = ur.role_id
    $where_clause
    ORDER BY al.logged_at DESC
    LIMIT 100";

$stmt_activities = $conn->prepare($sql_activities);
if (!empty($params)) {
    $stmt_activities->bind_param($param_types, ...$params);
}
$stmt_activities->execute();
$activities_result = $stmt_activities->get_result();

// Get activity statistics
$sql_stats = "
    SELECT 
        COUNT(*) as total_activities,
        COUNT(CASE WHEN DATE(logged_at) = CURDATE() THEN 1 END) as today_activities,
        COUNT(CASE WHEN DATE(logged_at) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) THEN 1 END) as week_activities,
        COUNT(DISTINCT u.user_id) as active_users,
        COUNT(CASE WHEN action = 'LOGIN' AND DATE(logged_at) = CURDATE() THEN 1 END) as today_logins,
        COUNT(CASE WHEN action IN ('CREATE', 'UPDATE', 'DELETE') AND DATE(logged_at) = CURDATE() THEN 1 END) as today_changes
    FROM activity_log al
    LEFT JOIN users u ON al.user_id = u.user_id";

$stats_result = $conn->query($sql_stats);
$stats = $stats_result->fetch_assoc();

// Get available modules and actions for filters
$sql_modules = "SELECT DISTINCT module FROM activity_log WHERE module IS NOT NULL ORDER BY module";
$modules_result = $conn->query($sql_modules);

$sql_actions = "SELECT DISTINCT action FROM activity_log ORDER BY action";
$actions_result = $conn->query($sql_actions);

// Get recent user activity summary
$sql_user_activity = "
    SELECT 
        u.user_id,
        u.full_name,
        u.username,
        ur.role_name,
        COUNT(*) as activity_count,
        MAX(al.logged_at) as last_activity,
        COUNT(CASE WHEN DATE(al.logged_at) = CURDATE() THEN 1 END) as today_count
    FROM activity_log al
    INNER JOIN users u ON al.user_id = u.user_id
    INNER JOIN user_roles ur ON u.role_id = ur.role_id
    WHERE al.logged_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
    GROUP BY u.user_id, u.full_name, u.username, ur.role_name
    ORDER BY activity_count DESC
    LIMIT 10";

$user_activity_result = $conn->query($sql_user_activity);

$conn->close();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'User Activity Log')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- DataTables CSS -->
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.bootstrap5.min.css" rel="stylesheet">
    
    <!-- SweetAlert2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    
    <!-- Remix Icons -->
    <link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
    
    <style>
        .activity-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border: 1px solid #e3e6f0;
            transition: all 0.3s ease;
            margin-bottom: 1.5rem;
        }
        
        .activity-card:hover {
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
            transform: translateY(-2px);
        }
        
        .summary-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 1.5rem;
            position: relative;
            overflow: hidden;
        }
        
        .summary-card::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 100px;
            height: 100px;
            background: rgba(255,255,255,0.1);
            border-radius: 50%;
            transform: translate(30px, -30px);
        }
        
        .summary-value {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .summary-label {
            font-size: 0.9rem;
            opacity: 0.9;
        }
        
        .activity-timeline {
            position: relative;
            padding-left: 3rem;
        }
        
        .activity-timeline::before {
            content: '';
            position: absolute;
            left: 1.5rem;
            top: 0;
            bottom: 0;
            width: 2px;
            background: linear-gradient(to bottom, #e9ecef, #dee2e6);
        }
        
        .activity-item {
            position: relative;
            margin-bottom: 1.5rem;
            background: white;
            border-radius: 10px;
            padding: 1.5rem;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            border-left: 4px solid #e9ecef;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .activity-item:hover {
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            transform: translateX(5px);
        }
        
        .activity-item::before {
            content: '';
            position: absolute;
            left: -3rem;
            top: 1rem;
            width: 1rem;
            height: 1rem;
            border-radius: 50%;
            border: 3px solid white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
        
        .activity-item.login { border-left-color: #28a745; }
        .activity-item.login::before { background: #28a745; }
        
        .activity-item.logout { border-left-color: #17a2b8; }
        .activity-item.logout::before { background: #17a2b8; }
        
        .activity-item.create { border-left-color: #007bff; }
        .activity-item.create::before { background: #007bff; }
        
        .activity-item.update { border-left-color: #ffc107; }
        .activity-item.update::before { background: #ffc107; }
        
        .activity-item.delete { border-left-color: #dc3545; }
        .activity-item.delete::before { background: #dc3545; }
        
        .activity-item.other { border-left-color: #6c757d; }
        .activity-item.other::before { background: #6c757d; }
        
        .activity-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 0.75rem;
        }
        
        .activity-user {
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }
        
        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.9rem;
        }
        
        .user-info h6 {
            margin: 0;
            font-weight: 600;
            color: #495057;
        }
        
        .user-role {
            font-size: 0.8rem;
            color: #6c757d;
        }
        
        .activity-time {
            text-align: right;
            color: #6c757d;
            font-size: 0.85rem;
        }
        
        .activity-details {
            margin-bottom: 0.75rem;
        }
        
        .activity-action {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            margin-bottom: 0.5rem;
        }
        
        .action-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 15px;
            font-size: 0.7rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.3px;
        }
        
        .badge-login { background: #d1e7dd; color: #0f5132; }
        .badge-logout { background: #cff4fc; color: #055160; }
        .badge-create { background: #cce7ff; color: #004085; }
        .badge-update { background: #fff3cd; color: #856404; }
        .badge-delete { background: #f8d7da; color: #721c24; }
        .badge-export { background: #e2e3e5; color: #383d41; }
        .badge-import { background: #e2e3e5; color: #383d41; }
        .badge-approve { background: #d1ecf1; color: #0c5460; }
        .badge-reject { background: #f5c6cb; color: #721c24; }
        .badge-other { background: #e2e3e5; color: #383d41; }
        
        .module-badge {
            background: #f8f9fa;
            color: #495057;
            padding: 0.2rem 0.6rem;
            border-radius: 12px;
            font-size: 0.7rem;
            font-weight: 500;
            border: 1px solid #e9ecef;
        }
        
        .activity-description {
            color: #6c757d;
            font-size: 0.9rem;
            line-height: 1.4;
        }
        
        .activity-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-top: 0.75rem;
            border-top: 1px solid #f1f5f9;
            font-size: 0.8rem;
            color: #adb5bd;
        }
        
        .meta-left {
            display: flex;
            gap: 1rem;
            align-items: center;
        }
        
        .ip-address {
            font-family: 'Courier New', monospace;
            background: #f8f9fa;
            padding: 0.2rem 0.4rem;
            border-radius: 4px;
            font-size: 0.75rem;
        }
        
        .filter-section {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            border: 1px solid #e9ecef;
        }
        
        .live-indicator {
            animation: pulse 2s infinite;
            margin-left: 0.5rem;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
        
        .top-users-section {
            max-height: 500px;
            overflow-y: auto;
        }
        
        .user-activity-item {
            display: flex;
            align-items: center;
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            transition: background 0.2s ease;
        }
        
        .user-activity-item:hover {
            background: #f8fafc;
        }
        
        .user-activity-item:last-child {
            border-bottom: none;
        }
        
        .user-stats {
            flex-grow: 1;
            margin-left: 0.75rem;
        }
        
        .user-name {
            font-weight: 600;
            color: #495057;
            margin-bottom: 0.25rem;
        }
        
        .user-role-badge {
            font-size: 0.7rem;
            color: #6c757d;
            background: #f8f9fa;
            padding: 0.1rem 0.4rem;
            border-radius: 8px;
        }
        
        .activity-count {
            text-align: right;
        }
        
        .count-number {
            font-size: 1.2rem;
            font-weight: 700;
            color: #007bff;
        }
        
        .count-label {
            font-size: 0.7rem;
            color: #6c757d;
        }
        
        .refresh-btn {
            background: linear-gradient(45deg, #28a745, #20c997);
            border: none;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 10px;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(40,167,69,0.3);
        }
        
        .refresh-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(40,167,69,0.4);
            color: white;
        }
        
        @media (max-width: 768px) {
            .activity-timeline {
                padding-left: 1.5rem;
            }
            
            .activity-timeline::before {
                left: 0.75rem;
            }
            
            .activity-item::before {
                left: -1.5rem;
            }
            
            .activity-header {
                flex-direction: column;
                gap: 0.5rem;
            }
            
            .activity-time {
                text-align: left;
            }
            
            .activity-meta {
                flex-direction: column;
                align-items: flex-start;
                gap: 0.5rem;
            }
            
            .meta-left {
                flex-direction: column;
                align-items: flex-start;
                gap: 0.25rem;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">
                                    <i class="ri-history-line me-2"></i>User Activity Log
                                    <span class="live-indicator">
                                        <i class="ri-live-line text-success" title="Live monitoring"></i>
                                    </span>
                                </h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="users.php">User Management</a></li>
                                        <li class="breadcrumb-item active">Activity Log</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Summary Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-2 col-md-4 col-sm-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                                <div class="summary-value"><?php echo number_format($stats['total_activities']); ?></div>
                                <div class="summary-label">Total Activities</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-2 col-md-4 col-sm-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                                <div class="summary-value"><?php echo number_format($stats['today_activities']); ?></div>
                                <div class="summary-label">Today's Activities</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-2 col-md-4 col-sm-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                                <div class="summary-value"><?php echo number_format($stats['week_activities']); ?></div>
                                <div class="summary-label">This Week</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-2 col-md-4 col-sm-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);">
                                <div class="summary-value"><?php echo number_format($stats['active_users']); ?></div>
                                <div class="summary-label">Active Users</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-2 col-md-4 col-sm-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);">
                                <div class="summary-value"><?php echo number_format($stats['today_logins']); ?></div>
                                <div class="summary-label">Today's Logins</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-2 col-md-4 col-sm-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #d299c2 0%, #fef9d7 100%);">
                                <div class="summary-value"><?php echo number_format($stats['today_changes']); ?></div>
                                <div class="summary-label">Today's Changes</div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters and Actions -->
                    <div class="row">
                        <div class="col-12">
                            <div class="activity-card">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <button class="btn refresh-btn me-2" onclick="refreshActivityLog()">
                                                <i class="ri-refresh-line me-1"></i>Refresh
                                            </button>
                                            <button class="btn btn-outline-success me-2" onclick="exportActivityLog()">
                                                <i class="ri-download-line me-1"></i>Export Log
                                            </button>
                                            <button class="btn btn-outline-warning" onclick="clearOldLogs()">
                                                <i class="ri-delete-bin-line me-1"></i>Clear Old Logs
                                            </button>
                                        </div>
                                        <button class="btn btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#filterSection">
                                            <i class="ri-filter-3-line me-1"></i>Filters
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filter Section -->
                    <div class="collapse" id="filterSection">
                        <div class="filter-section">
                            <form method="GET" class="row g-3">
                                <div class="col-md-3">
                                    <label for="user_filter" class="form-label">User</label>
                                    <input type="text" class="form-control" name="user_filter" id="user_filter" 
                                           placeholder="Search user..." value="<?php echo htmlspecialchars($user_filter); ?>">
                                </div>
                                
                                <div class="col-md-2">
                                    <label for="action" class="form-label">Action</label>
                                    <select class="form-select" name="action" id="action">
                                        <option value="">All Actions</option>
                                        <?php while ($action = $actions_result->fetch_assoc()): ?>
                                        <option value="<?php echo $action['action']; ?>" <?php echo $action_filter == $action['action'] ? 'selected' : ''; ?>>
                                            <?php echo $action['action']; ?>
                                        </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                
                                <div class="col-md-2">
                                    <label for="module" class="form-label">Module</label>
                                    <select class="form-select" name="module" id="module">
                                        <option value="">All Modules</option>
                                        <?php while ($module = $modules_result->fetch_assoc()): ?>
                                        <option value="<?php echo $module['module']; ?>" <?php echo $module_filter == $module['module'] ? 'selected' : ''; ?>>
                                            <?php echo ucfirst($module['module']); ?>
                                        </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                
                                <div class="col-md-2">
                                    <label for="date_from" class="form-label">Date From</label>
                                    <input type="date" class="form-control" name="date_from" id="date_from" value="<?php echo $date_from; ?>">
                                </div>
                                
                                <div class="col-md-2">
                                    <label for="date_to" class="form-label">Date To</label>
                                    <input type="date" class="form-control" name="date_to" id="date_to" value="<?php echo $date_to; ?>">
                                </div>
                                
                                <div class="col-md-1">
                                    <label class="form-label">&nbsp;</label>
                                    <button type="submit" class="btn btn-primary d-block w-100">
                                        <i class="ri-search-line"></i>
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Activity Log and User Stats -->
                    <div class="row">
                        <!-- Activity Timeline -->
                        <div class="col-xl-8">
                            <div class="activity-card">
                                <div class="card-header bg-transparent border-bottom">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-timeline-view me-2"></i>Activity Timeline
                                        <small class="text-muted">(Latest 100 activities)</small>
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <?php if ($activities_result->num_rows === 0): ?>
                                    <div class="text-center py-5">
                                        <i class="ri-history-line fs-1 text-muted mb-3"></i>
                                        <h5 class="text-muted">No activities found</h5>
                                        <p class="text-muted">Try adjusting your search criteria or check back later.</p>
                                    </div>
                                    <?php else: ?>
                                    <div class="activity-timeline">
                                        <?php while ($activity = $activities_result->fetch_assoc()): ?>
                                        <div class="activity-item <?php echo strtolower($activity['action']); ?>" 
                                             onclick="showActivityDetails(<?php echo $activity['log_id']; ?>)">
                                            
                                            <div class="activity-header">
                                                <div class="activity-user">
                                                    <div class="user-avatar">
                                                        <?php 
                                                        $full_name = $activity['full_name'] ?? $activity['username'] ?? 'Unknown';
                                                        $name_parts = explode(' ', $full_name);
                                                        $initials = substr($name_parts[0], 0, 1) . (isset($name_parts[1]) ? substr($name_parts[1], 0, 1) : '');
                                                        echo strtoupper($initials);
                                                        ?>
                                                    </div>
                                                    <div class="user-info">
                                                        <h6><?php echo htmlspecialchars($full_name); ?></h6>
                                                        <div class="user-role"><?php echo htmlspecialchars($activity['role_name'] ?? 'No Role'); ?></div>
                                                    </div>
                                                </div>
                                                
                                                <div class="activity-time">
                                                    <?php 
                                                    $time_diff = time() - strtotime($activity['logged_at']);
                                                    if ($time_diff < 60) {
                                                        echo 'Just now';
                                                    } elseif ($time_diff < 3600) {
                                                        echo floor($time_diff / 60) . ' min ago';
                                                    } elseif ($time_diff < 86400) {
                                                        echo floor($time_diff / 3600) . ' hour' . (floor($time_diff / 3600) > 1 ? 's' : '') . ' ago';
                                                    } else {
                                                        echo date('M j, Y H:i', strtotime($activity['logged_at']));
                                                    }
                                                    ?>
                                                    <br>
                                                    <small class="text-muted"><?php echo date('H:i:s', strtotime($activity['logged_at'])); ?></small>
                                                </div>
                                            </div>
                                            
                                            <div class="activity-details">
                                                <div class="activity-action">
                                                    <span class="action-badge badge-<?php echo strtolower($activity['action']); ?>">
                                                        <?php echo $activity['action']; ?>
                                                    </span>
                                                    <span class="module-badge"><?php echo ucfirst($activity['module']); ?></span>
                                                </div>
                                                
                                                <div class="activity-description">
                                                    <?php 
                                                    $description = '';
                                                    switch ($activity['action']) {
                                                        case 'LOGIN':
                                                            $description = 'Successfully logged into the system';
                                                            break;
                                                        case 'LOGOUT':
                                                            $description = 'Logged out of the system';
                                                            break;
                                                        case 'CREATE':
                                                            $description = "Created new {$activity['module']} record" . ($activity['record_id'] ? " (ID: {$activity['record_id']})" : '');
                                                            break;
                                                        case 'UPDATE':
                                                            $description = "Updated {$activity['module']} record" . ($activity['record_id'] ? " (ID: {$activity['record_id']})" : '');
                                                            break;
                                                        case 'DELETE':
                                                            $description = "Deleted {$activity['module']} record" . ($activity['record_id'] ? " (ID: {$activity['record_id']})" : '');
                                                            break;
                                                        case 'EXPORT':
                                                            $description = "Exported {$activity['module']} data";
                                                            break;
                                                        case 'IMPORT':
                                                            $description = "Imported data into {$activity['module']}";
                                                            break;
                                                        case 'APPROVE':
                                                            $description = "Approved {$activity['module']} record" . ($activity['record_id'] ? " (ID: {$activity['record_id']})" : '');
                                                            break;
                                                        case 'REJECT':
                                                            $description = "Rejected {$activity['module']} record" . ($activity['record_id'] ? " (ID: {$activity['record_id']})" : '');
                                                            break;
                                                        default:
                                                            $description = "{$activity['action']} action performed on {$activity['module']}";
                                                    }
                                                    echo htmlspecialchars($description);
                                                    ?>
                                                </div>
                                            </div>
                                            
                                            <div class="activity-meta">
                                                <div class="meta-left">
                                                    <?php if ($activity['ip_address']): ?>
                                                    <span><i class="ri-map-pin-line me-1"></i><span class="ip-address"><?php echo htmlspecialchars($activity['ip_address']); ?></span></span>
                                                    <?php endif; ?>
                                                    
                                                    <?php if ($activity['record_id']): ?>
                                                    <span><i class="ri-hashtag me-1"></i>Record: <?php echo $activity['record_id']; ?></span>
                                                    <?php endif; ?>
                                                </div>
                                                
                                                <div class="meta-right">
                                                    <i class="ri-information-line me-1"></i>Click for details
                                                </div>
                                            </div>
                                        </div>
                                        <?php endwhile; ?>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Top Active Users -->
                        <div class="col-xl-4">
                            <div class="activity-card">
                                <div class="card-header bg-transparent border-bottom">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-user-star-line me-2"></i>Most Active Users
                                        <small class="text-muted">(Last 7 Days)</small>
                                    </h5>
                                </div>
                                <div class="card-body p-0">
                                    <div class="top-users-section">
                                        <?php if ($user_activity_result->num_rows === 0): ?>
                                        <div class="text-center py-4">
                                            <i class="ri-user-line fs-2 text-muted mb-2"></i>
                                            <p class="text-muted mb-0">No user activity in the last 7 days</p>
                                        </div>
                                        <?php else: ?>
                                        <?php while ($user_activity = $user_activity_result->fetch_assoc()): ?>
                                        <div class="user-activity-item">
                                            <div class="user-avatar">
                                                <?php 
                                                $name_parts = explode(' ', $user_activity['full_name']);
                                                $initials = substr($name_parts[0], 0, 1) . (isset($name_parts[1]) ? substr($name_parts[1], 0, 1) : '');
                                                echo strtoupper($initials);
                                                ?>
                                            </div>
                                            
                                            <div class="user-stats">
                                                <div class="user-name"><?php echo htmlspecialchars($user_activity['full_name']); ?></div>
                                                <div class="user-role-badge"><?php echo htmlspecialchars($user_activity['role_name']); ?></div>
                                                <div style="font-size: 0.7rem; color: #adb5bd; margin-top: 0.25rem;">
                                                    <i class="ri-time-line me-1"></i>
                                                    Last: <?php echo date('M j, H:i', strtotime($user_activity['last_activity'])); ?>
                                                </div>
                                            </div>
                                            
                                            <div class="activity-count">
                                                <div class="count-number"><?php echo $user_activity['activity_count']; ?></div>
                                                <div class="count-label">activities</div>
                                                <?php if ($user_activity['today_count'] > 0): ?>
                                                <div class="badge bg-success mt-1" style="font-size: 0.6rem;">
                                                    <?php echo $user_activity['today_count']; ?> today
                                                </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <?php endwhile; ?>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Quick Stats Card -->
                            <div class="activity-card">
                                <div class="card-header bg-transparent border-bottom">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-bar-chart-line me-2"></i>Quick Statistics
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="row text-center">
                                        <div class="col-6 mb-3">
                                            <div style="background: #e7f3ff; border-radius: 8px; padding: 1rem;">
                                                <div style="font-size: 1.5rem; font-weight: 700; color: #1e40af;">
                                                    <?php echo number_format(($stats['today_activities'] / max($stats['active_users'], 1)), 1); ?>
                                                </div>
                                                <div style="font-size: 0.8rem; color: #64748b;">Avg Activities/User</div>
                                            </div>
                                        </div>
                                        <div class="col-6 mb-3">
                                            <div style="background: #f0fdf4; border-radius: 8px; padding: 1rem;">
                                                <div style="font-size: 1.5rem; font-weight: 700; color: #059669;">
                                                    <?php echo $stats['today_logins']; ?>
                                                </div>
                                                <div style="font-size: 0.8rem; color: #64748b;">Logins Today</div>
                                            </div>
                                        </div>
                                        <div class="col-6">
                                            <div style="background: #fef3c7; border-radius: 8px; padding: 1rem;">
                                                <div style="font-size: 1.5rem; font-weight: 700; color: #d97706;">
                                                    <?php echo $stats['today_changes']; ?>
                                                </div>
                                                <div style="font-size: 0.8rem; color: #64748b;">Changes Today</div>
                                            </div>
                                        </div>
                                        <div class="col-6">
                                            <div style="background: #f3e8ff; border-radius: 8px; padding: 1rem;">
                                                <div style="font-size: 1.5rem; font-weight: 700; color: #7c3aed;">
                                                    <?php echo number_format(($stats['week_activities'] / 7), 1); ?>
                                                </div>
                                                <div style="font-size: 0.8rem; color: #64748b;">Daily Average</div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mt-3 pt-3 border-top">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <span class="text-muted" style="font-size: 0.8rem;">Last updated:</span>
                                            <span class="text-muted" style="font-size: 0.8rem;" id="lastUpdated">
                                                <?php echo date('H:i:s'); ?>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Activity Details Modal -->
    <div class="modal fade" id="activityDetailsModal" tabindex="-1" aria-labelledby="activityDetailsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="activityDetailsModalLabel">
                        <i class="ri-information-line me-2"></i>Activity Details
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="activityDetailsContent">
                    <div class="text-center py-4">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-2">Loading activity details...</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>
    
    <script>
$(document).ready(function() {
    // Auto-refresh activity log every 30 seconds
    setInterval(function() {
        if (!$('.modal').hasClass('show')) {
            updateLastRefreshTime();
        }
    }, 30000);
    
    // Initialize tooltips
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function(tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
});

// Show activity details
function showActivityDetails(logId) {
    $('#activityDetailsModal').modal('show');
    
    $.ajax({
        url: 'user_activity.php',
        method: 'GET',
        data: { get_activity_details: true, log_id: logId },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                const activity = response.data;
                const content = `
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label fw-bold text-primary">User Information:</label>
                            <div class="card border-0 bg-light">
                                <div class="card-body p-3">
                                    <div class="d-flex align-items-center">
                                        <div class="user-avatar me-3" style="width: 50px; height: 50px; font-size: 1.1rem;">
                                            ${getInitials(activity.full_name || activity.username || 'Unknown')}
                                        </div>
                                        <div>
                                            <h6 class="mb-1">${activity.full_name || activity.username || 'Unknown User'}</h6>
                                            <small class="text-muted">${activity.role_name || 'No Role'}</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label fw-bold text-primary">Activity Information:</label>
                            <div class="card border-0 bg-light">
                                <div class="card-body p-3">
                                    <div class="mb-2">
                                        <span class="action-badge badge-${activity.action.toLowerCase()}">${activity.action}</span>
                                        <span class="module-badge ms-2">${activity.module || 'N/A'}</span>
                                    </div>
                                    <small class="text-muted">
                                        <i class="ri-time-line me-1"></i>
                                        ${new Date(activity.logged_at).toLocaleString()}
                                    </small>
                                </div>
                            </div>
                        </div>
                        
                        ${activity.record_id ? `
                        <div class="col-md-6">
                            <label class="form-label fw-bold">Record ID:</label>
                            <div class="form-control-plaintext">
                                <span class="badge bg-info">${activity.record_id}</span>
                            </div>
                        </div>
                        ` : ''}
                        
                        ${activity.ip_address ? `
                        <div class="col-md-6">
                            <label class="form-label fw-bold">IP Address:</label>
                            <div class="form-control-plaintext">
                                <span class="ip-address">${activity.ip_address}</span>
                            </div>
                        </div>
                        ` : ''}
                        
                        ${activity.user_agent ? `
                        <div class="col-12">
                            <label class="form-label fw-bold">User Agent:</label>
                            <div class="form-control-plaintext">
                                <small class="text-muted" style="word-break: break-all;">${activity.user_agent}</small>
                            </div>
                        </div>
                        ` : ''}
                        
                        ${activity.old_values ? `
                        <div class="col-12">
                            <label class="form-label fw-bold text-warning">Previous Values:</label>
                            <div class="card border-warning bg-warning bg-opacity-10">
                                <div class="card-body p-3">
                                    <pre class="mb-0 small">${formatJsonData(activity.old_values)}</pre>
                                </div>
                            </div>
                        </div>
                        ` : ''}
                        
                        ${activity.new_values ? `
                        <div class="col-12">
                            <label class="form-label fw-bold text-success">New Values:</label>
                            <div class="card border-success bg-success bg-opacity-10">
                                <div class="card-body p-3">
                                    <pre class="mb-0 small">${formatJsonData(activity.new_values)}</pre>
                                </div>
                            </div>
                        </div>
                        ` : ''}
                        
                        ${activity.additional_info ? `
                        <div class="col-12">
                            <label class="form-label fw-bold">Additional Information:</label>
                            <div class="card border-info bg-info bg-opacity-10">
                                <div class="card-body p-3">
                                    <small>${activity.additional_info}</small>
                                </div>
                            </div>
                        </div>
                        ` : ''}
                    </div>
                `;
                
                $('#activityDetailsContent').html(content);
            } else {
                $('#activityDetailsContent').html(`
                    <div class="text-center py-4">
                        <i class="ri-error-warning-line fs-1 text-danger mb-3"></i>
                        <h5 class="text-danger">Error Loading Details</h5>
                        <p class="text-muted">${response.message}</p>
                    </div>
                `);
            }
        },
        error: function() {
            $('#activityDetailsContent').html(`
                <div class="text-center py-4">
                    <i class="ri-wifi-off-line fs-1 text-danger mb-3"></i>
                    <h5 class="text-danger">Connection Error</h5>
                    <p class="text-muted">Unable to load activity details. Please check your connection and try again.</p>
                </div>
            `);
        }
    });
}

// Helper function to get initials
function getInitials(name) {
    const names = name.split(' ');
    return names.map(n => n.charAt(0).toUpperCase()).join('').substring(0, 2);
}

// Helper function to format JSON data
function formatJsonData(jsonString) {
    try {
        const parsed = JSON.parse(jsonString);
        return JSON.stringify(parsed, null, 2);
    } catch (e) {
        return jsonString;
    }
}

// Refresh activity log
function refreshActivityLog() {
    Swal.fire({
        title: 'Refreshing Activity Log...',
        text: 'Loading the latest user activities.',
        icon: 'info',
        allowOutsideClick: false,
        showConfirmButton: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    setTimeout(() => {
        location.reload();
    }, 1500);
}

// Update last refresh time
function updateLastRefreshTime() {
    $('#lastUpdated').text(new Date().toLocaleTimeString());
}

// Export activity log
function exportActivityLog() {
    Swal.fire({
        title: 'Export Activity Log',
        html: `
            <div class="text-start">
                <div class="mb-3">
                    <label class="form-label fw-bold">Export Format:</label>
                    <select class="form-select" id="exportFormat">
                        <option value="excel">Excel Spreadsheet (.xlsx)</option>
                        <option value="pdf">PDF Report (.pdf)</option>
                        <option value="csv">CSV Data (.csv)</option>
                    </select>
                </div>
                
                <div class="mb-3">
                    <label class="form-label fw-bold">Date Range:</label>
                    <div class="row g-2">
                        <div class="col-6">
                            <label class="form-label small">From:</label>
                            <input type="date" class="form-control" id="exportDateFrom" 
                                   value="${new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]}">
                        </div>
                        <div class="col-6">
                            <label class="form-label small">To:</label>
                            <input type="date" class="form-control" id="exportDateTo" 
                                   value="${new Date().toISOString().split('T')[0]}">
                        </div>
                    </div>
                </div>
                
                <div class="mb-3">
                    <label class="form-label fw-bold">Include in Export:</label>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="includeUserDetails" checked>
                        <label class="form-check-label" for="includeUserDetails">User Details & Roles</label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="includeIPAddress" checked>
                        <label class="form-check-label" for="includeIPAddress">IP Addresses</label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="includeUserAgent">
                        <label class="form-check-label" for="includeUserAgent">User Agent Information</label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="includeChangeData" checked>
                        <label class="form-check-label" for="includeChangeData">Change Data (Old/New Values)</label>
                    </div>
                </div>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: '<i class="ri-download-line me-1"></i>Export',
        cancelButtonText: 'Cancel',
        width: '500px',
        preConfirm: () => {
            const dateFrom = document.getElementById('exportDateFrom').value;
            const dateTo = document.getElementById('exportDateTo').value;
            
            if (!dateFrom || !dateTo) {
                Swal.showValidationMessage('Please select both start and end dates');
                return false;
            }
            
            if (new Date(dateFrom) > new Date(dateTo)) {
                Swal.showValidationMessage('Start date cannot be later than end date');
                return false;
            }
            
            return {
                format: document.getElementById('exportFormat').value,
                dateFrom: dateFrom,
                dateTo: dateTo,
                includeUserDetails: document.getElementById('includeUserDetails').checked,
                includeIPAddress: document.getElementById('includeIPAddress').checked,
                includeUserAgent: document.getElementById('includeUserAgent').checked,
                includeChangeData: document.getElementById('includeChangeData').checked
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const { format, dateFrom, dateTo } = result.value;
            
            Swal.fire({
                title: 'Generating Export...',
                html: `
                    <div class="text-center">
                        <div class="spinner-border text-primary mb-3" role="status"></div>
                        <p>Preparing your activity log export...</p>
                        <small class="text-muted">This may take a few moments for large datasets.</small>
                    </div>
                `,
                allowOutsideClick: false,
                showConfirmButton: false,
                didOpen: () => {
                    // Simulate export generation
                    setTimeout(() => {
                        Swal.close();
                        
                        // Trigger download (in real implementation, this would call your export endpoint)
                        const link = document.createElement('a');
                        link.href = `exports/activity_log_export.php?format=${format}&date_from=${dateFrom}&date_to=${dateTo}`;
                        link.download = `activity_log_${dateFrom}_to_${dateTo}.${format}`;
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                        
                        Swal.fire({
                            title: 'Export Complete!',
                            text: 'Your activity log has been exported successfully.',
                            icon: 'success',
                            timer: 3000,
                            showConfirmButton: false
                        });
                    }, 2500);
                }
            });
        }
    });
}

// Clear old logs
function clearOldLogs() {
    Swal.fire({
        title: 'Clear Old Activity Logs',
        html: `
            <div class="text-start">
                <div class="mb-3">
                    <label class="form-label fw-bold">Clear logs older than:</label>
                    <select class="form-select" id="clearPeriod">
                        <option value="30">30 days (1 month)</option>
                        <option value="60">60 days (2 months)</option>
                        <option value="90" selected>90 days (3 months)</option>
                        <option value="180">180 days (6 months)</option>
                        <option value="365">365 days (1 year)</option>
                    </select>
                </div>
                
                <div class="alert alert-warning d-flex align-items-start">
                    <i class="ri-warning-line me-2 flex-shrink-0 mt-1"></i>
                    <div>
                        <strong>Warning:</strong> This action cannot be undone. Old activity logs will be permanently deleted from the database.
                    </div>
                </div>
                
                <div class="alert alert-info d-flex align-items-start">
                    <i class="ri-information-line me-2 flex-shrink-0 mt-1"></i>
                    <div>
                        <strong>Note:</strong> It's recommended to export logs before deletion for archive purposes.
                    </div>
                </div>
            </div>
        `,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: '<i class="ri-delete-bin-line me-1"></i>Clear Logs',
        cancelButtonText: 'Cancel',
        confirmButtonColor: '#dc3545',
        width: '500px',
        preConfirm: () => {
            return {
                period: document.getElementById('clearPeriod').value
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const { period } = result.value;
            
            Swal.fire({
                title: 'Clearing Old Logs...',
                html: `
                    <div class="text-center">
                        <div class="spinner-border text-danger mb-3" role="status"></div>
                        <p>Deleting activity logs older than ${period} days...</p>
                        <small class="text-muted">Please wait while we clean up the database.</small>
                    </div>
                `,
                allowOutsideClick: false,
                showConfirmButton: false,
                didOpen: () => {
                    // Make AJAX request to clear logs
                    $.ajax({
                        url: 'user_activity.php',
                        method: 'POST',
                        data: {
                            action: 'clear_logs',
                            days: period
                        },
                        dataType: 'json',
                        success: function(response) {
                            if (response.success) {
                                Swal.fire({
                                    title: 'Logs Cleared Successfully!',
                                    html: `
                                        <div class="text-center">
                                            <i class="ri-check-line text-success fs-1 mb-3"></i>
                                            <p><strong>${response.deleted_count}</strong> old activity records have been successfully removed.</p>
                                            <small class="text-muted">The page will refresh to show updated data.</small>
                                        </div>
                                    `,
                                    icon: 'success',
                                    timer: 3000,
                                    showConfirmButton: false
                                }).then(() => {
                                    location.reload();
                                });
                            } else {
                                Swal.fire({
                                    title: 'Error',
                                    text: response.message || 'Failed to clear logs. Please try again.',
                                    icon: 'error'
                                });
                            }
                        },
                        error: function() {
                            Swal.fire({
                                title: 'Connection Error',
                                text: 'Unable to clear logs. Please check your connection and try again.',
                                icon: 'error'
                            });
                        }
                    });
                }
            });
        }
    });
}

// Keyboard shortcuts
document.addEventListener('keydown', function(e) {
    // Ctrl/Cmd + R for refresh
    if ((e.ctrlKey || e.metaKey) && e.key === 'r') {
        e.preventDefault();
        refreshActivityLog();
    }
    
    // Ctrl/Cmd + E for export
    if ((e.ctrlKey || e.metaKey) && e.key === 'e') {
        e.preventDefault();
        exportActivityLog();
    }
    
    // ESC to close modals
    if (e.key === 'Escape') {
        $('.modal').modal('hide');
    }
});

// Real-time activity updates indicator
let lastActivityCheck = new Date().getTime();
setInterval(function() {
    const now = new Date().getTime();
    if (now - lastActivityCheck > 60000) { // Check every minute
        const liveIndicator = document.querySelector('.live-indicator i');
        if (liveIndicator) {
            liveIndicator.style.animation = 'pulse 0.8s ease-in-out 3';
            setTimeout(() => {
                liveIndicator.style.animation = 'pulse 2s infinite';
            }, 2400);
        }
        lastActivityCheck = now;
    }
}, 60000);

// Smooth scroll to top when refreshing
function scrollToTop() {
    window.scrollTo({
        top: 0,
        behavior: 'smooth'
    });
}

// Add loading state to refresh button
function setRefreshLoading(loading) {
    const refreshBtn = document.querySelector('.refresh-btn');
    if (loading) {
        refreshBtn.innerHTML = '<i class="ri-loader-4-line me-1 spin"></i>Refreshing...';
        refreshBtn.disabled = true;
    } else {
        refreshBtn.innerHTML = '<i class="ri-refresh-line me-1"></i>Refresh';
        refreshBtn.disabled = false;
    }
}

// Enhanced refresh with loading state
function refreshActivityLog() {
    setRefreshLoading(true);
    scrollToTop();
    
    Swal.fire({
        title: 'Refreshing Activity Log...',
        text: 'Loading the latest user activities.',
        icon: 'info',
        allowOutsideClick: false,
        showConfirmButton: false,
        timer: 1500,
        didOpen: () => {
            Swal.showLoading();
        }
    }).then(() => {
        location.reload();
    });
}

// Initialize page
document.addEventListener('DOMContentLoaded', function() {
    // Add CSS for spinning animation
    const style = document.createElement('style');
    style.textContent = `
        .spin {
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
    `;
    document.head.appendChild(style);
    
    // Show welcome message for first-time visitors
    if (sessionStorage.getItem('activityLogFirstVisit') !== 'true') {
        setTimeout(() => {
            Swal.fire({
                title: 'Welcome to Activity Log!',
                html: `
                    <div class="text-start">
                        <p>This page shows real-time user activity across your freight management system.</p>
                        <ul class="small text-muted">
                            <li>Click on any activity item to view detailed information</li>
                            <li>Use filters to narrow down specific activities</li>
                            <li>Export logs for compliance and auditing</li>
                            <li>The page automatically updates with new activities</li>
                        </ul>
                        <p class="small text-info mb-0"><i class="ri-lightbulb-line me-1"></i>Tip: Use Ctrl+R to refresh or Ctrl+E to export!</p>
                    </div>
                `,
                icon: 'info',
                confirmButtonText: 'Got it!',
                showClass: {
                    popup: 'animate__animated animate__fadeInDown'
                },
                hideClass: {
                    popup: 'animate__animated animate__fadeOutUp'
                }
            });
            sessionStorage.setItem('activityLogFirstVisit', 'true');
        }, 1000);
    }
});
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>