<?php
// Include session handling
include 'services/session.php'; 

// Check if user is logged in
if (!$_SESSION['user'] || !isset($_SESSION['user'])) {
    header('Location: auth-login.php?error=session_expired');
    exit();
}

// Get user role and permissions
$user_role = $_SESSION['role_name'] ?? 'Customer';
$user_id = $_SESSION['user_id'] ?? 0;

// Check if user has permission to view activity logs
if (!in_array($user_role, ['Administrator', 'Support Agent'])) {
    $_SESSION['error'] = "You don't have permission to access this page.";
    header('Location: dashboard.php');
    exit();
}

// Include database connection
require_once 'layouts/dbconn.php';

$page_title = "User Activity Log";
$page_description = "Monitor user activities and system events";

// Pagination settings
$records_per_page = 50;
$current_page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($current_page - 1) * $records_per_page;

// Filter parameters
$user_filter = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;
$action_filter = isset($_GET['action']) ? trim($_GET['action']) : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';

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

if ($user_filter > 0) {
    $where_conditions[] = "al.user_id = ?";
    $params[] = $user_filter;
    $param_types .= "i";
}

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

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

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

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

// Get total count for pagination
$count_query = "SELECT COUNT(*) as total FROM activity_log al $where_clause";
$count_stmt = $conn->prepare($count_query);
if (!empty($params)) {
    $count_stmt->bind_param($param_types, ...$params);
}
$count_stmt->execute();
$total_records = $count_stmt->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_records / $records_per_page);

// Get activity logs
$activity_query = "
    SELECT 
        al.log_id,
        al.user_id,
        al.action,
        al.details,
        al.ip_address,
        al.user_agent,
        al.created_at,
        u.username,
        u.full_name,
        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_clause
    ORDER BY al.created_at DESC
    LIMIT ? OFFSET ?
";

$activity_stmt = $conn->prepare($activity_query);
$final_params = $params;
$final_param_types = $param_types . "ii";
$final_params[] = $records_per_page;
$final_params[] = $offset;

if (!empty($final_params)) {
    $activity_stmt->bind_param($final_param_types, ...$final_params);
}
$activity_stmt->execute();
$activity_result = $activity_stmt->get_result();

// Get users for filter dropdown
$users_query = "
    SELECT u.user_id, u.username, u.full_name, ur.role_name 
    FROM users u 
    LEFT JOIN user_roles ur ON u.role_id = ur.role_id 
    ORDER BY u.full_name
";
$users_result = $conn->query($users_query);

// Get distinct actions for filter
$actions_query = "SELECT DISTINCT action FROM activity_log ORDER BY action";
$actions_result = $conn->query($actions_query);

// Get activity summary for today
$today_stats_query = "
    SELECT 
        COUNT(*) as total_activities,
        COUNT(DISTINCT user_id) as active_users,
        SUM(CASE WHEN action LIKE '%login%' THEN 1 ELSE 0 END) as logins,
        SUM(CASE WHEN action LIKE '%failed%' OR action LIKE '%error%' THEN 1 ELSE 0 END) as failed_attempts
    FROM activity_log 
    WHERE DATE(created_at) = CURDATE()
";
$today_stats = $conn->query($today_stats_query)->fetch_assoc();

// Function to get activity icon
function getActivityIcon($action) {
    $action = strtolower($action);
    if (strpos($action, 'login') !== false) return 'mdi-login text-success';
    if (strpos($action, 'logout') !== false) return 'mdi-logout text-info';
    if (strpos($action, 'create') !== false) return 'mdi-plus-circle text-primary';
    if (strpos($action, 'update') !== false) return 'mdi-pencil text-warning';
    if (strpos($action, 'delete') !== false) return 'mdi-delete text-danger';
    if (strpos($action, 'download') !== false) return 'mdi-download text-info';
    if (strpos($action, 'upload') !== false) return 'mdi-upload text-info';
    if (strpos($action, 'payment') !== false) return 'mdi-credit-card text-success';
    if (strpos($action, 'failed') !== false || strpos($action, 'error') !== false) return 'mdi-alert-circle text-danger';
    return 'mdi-information text-muted';
}

