<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<main class="main-content" id="mainContent">
    <header class="main-header">
        <div>
            <h1>ACTIVITY LOGS</h1>
            <p class="welcome-text">Monitor all user activities and system events in real-time</p>
        </div>
        <div class="header-actions">
            <button class="btn btn-primary" onclick="refreshActivity()">
                <i class="fas fa-sync-alt"></i> Refresh
            </button>
            <button class="btn btn-secondary" onclick="exportActivity()">
                <i class="fas fa-download"></i> Export
            </button>
        </div>
    </header>

    <!-- Activity Filters -->
    <div class="content-area">
        <div class="filters-section">
            <div class="filters-header">
                <h3>Filter Activities</h3>
                <button class="btn btn-sm" onclick="clearFilters()">Clear Filters</button>
            </div>
            <div class="filters-grid">
                <div class="filter-group">
                    <label class="filter-label">Activity Type</label>
                    <select class="filter-select" id="activityType" onchange="filterActivities()">
                        <option value="all">All Activities</option>
                        <option value="login">User Logins</option>
                        <option value="project">Project Activities</option>
                        <option value="system">System Events</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label class="filter-label">User</label>
                    <select class="filter-select" id="userFilter" onchange="filterActivities()">
                        <option value="all">All Users</option>
                        <?php foreach ($users as $user): ?>
                            <option value="<?php echo $user->id; ?>"><?php echo htmlspecialchars($user->full_name); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <label class="filter-label">Date Range</label>
                    <select class="filter-select" id="dateRange" onchange="filterActivities()">
                        <option value="today">Today</option>
                        <option value="yesterday">Yesterday</option>
                        <option value="week">Last 7 Days</option>
                        <option value="month">Last 30 Days</option>
                        <option value="all">All Time</option>
                    </select>
                </div>
            </div>
        </div>

        <!-- Activity Stats -->
        <div class="metrics-cards">
            <div class="card stat-card">
                <div class="card-icon">
                    <i class="fas fa-sign-in-alt"></i>
                </div>
                <div class="card-content">
                    <p class="card-label">TOTAL LOGINS</p>
                    <div class="card-data">
                        <span class="value" id="totalLogins"><?php echo $activity_stats['total_logins']; ?></span>
                        <span class="change positive">+0%</span>
                    </div>
                </div>
            </div>

            <div class="card stat-card">
                <div class="card-icon">
                    <i class="fas fa-user-clock"></i>
                </div>
                <div class="card-content">
                    <p class="card-label">ACTIVE USERS</p>
                    <div class="card-data">
                        <span class="value" id="activeUsers"><?php echo $activity_stats['active_users']; ?></span>
                        <span class="change positive">+0%</span>
                    </div>
                </div>
            </div>

            <div class="card stat-card">
                <div class="card-icon">
                    <i class="fas fa-project-diagram"></i>
                </div>
                <div class="card-content">
                    <p class="card-label">PROJECT ACTIVITIES</p>
                    <div class="card-data">
                        <span class="value" id="projectActivities"><?php echo $activity_stats['project_activities']; ?></span>
                        <span class="change positive">+0%</span>
                    </div>
                </div>
            </div>

            <div class="card stat-card">
                <div class="card-icon">
                    <i class="fas fa-exclamation-triangle"></i>
                </div>
                <div class="card-content">
                    <p class="card-label">SYSTEM EVENTS</p>
                    <div class="card-data">
                        <span class="value" id="systemEvents"><?php echo $activity_stats['system_events']; ?></span>
                        <span class="change negative">+0%</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Activity Timeline -->
        <div class="chart-card">
            <div class="chart-header">
                <h3>Activity Timeline</h3>
                <div class="chart-legend">
                    <span class="legend-item"><span class="legend-color" style="background:#4caf50"></span>Logins</span>
                    <span class="legend-item"><span class="legend-color" style="background:#2196f3"></span>Projects</span>
                    <span class="legend-item"><span class="legend-color" style="background:#ff9800"></span>System</span>
                </div>
            </div>
            <div class="chart-container">
                <canvas id="activityTimelineChart"></canvas>
            </div>
        </div>

        <!-- Activity List -->
        <div class="chart-card">
            <div class="chart-header">
                <h3>Recent Activities</h3>
                <span class="results-count" id="activityCount"><?php echo count($activities); ?> activities</span>
            </div>
            <div class="activity-list" id="activityList">
                <?php foreach ($activities as $activity): ?>
                <div class="activity-item" data-type="<?php echo $activity['type']; ?>" data-user="<?php echo $activity['user_id']; ?>">
                    <div class="activity-icon" style="background: <?php echo $activity['color']; ?>;">
                        <i class="<?php echo $activity['icon']; ?>"></i>
                    </div>
                    <div class="activity-content">
                        <div class="activity-title"><?php echo $activity['title']; ?></div>
                        <div class="activity-description"><?php echo $activity['description']; ?></div>
                        <div class="activity-meta">
                            <span class="user-badge"><?php echo $activity['user_name']; ?> (<?php echo $activity['user_role']; ?>)</span>
                            <span class="activity-time"><?php echo date('M j, Y g:i A', strtotime($activity['timestamp'])); ?></span>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</main>

<style>
.activity-item {
    display: flex;
    align-items: flex-start;
    gap: 16px;
    padding: 20px;
    border-bottom: 1px solid var(--border-color);
    transition: background-color 0.3s ease;
}

.activity-item:hover {
    background-color: var(--hover-color);
}

.activity-item:last-child {
    border-bottom: none;
}

.activity-icon {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 18px;
    flex-shrink: 0;
}

.activity-content {
    flex: 1;
}

