<?php
session_start();
require_once 'config/config.php';
require_once 'auth/check_auth.php';

if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

$pageTitle = 'Online Status & Activity Tracking';
$currentPage = 'activity-tracking';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?php echo $pageTitle; ?> | KSO Chandigarh</title>
    
    <!-- AdminLTE CSS -->
    <link rel="stylesheet" href="dist/css/adminlte.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    
    <style>
        .activity-dashboard {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .online-indicator {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 8px;
        }
        
        .online-indicator.online {
            background-color: #28a745;
            box-shadow: 0 0 0 2px rgba(40, 167, 69, 0.3);
        }
        
        .online-indicator.offline {
            background-color: #dc3545;
        }
        
        .online-indicator.away {
            background-color: #ffc107;
        }
        
        .user-activity-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            border-left: 4px solid #007bff;
        }
        
        .activity-timeline {
            max-height: 400px;
            overflow-y: auto;
            padding: 10px;
        }
        
        .timeline-item {
            display: flex;
            align-items: center;
            padding: 10px 0;
            border-bottom: 1px solid #eee;
        }
        
        .timeline-item:last-child {
            border-bottom: none;
        }
        
        .timeline-icon {
            width: 35px;
            height: 35px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 15px;
            color: white;
            font-size: 14px;
        }
        
        .timeline-icon.login {
            background-color: #28a745;
        }
        
        .timeline-icon.logout {
            background-color: #dc3545;
        }
        
        .timeline-icon.activity {
            background-color: #007bff;
        }
        
        .real-time-stats {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .location-map {
            height: 300px;
            border-radius: 10px;
            border: 1px solid #ddd;
        }
        
        .session-card {
            background: white;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            border-left: 3px solid #007bff;
        }
        
        .heatmap-container {
            background: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
    </style>
</head>

<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
    <!-- Include header -->
    <?php include 'templates/header.php'; ?>
    
    <!-- Include sidebar -->
    <?php include 'templates/sidebar.php'; ?>
    
    <!-- Content Wrapper -->
    <div class="content-wrapper">
        <!-- Content Header -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0">
                            <i class="fas fa-chart-line text-primary"></i> Online Status & Activity Tracking
                        </h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                            <li class="breadcrumb-item active">Activity Tracking</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>

        <!-- Main content -->
        <section class="content">
            <div class="container-fluid">
                
                <!-- Activity Dashboard -->
                <div class="activity-dashboard">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="text-center">
                                <h3 class="mb-1" id="onlineUsers">0</h3>
                                <p class="mb-0">Online Now</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="text-center">
                                <h3 class="mb-1" id="totalSessions">0</h3>
                                <p class="mb-0">Total Sessions</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="text-center">
                                <h3 class="mb-1" id="avgSessionTime">0</h3>
                                <p class="mb-0">Avg Session Time</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="text-center">
                                <h3 class="mb-1" id="totalActivities">0</h3>
                                <p class="mb-0">Activities Today</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Real-time Activity Feed -->
                <div class="row">
                    <div class="col-md-8">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">
                                    <i class="fas fa-stream"></i> Real-time Activity Feed
                                </h3>
                                <div class="card-tools">
                                    <button class="btn btn-sm btn-primary" onclick="toggleAutoRefresh()">
                                        <i class="fas fa-sync" id="refreshIcon"></i> Auto Refresh
                                    </button>
                                </div>
                            </div>
                            <div class="card-body">
                                <div class="activity-timeline" id="activityTimeline">
                                    <!-- Activity items will be loaded here -->
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">
                                    <i class="fas fa-users"></i> Online Users
                                </h3>
                            </div>
                            <div class="card-body">
                                <div id="onlineUsersList">
                                    <!-- Online users will be loaded here -->
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Activity Analytics -->
                <div class="row">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">
                                    <i class="fas fa-chart-bar"></i> Activity Heatmap
                                </h3>
                            </div>
                            <div class="card-body">
                                <div class="heatmap-container">
                                    <canvas id="activityHeatmap" width="400" height="300"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">
                                    <i class="fas fa-clock"></i> Session Duration Chart
                                </h3>
                            </div>
                            <div class="card-body">
                                <canvas id="sessionChart" width="400" height="300"></canvas>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Active Sessions -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-desktop"></i> Active Sessions
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="row" id="activeSessions">
                            <!-- Active sessions will be loaded here -->
                        </div>
                    </div>
                </div>

                <!-- Location Tracking -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-map-marker-alt"></i> User Location Tracking
                        </h3>
                    </div>
                    <div class="card-body">
                        <div id="locationMap" class="location-map">
                            <!-- Map will be loaded here -->
                        </div>
                    </div>
                </div>

            </div>
        </section>
    </div>
</div>

<!-- Include footer -->
<?php include 'templates/footer.php'; ?>

<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="dist/js/adminlte.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@2.29.4/moment.min.js"></script>

<script>
// Activity Tracking System
let autoRefreshInterval = null;
let isAutoRefreshEnabled = false;

$(document).ready(function() {
    loadActivityStats();
    loadActivityTimeline();
    loadOnlineUsers();
    loadActiveSessions();
    loadActivityHeatmap();
    loadSessionChart();
    initializeLocationMap();
    
    // Start auto refresh
    toggleAutoRefresh();
});

function loadActivityStats() {
    $.ajax({
        url: 'api/activity/stats.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                $('#onlineUsers').text(response.stats.online_users);
                $('#totalSessions').text(response.stats.total_sessions);
                $('#avgSessionTime').text(response.stats.avg_session_time);
                $('#totalActivities').text(response.stats.total_activities);
            }
        }
    });
}