// Function to get activity color class
function getActivityColorClass($action) {
    $action = strtolower($action);
    if (strpos($action, 'failed') !== false || strpos($action, 'error') !== false) return 'border-danger';
    if (strpos($action, 'login') !== false) return 'border-success';
    if (strpos($action, 'payment') !== false) return 'border-success';
    if (strpos($action, 'delete') !== false) return 'border-warning';
    return 'border-info';
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <title><?php echo $page_title; ?> | MoMo Platform</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta content="User activity monitoring for MoMo Platform" name="description" />
    <meta content="MoMo Platform" name="author" />
    
    <!-- App favicon -->
    <link rel="shortcut icon" href="assets/images/favicon.ico">

    <!-- App CSS -->
    <link href="assets/css/icons.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/css/app.min.css" rel="stylesheet" type="text/css" id="app-style"/>
</head>

<body class="loading" data-layout-color="light" data-leftbar-theme="dark" data-layout-mode="fluid" data-rightbar-onstart="true">

    <!-- Begin page -->
    <div class="wrapper">

        <!-- ========== Left Sidebar Start ========== -->
        <?php include 'layouts/left-sidebar.php'; ?>
        <!-- Left Sidebar End -->

        <!-- ============================================================== -->
        <!-- Start Page Content here -->
        <!-- ============================================================== -->

        <div class="content-page">
            <div class="content">

                <!-- Topbar Start -->
                <?php include 'layouts/topbar.php'; ?>
                <!-- end Topbar -->

                <!-- Start Content-->
                <div class="container-fluid">
                    
                    <!-- start page title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box">
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="admin-dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="#">Users & Customers</a></li>
                                        <li class="breadcrumb-item active">Activity Log</li>
                                    </ol>
                                </div>
                                <h4 class="page-title"><?php echo $page_title; ?></h4>
                            </div>
                        </div>
                    </div>
                    <!-- end page title -->

                    <!-- Today's Summary Stats -->
                    <div class="row">
                        <div class="col-md-3">
                            <div class="card widget-flat">
                                <div class="card-body">
                                    <div class="float-end">
                                        <i class="mdi mdi-chart-line widget-icon"></i>
                                    </div>
                                    <h5 class="text-muted fw-normal mt-0" title="Total Activities Today">Total Activities</h5>
                                    <h3 class="mt-3 mb-3"><?php echo number_format($today_stats['total_activities']); ?></h3>
                                    <p class="mb-0 text-muted">
                                        <span class="text-nowrap">Today</span>
                                    </p>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="card widget-flat">
                                <div class="card-body">
                                    <div class="float-end">
                                        <i class="mdi mdi-account-group widget-icon bg-success-lighten text-success"></i>
                                    </div>
                                    <h5 class="text-muted fw-normal mt-0" title="Active Users Today">Active Users</h5>
                                    <h3 class="mt-3 mb-3"><?php echo number_format($today_stats['active_users']); ?></h3>
                                    <p class="mb-0 text-muted">
                                        <span class="text-nowrap">Today</span>
                                    </p>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="card widget-flat">
                                <div class="card-body">
                                    <div class="float-end">
                                        <i class="mdi mdi-login widget-icon bg-info-lighten text-info"></i>
                                    </div>
                                    <h5 class="text-muted fw-normal mt-0" title="Logins Today">Logins</h5>
                                    <h3 class="mt-3 mb-3"><?php echo number_format($today_stats['logins']); ?></h3>
                                    <p class="mb-0 text-muted">
                                        <span class="text-nowrap">Today</span>
                                    </p>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="card widget-flat">
                                <div class="card-body">
                                    <div class="float-end">
                                        <i class="mdi mdi-alert-circle widget-icon bg-danger-lighten text-danger"></i>
                                    </div>
                                    <h5 class="text-muted fw-normal mt-0" title="Failed Attempts Today">Failed Attempts</h5>
                                    <h3 class="mt-3 mb-3"><?php echo number_format($today_stats['failed_attempts']); ?></h3>
                                    <p class="mb-0 text-muted">
                                        <span class="text-nowrap">Today</span>
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <form method="GET" class="row g-3">
                                        <div class="col-md-3">
                                            <label for="user_id" class="form-label">User</label>
                                            <select class="form-select" id="user_id" name="user_id">
                                                <option value="">All Users</option>
                                                <?php while ($user = $users_result->fetch_assoc()): ?>
                                                    <option value="<?php echo $user['user_id']; ?>" 
                                                            <?php echo $user_filter == $user['user_id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($user['full_name']); ?> 
                                                        (<?php echo htmlspecialchars($user['role_name']); ?>)
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label for="action" class="form-label">Action</label>
                                            <select class="form-select" id="action" name="action">
                                                <option value="">All Actions</option>
                                                <?php while ($action = $actions_result->fetch_assoc()): ?>
                                                    <option value="<?php echo htmlspecialchars($action['action']); ?>" 
                                                            <?php echo $action_filter === $action['action'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($action['action']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label for="date_from" class="form-label">From Date</label>
                                            <input type="date" class="form-control" id="date_from" name="date_from" 
                                                   value="<?php echo htmlspecialchars($date_from); ?>">
                                        </div>
                                        <div class="col-md-2">
                                            <label for="date_to" class="form-label">To Date</label>
                                            <input type="date" class="form-control" id="date_to" name="date_to" 
                                                   value="<?php echo htmlspecialchars($date_to); ?>">
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">&nbsp;</label>
                                            <div class="d-grid">
                                                <button type="submit" class="btn btn-primary">
                                                    <i class="mdi mdi-filter-variant"></i> Filter
                                                </button>
                                            </div>
                                        </div>
                                        <div class="col-md-1">
                                            <label class="form-label">&nbsp;</label>
                                            <div class="d-grid">
                                                <a href="user-activity.php" class="btn btn-outline-secondary">
                                                    <i class="mdi mdi-refresh"></i>
                                                </a>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Activity Timeline -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <h5 class="header-title mb-4">
                                        <i class="mdi mdi-timeline-clock me-2"></i>Activity Timeline
                                        <span class="text-muted small ms-2">(Showing <?php echo $total_records; ?> activities)</span>
                                    </h5>
                                    <div class="timeline-container">
                                        <?php if ($activity_result->num_rows > 0): ?>
                                            <?php while ($activity = $activity_result->fetch_assoc()): ?>
                                                <div class="timeline-item border-start <?php echo getActivityColorClass($activity['action']); ?> ps-3 pb-4">
                                                    <div class="timeline-marker">
                                                        <i class="mdi <?php echo getActivityIcon($activity['action']); ?>"></i>
                                                    </div>
                                                    <div class="timeline-content">
                                                        <div class="d-flex justify-content-between align-items-start">
                                                            <div class="flex-grow-1">
                                                                <h6 class="mb-1 fw-semibold"><?php echo htmlspecialchars($activity['action']); ?></h6>
                                                                <div class="d-flex align-items-center mb-2">
                                                                    <?php if ($activity['username']): ?>
                                                                        <div class="avatar-xs bg-primary rounded-circle d-flex align-items-center justify-content-center me-2">
                                                                            <span class="text-white fw-bold" style="font-size: 10px;">
                                                                                <?php echo strtoupper(substr($activity['full_name'] ?: $activity['username'], 0, 2)); ?>
                                                                            </span>
                                                                        </div>
                                                                        <span class="text-muted small me-2">
                                                                            <?php echo htmlspecialchars($activity['full_name'] ?: $activity['username']); ?>
                                                                        </span>
                                                                        <span class="badge bg-info-lighten text-info small">
                                                                            <?php echo htmlspecialchars($activity['role_name'] ?: 'Unknown'); ?>
                                                                        </span>
                                                                    <?php else: ?>
                                                                        <span class="text-muted small">System</span>
                                                                    <?php endif; ?>
                                                                </div>
                                                                
                                                                <?php if (!empty($activity['details'])): ?>
                                                                    <div class="alert alert-light border py-2 px-3 mb-2">
                                                                        <small class="mb-0"><?php echo htmlspecialchars($activity['details']); ?></small>
                                                                    </div>
                                                                <?php endif; ?>
                                                                
                                                                <div class="d-flex align-items-center text-muted small">
                                                                    <i class="mdi mdi-clock-outline me-1"></i>
                                                                    <span class="me-3"><?php echo date('M j, Y g:i A', strtotime($activity['created_at'])); ?></span>
                                                                    
                                                                    <?php if (!empty($activity['ip_address'])): ?>
                                                                        <i class="mdi mdi-ip-network-outline me-1"></i>
                                                                        <span class="me-3"><?php echo htmlspecialchars($activity['ip_address']); ?></span>
                                                                    <?php endif; ?>
                                                                    
                                                                    <?php if (!empty($activity['user_agent'])): ?>
                                                                        <i class="mdi mdi-monitor me-1"></i>
                                                                        <span class="text-truncate" style="max-width: 200px;" 
                                                                              title="<?php echo htmlspecialchars($activity['user_agent']); ?>">
                                                                            <?php echo htmlspecialchars(substr($activity['user_agent'], 0, 50)); ?>...
                                                                        </span>
                                                                    <?php endif; ?>
                                                                </div>
                                                            </div>
                                                            <div class="text-end">
                                                                <small class="text-muted">
                                                                    <?php echo time_elapsed_string($activity['created_at']); ?>
                                                                </small>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            <?php endwhile; ?>
                                        <?php else: ?>
                                            <div class="text-center py-5">
                                                <div class="text-muted">
                                                    <i class="mdi mdi-timeline-clock display-4"></i>
                                                    <p class="mt-3">No activity found matching your criteria.</p>
                                                    <a href="user-activity.php" class="btn btn-primary btn-sm">View All Activities</a>
                                                </div>
                                            </div>
                                        <?php endif; ?>
                                    </div>

                                    <!-- Pagination -->
                                    <?php if ($total_pages > 1): ?>
                                        <div class="row">
                                            <div class="col-12">
                                                <div class="d-flex justify-content-between align-items-center mt-4 pt-3 border-top">
                                                    <div class="text-muted">
                                                        Showing <?php echo (($current_page - 1) * $records_per_page + 1); ?> to 
                                                        <?php echo min($current_page * $records_per_page, $total_records); ?> of 
                                                        <?php echo $total_records; ?> activities
                                                    </div>
                                                    <nav aria-label="Page navigation">
                                                        <ul class="pagination pagination-sm mb-0">
                                                            <?php if ($current_page > 1): ?>
                                                                <li class="page-item">
                                                                    <a class="page-link" href="?page=<?php echo ($current_page - 1); ?>&<?php echo http_build_query(array_filter($_GET)); ?>">
                                                                        <i class="mdi mdi-chevron-left"></i>
                                                                    </a>
                                                                </li>
                                                            <?php endif; ?>

                                                            <?php
                                                            $start_page = max(1, $current_page - 2);
                                                            $end_page = min($total_pages, $current_page + 2);
                                                            
                                                            for ($i = $start_page; $i <= $end_page; $i++):
                                                            ?>
                                                                <li class="page-item <?php echo ($i == $current_page) ? 'active' : ''; ?>">
                                                                    <a class="page-link" href="?page=<?php echo $i; ?>&<?php echo http_build_query(array_filter($_GET)); ?>">
                                                                        <?php echo $i; ?>
                                                                    </a>
                                                                </li>
                                                            <?php endfor; ?>

                                                            <?php if ($current_page < $total_pages): ?>
                                                                <li class="page-item">
                                                                    <a class="page-link" href="?page=<?php echo ($current_page + 1); ?>&<?php echo http_build_query(array_filter($_GET)); ?>">
                                                                        <i class="mdi mdi-chevron-right"></i>
                                                                    </a>
                                                                </li>
                                                            <?php endif; ?>
                                                        </ul>
                                                    </nav>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                </div> <!-- container -->

            </div> <!-- content -->

            <!-- Footer Start -->
            <?php include 'layouts/footer.php'; ?>
            <!-- end Footer -->

        </div>

    </div>
    <!-- END wrapper -->

    <!-- Right Sidebar -->
    <?php include 'layouts/right-sidebar.php'; ?>

    <!-- bundle -->
    <script src="assets/js/vendor.min.js"></script>
    <script src="assets/js/app.min.js"></script>

    <script>
        $(document).ready(function() {
            // Auto-submit form when filters change
            $('#user_id, #action').on('change', function() {
                $(this).closest('form').submit();
            });
            
            // Auto-refresh every 30 seconds for real-time updates
            setInterval(function() {
                const urlParams = new URLSearchParams(window.location.search);
                if (!urlParams.toString()) {
                    // Only auto-refresh if no filters are applied
                    window.location.reload();
                }
            }, 30000);
            
            // Initialize tooltips
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
            var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl);
            });
        });
    </script>

    <style>
        .timeline-container {
            position: relative;
        }
        
        .timeline-item {
            position: relative;
            border-left-width: 3px !important;
            margin-left: 1rem;
        }
        
        .timeline-marker {
            position: absolute;
            left: -12px;
            top: 8px;
            width: 20px;
            height: 20px;
            background: white;
            border: 2px solid #dee2e6;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .timeline-marker i {
            font-size: 12px;
        }
        
        .timeline-content {
            margin-left: 1rem;
        }
        
        .avatar-xs {
            width: 24px;
            height: 24px;
        }
        
        /* Timeline border colors */
        .border-success {
            border-left-color: #28a745 !important;
        }
        
        .border-success .timeline-marker {
            border-color: #28a745;
            background-color: #d4edda;
        }
        
        .border-info {
            border-left-color: #17a2b8 !important;
        }
        
        .border-info .timeline-marker {
            border-color: #17a2b8;
            background-color: #d1ecf1;
        }
        
        .border-warning {
            border-left-color: #ffc107 !important;
        }
        
        .border-warning .timeline-marker {
            border-color: #ffc107;
            background-color: #fff3cd;
        }
        
        .border-danger {
            border-left-color: #dc3545 !important;
        }
        
        .border-danger .timeline-marker {
            border-color: #dc3545;
            background-color: #f8d7da;
        }
    </style>

</body>
</html>

<?php
// Helper function for time elapsed
function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}
?>