.activity-title {
    font-size: 16px;
    font-weight: 600;
    color: var(--text-color);
    margin-bottom: 4px;
}

.activity-description {
    font-size: 14px;
    color: var(--light-text);
    margin-bottom: 8px;
}

.activity-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 12px;
}

.user-badge {
    background: var(--border-color);
    padding: 4px 8px;
    border-radius: 12px;
    color: var(--text-color);
    font-weight: 600;
}

.activity-time {
    color: var(--light-text);
}

.legend-item {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
}

.legend-color {
    width: 12px;
    height: 12px;
    border-radius: 50%;
}

.loading-activity {
    text-align: center;
    padding: 40px;
    color: var(--light-text);
}

.loading-activity i {
    font-size: 24px;
    margin-bottom: 10px;
}
</style>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
let activityChart;
let currentFilters = {
    type: 'all',
    user: 'all',
    date_range: 'today'
};

document.addEventListener('DOMContentLoaded', function() {
    initializeActivityChart();
    loadActivityData();
});

function initializeActivityChart() {
    const ctx = document.getElementById('activityTimelineChart').getContext('2d');
    activityChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [
                {
                    label: 'Logins',
                    data: [],
                    borderColor: '#4caf50',
                    backgroundColor: 'rgba(76, 175, 80, 0.1)',
                    tension: 0.4,
                    fill: true
                },
                {
                    label: 'Projects',
                    data: [],
                    borderColor: '#2196f3',
                    backgroundColor: 'rgba(33, 150, 243, 0.1)',
                    tension: 0.4,
                    fill: true
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                intersect: false,
                mode: 'index'
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(0, 0, 0, 0.1)'
                    }
                },
                x: {
                    grid: {
                        display: false
                    }
                }
            }
        }
    });
}

async function loadActivityData() {
    try {
        showLoading();
        
        const params = new URLSearchParams(currentFilters);
        const response = await fetch(`<?php echo base_url('admin/get_activity_data_ajax'); ?>?${params}`);
        const data = await response.json();
        
        if (data.success) {
            updateActivityStats(data.stats);
            updateActivityList(data.activities);
            updateActivityChart(data.activities);
        }
    } catch (error) {
        console.error('Error loading activity data:', error);
        showError('Failed to load activity data');
    }
}

function updateActivityStats(stats) {
    document.getElementById('totalLogins').textContent = stats.total_logins || 0;
    document.getElementById('activeUsers').textContent = stats.active_users || 0;
    document.getElementById('projectActivities').textContent = stats.project_activities || 0;
    document.getElementById('systemEvents').textContent = stats.system_events || 0;
}

function updateActivityList(activities) {
    const activityList = document.getElementById('activityList');
    const activityCount = document.getElementById('activityCount');
    
    activityCount.textContent = `${activities.length} activities`;
    
    if (activities.length === 0) {
        activityList.innerHTML = `
            <div class="loading-activity">
                <i class="fas fa-inbox"></i>
                <p>No activities found for the selected filters</p>
            </div>
        `;
        return;
    }
    
    activityList.innerHTML = activities.map(activity => `
        <div class="activity-item" data-type="${activity.type}" data-user="${activity.user_id}">
            <div class="activity-icon" style="background: ${activity.color};">
                <i class="${activity.icon}"></i>
            </div>
            <div class="activity-content">
                <div class="activity-title">${activity.title}</div>
                <div class="activity-description">${activity.description}</div>
                <div class="activity-meta">
                    <span class="user-badge">${activity.user_name} (${activity.user_role})</span>
                    <span class="activity-time">${new Date(activity.timestamp).toLocaleString()}</span>
                </div>
            </div>
        </div>
    `).join('');
}

function updateActivityChart(activities) {
    // Group activities by date and type
    const dailyData = {};
    const types = ['login', 'project'];
    
    activities.forEach(activity => {
        const date = new Date(activity.timestamp).toLocaleDateString();
        if (!dailyData[date]) {
            dailyData[date] = { login: 0, project: 0 };
        }
        if (types.includes(activity.type)) {
            dailyData[date][activity.type]++;
        }
    });
    
    const labels = Object.keys(dailyData).slice(-10); // Last 10 days
    const loginData = labels.map(date => dailyData[date]?.login || 0);
    const projectData = labels.map(date => dailyData[date]?.project || 0);
    
    activityChart.data.labels = labels;
    activityChart.data.datasets[0].data = loginData;
    activityChart.data.datasets[1].data = projectData;
    activityChart.update();
}

function filterActivities() {
    currentFilters.type = document.getElementById('activityType').value;
    currentFilters.user = document.getElementById('userFilter').value;
    currentFilters.date_range = document.getElementById('dateRange').value;
    
    loadActivityData();
}

function clearFilters() {
    document.getElementById('activityType').value = 'all';
    document.getElementById('userFilter').value = 'all';
    document.getElementById('dateRange').value = 'today';
    
    filterActivities();
}

function refreshActivity() {
    loadActivityData();
}

function exportActivity() {
    // Implement export functionality
    alert('Export functionality will be implemented');
}

function showLoading() {
    const activityList = document.getElementById('activityList');
    activityList.innerHTML = `
        <div class="loading-activity">
            <i class="fas fa-spinner fa-spin"></i>
            <p>Loading activities...</p>
        </div>
    `;
}

function showError(message) {
    const activityList = document.getElementById('activityList');
    activityList.innerHTML = `
        <div class="loading-activity">
            <i class="fas fa-exclamation-triangle"></i>
            <p>${message}</p>
        </div>
    `;
}

// Auto-refresh every 30 seconds
setInterval(loadActivityData, 30000);
</script>