function loadActivityTimeline() {
    $.ajax({
        url: 'api/activity/timeline.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const timeline = $('#activityTimeline');
                timeline.empty();
                
                response.activities.forEach(function(activity) {
                    timeline.append(createTimelineItem(activity));
                });
            }
        }
    });
}

function createTimelineItem(activity) {
    const iconClass = getActivityIcon(activity.type);
    const timeAgo = moment(activity.timestamp).fromNow();
    
    return `
        <div class="timeline-item">
            <div class="timeline-icon ${activity.type}">
                <i class="fas ${iconClass}"></i>
            </div>
            <div class="timeline-content">
                <h6 class="mb-1">${activity.user_name}</h6>
                <p class="text-muted mb-1">${activity.description}</p>
                <small class="text-muted">${timeAgo}</small>
            </div>
        </div>
    `;
}

function getActivityIcon(type) {
    switch(type) {
        case 'login': return 'fa-sign-in-alt';
        case 'logout': return 'fa-sign-out-alt';
        case 'activity': return 'fa-mouse-pointer';
        default: return 'fa-circle';
    }
}

function loadOnlineUsers() {
    $.ajax({
        url: 'api/activity/online-users.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const usersList = $('#onlineUsersList');
                usersList.empty();
                
                response.users.forEach(function(user) {
                    usersList.append(createOnlineUserCard(user));
                });
            }
        }
    });
}

function createOnlineUserCard(user) {
    const statusClass = user.status === 'online' ? 'online' : (user.status === 'away' ? 'away' : 'offline');
    const lastSeen = user.last_activity ? moment(user.last_activity).fromNow() : 'Never';
    
    return `
        <div class="user-activity-card">
            <div class="d-flex align-items-center">
                <span class="online-indicator ${statusClass}"></span>
                <div class="flex-grow-1">
                    <h6 class="mb-0">${user.name}</h6>
                    <small class="text-muted">${user.kso_id}</small>
                </div>
                <div class="text-right">
                    <small class="text-muted">${lastSeen}</small>
                </div>
            </div>
        </div>
    `;
}

function loadActiveSessions() {
    $.ajax({
        url: 'api/activity/sessions.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const sessions = $('#activeSessions');
                sessions.empty();
                
                response.sessions.forEach(function(session) {
                    sessions.append(createSessionCard(session));
                });
            }
        }
    });
}

function createSessionCard(session) {
    const duration = moment.duration(moment().diff(moment(session.start_time))).humanize();
    
    return `
        <div class="col-md-6">
            <div class="session-card">
                <div class="row">
                    <div class="col-md-8">
                        <h6 class="mb-1">${session.user_name}</h6>
                        <p class="text-muted mb-1">IP: ${session.ip_address}</p>
                        <p class="text-muted mb-0">Device: ${session.device_info}</p>
                    </div>
                    <div class="col-md-4 text-right">
                        <p class="mb-1"><strong>${duration}</strong></p>
                        <button class="btn btn-sm btn-danger" onclick="terminateSession('${session.session_id}')">
                            <i class="fas fa-times"></i> End
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;
}

function terminateSession(sessionId) {
    if (confirm('Are you sure you want to terminate this session?')) {
        $.ajax({
            url: 'api/activity/terminate-session.php',
            method: 'POST',
            data: { session_id: sessionId },
            success: function(response) {
                if (response.success) {
                    if (window.ksoToast) {
                        window.ksoToast.success('Session terminated successfully');
                    }
                    loadActiveSessions();
                    loadOnlineUsers();
                } else {
                    if (window.ksoToast) {
                        window.ksoToast.error('Failed to terminate session');
                    }
                }
            }
        });
    }
}

function loadActivityHeatmap() {
    $.ajax({
        url: 'api/activity/heatmap.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const ctx = document.getElementById('activityHeatmap').getContext('2d');
                new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels: response.labels,
                        datasets: [{
                            label: 'Activity Count',
                            data: response.data,
                            backgroundColor: 'rgba(54, 162, 235, 0.2)',
                            borderColor: 'rgba(54, 162, 235, 1)',
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        scales: {
                            y: {
                                beginAtZero: true
                            }
                        }
                    }
                });
            }
        }
    });
}

function loadSessionChart() {
    $.ajax({
        url: 'api/activity/session-chart.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const ctx = document.getElementById('sessionChart').getContext('2d');
                new Chart(ctx, {
                    type: 'doughnut',
                    data: {
                        labels: response.labels,
                        datasets: [{
                            data: response.data,
                            backgroundColor: [
                                '#FF6384',
                                '#36A2EB',
                                '#FFCE56',
                                '#4BC0C0',
                                '#9966FF'
                            ]
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false
                    }
                });
            }
        }
    });
}

function initializeLocationMap() {
    // Simple mock map implementation
    const mapContainer = document.getElementById('locationMap');
    mapContainer.innerHTML = `
        <div class="d-flex align-items-center justify-content-center h-100">
            <div class="text-center">
                <i class="fas fa-map-marked-alt fa-3x text-muted mb-3"></i>
                <p class="text-muted">Location tracking map will be displayed here</p>
                <small class="text-muted">Integration with Google Maps or similar service required</small>
            </div>
        </div>
    `;
}

function toggleAutoRefresh() {
    if (isAutoRefreshEnabled) {
        clearInterval(autoRefreshInterval);
        isAutoRefreshEnabled = false;
        $('#refreshIcon').removeClass('fa-spin');
    } else {
        autoRefreshInterval = setInterval(function() {
            loadActivityStats();
            loadActivityTimeline();
            loadOnlineUsers();
            loadActiveSessions();
        }, 30000); // Refresh every 30 seconds
        
        isAutoRefreshEnabled = true;
        $('#refreshIcon').addClass('fa-spin');
    }
}

// Real-time updates using WebSocket (mock implementation)
function initializeWebSocket() {
    // This would connect to a WebSocket server for real-time updates
    // For now, we'll use polling
    setInterval(function() {
        if (isAutoRefreshEnabled) {
            loadActivityStats();
            loadOnlineUsers();
        }
    }, 10000); // Poll every 10 seconds
}
</script>

</body>
</html>
