<?php
// This file is now content-only and accessed through admin/index.php routing
require_once '../config.php';
require_once '../app/classes/UserLoginTracker.php';

use App\classes\UserLoginTracker;

// Initialize login tracker
$loginTracker = new UserLoginTracker($conn);

// Handle form submissions
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'clean_logs':
                $days = intval($_POST['days']);
                $result = $loginTracker->cleanOldLogs($days);
                if ($result['success']) {
                    $message = "Cleaned {$result['deleted_count']} old login logs (older than $days days)";
                    $message_type = 'success';
                } else {
                    $message = 'Failed to clean old logs';
                    $message_type = 'error';
                }
                break;
        }
    }
}

// Get filter parameters
$days = isset($_GET['days']) ? intval($_GET['days']) : 7;
$userId = isset($_GET['user_id']) ? intval($_GET['user_id']) : null;
$status = isset($_GET['status']) ? $_GET['status'] : null;

// Get recent logins with all filters
$recentLogins = $loginTracker->getRecentLogins(100, $userId, $status, $days);

// Get login statistics
$loginStats = $loginTracker->getLoginSummary($days);

// Get active sessions
$activeSessions = $loginTracker->getActiveSessions();

// Get top users by login frequency (filtered by days)
$topUsers = $loginTracker->getTopUsersByLogins(10, $days);

// Get all users for filter dropdown
$users_result = mysqli_query($conn, "SELECT id, username, role FROM agents ORDER BY username");
$users = [];
while ($row = mysqli_fetch_assoc($users_result)) {
    $users[] = $row;
}

?>

<!-- User Login Activity Content -->
<div class="space-y-6">
        <!-- Page Header -->
        <div class="bg-gradient-to-br from-slate-800 to-slate-700 rounded-2xl p-8 mb-8 border border-slate-600 shadow-2xl">
            <h1 class="text-4xl font-bold text-white mb-3 flex items-center">
                <i class="fas fa-user-clock mr-4 text-blue-400"></i>
                <span class="bg-gradient-to-r from-blue-400 to-purple-400 bg-clip-text text-transparent">
                    User Login Activity
                </span>
            </h1>
            <p class="text-slate-300 text-lg">Monitor user login activity, sessions, and security across your platform</p>
        </div>

        <!-- Success/Error Messages -->
        <?php if (!empty($message)): ?>
        <div class="mb-6 p-4 rounded-xl border flex items-center gap-3 <?= $message_type === 'success' ? 'bg-green-900/20 border-green-500/30 text-green-300' : 'bg-red-900/20 border-red-500/30 text-red-300' ?>">
            <i class="fas fa-<?= $message_type === 'success' ? 'check-circle' : 'exclamation-circle' ?> text-lg"></i>
            <span class="font-medium"><?= htmlspecialchars($message) ?></span>
        </div>
        <?php endif; ?>

        <!-- Active Filters Display -->
        <?php if ($userId || $status || $days != 7): ?>
        <div class="mb-6 p-4 bg-blue-900/20 border border-blue-500/30 rounded-xl">
            <h3 class="text-sm font-semibold text-blue-300 mb-2 flex items-center">
                <i class="fas fa-filter mr-2"></i>Active Filters
            </h3>
            <div class="flex flex-wrap gap-2">
                <?php if ($days != 7): ?>
                <span class="px-3 py-1 bg-blue-500/20 text-blue-300 rounded-full text-sm">
                    <i class="fas fa-calendar mr-1"></i>Last <?= $days ?> days
                </span>
                <?php endif; ?>
                <?php if ($userId): ?>
                <span class="px-3 py-1 bg-blue-500/20 text-blue-300 rounded-full text-sm">
                    <i class="fas fa-user mr-1"></i>User: <?= htmlspecialchars($users[array_search($userId, array_column($users, 'id'))]['username'] ?? 'Unknown') ?>
                </span>
                <?php endif; ?>
                <?php if ($status): ?>
                <span class="px-3 py-1 bg-blue-500/20 text-blue-300 rounded-full text-sm">
                    <i class="fas fa-<?= $status == 'success' ? 'check-circle' : 'times-circle' ?> mr-1"></i>Status: <?= ucfirst($status) ?>
                </span>
                <?php endif; ?>
                <a href="index.php?page=user_activity" class="px-3 py-1 bg-red-500/20 text-red-300 rounded-full text-sm hover:bg-red-500/30 transition-colors">
                    <i class="fas fa-times mr-1"></i>Clear All Filters
                </a>
            </div>
        </div>
        <?php endif; ?>

        <!-- Statistics Cards -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <div class="bg-gradient-to-br from-slate-800 to-slate-700 rounded-xl p-6 border border-slate-600 shadow-lg hover:shadow-xl transition-all duration-300 hover:-translate-y-1 relative overflow-hidden">
                <div class="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-blue-500 to-cyan-500"></div>
                <div class="flex items-center">
                    <div class="p-3 bg-blue-500/20 rounded-xl">
                        <i class="fas fa-sign-in-alt text-blue-400 text-xl"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-slate-400 text-sm font-semibold uppercase tracking-wide">Total Logins</p>
                        <p class="text-3xl font-bold text-white"><?= number_format($loginStats['total_logins']) ?></p>
                    </div>
                </div>
            </div>
            
            <div class="bg-gradient-to-br from-slate-800 to-slate-700 rounded-xl p-6 border border-slate-600 shadow-lg hover:shadow-xl transition-all duration-300 hover:-translate-y-1 relative overflow-hidden">
                <div class="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-green-500 to-emerald-500"></div>
                <div class="flex items-center">
                    <div class="p-3 bg-green-500/20 rounded-xl">
                        <i class="fas fa-check-circle text-green-400 text-xl"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-slate-400 text-sm font-semibold uppercase tracking-wide">Successful</p>
                        <p class="text-3xl font-bold text-white"><?= number_format($loginStats['successful_logins']) ?></p>
                    </div>
                </div>
            </div>
            
            <div class="bg-gradient-to-br from-slate-800 to-slate-700 rounded-xl p-6 border border-slate-600 shadow-lg hover:shadow-xl transition-all duration-300 hover:-translate-y-1 relative overflow-hidden">
                <div class="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-red-500 to-pink-500"></div>
                <div class="flex items-center">
                    <div class="p-3 bg-red-500/20 rounded-xl">
                        <i class="fas fa-times-circle text-red-400 text-xl"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-slate-400 text-sm font-semibold uppercase tracking-wide">Failed</p>
                        <p class="text-3xl font-bold text-white"><?= number_format($loginStats['failed_logins']) ?></p>
                    </div>
                </div>
            </div>
            
            <div class="bg-gradient-to-br from-slate-800 to-slate-700 rounded-xl p-6 border border-slate-600 shadow-lg hover:shadow-xl transition-all duration-300 hover:-translate-y-1 relative overflow-hidden">
                <div class="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-purple-500 to-violet-500"></div>
                <div class="flex items-center">
                    <div class="p-3 bg-purple-500/20 rounded-xl">
                        <i class="fas fa-users text-purple-400 text-xl"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-slate-400 text-sm font-semibold uppercase tracking-wide">Active Sessions</p>
                        <p class="text-3xl font-bold text-white"><?= count($activeSessions) ?></p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filters -->
        <div class="bg-gradient-to-br from-slate-800 to-slate-700 rounded-xl p-6 mb-8 border border-slate-600 shadow-lg">
            <h2 class="text-xl font-bold text-white mb-6 flex items-center">
                <i class="fas fa-filter mr-3 text-blue-400"></i>Filters & Search
            </h2>
            <form method="GET" action="index.php" class="grid grid-cols-1 md:grid-cols-4 gap-6">
                <input type="hidden" name="page" value="user_activity">
                <div>
                    <label for="days" class="block text-sm font-semibold text-slate-300 mb-2">Time Period</label>
                    <select id="days" name="days" class="w-full px-4 py-3 bg-slate-700 border border-slate-600 rounded-lg text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors">
                        <option value="1" <?= $days == 1 ? 'selected' : '' ?>>Last 24 hours</option>
                        <option value="7" <?= $days == 7 ? 'selected' : '' ?>>Last 7 days</option>
                        <option value="30" <?= $days == 30 ? 'selected' : '' ?>>Last 30 days</option>
                        <option value="90" <?= $days == 90 ? 'selected' : '' ?>>Last 90 days</option>
                    </select>
                </div>
                
                <div>
                    <label for="user_id" class="block text-sm font-semibold text-slate-300 mb-2">User</label>
                    <select id="user_id" name="user_id" class="w-full px-4 py-3 bg-slate-700 border border-slate-600 rounded-lg text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors">
                        <option value="">All Users</option>
                        <?php foreach ($users as $user): ?>
                        <option value="<?= $user['id'] ?>" <?= $userId == $user['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($user['username']) ?> (<?= ucfirst($user['role']) ?>)
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div>
                    <label for="status" class="block text-sm font-semibold text-slate-300 mb-2">Status</label>
                    <select id="status" name="status" class="w-full px-4 py-3 bg-slate-700 border border-slate-600 rounded-lg text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors">
                        <option value="">All Status</option>
                        <option value="success" <?= $status == 'success' ? 'selected' : '' ?>>Successful</option>
                        <option value="failed" <?= $status == 'failed' ? 'selected' : '' ?>>Failed</option>
                    </select>
                </div>
                
                <div class="flex items-end">
                    <button type="submit" class="w-full bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white font-semibold py-3 px-6 rounded-lg transition-all duration-200 hover:shadow-lg hover:-translate-y-0.5 flex items-center justify-center">
                        <i class="fas fa-search mr-2"></i>Apply Filters
                    </button>
                </div>
            </form>
        </div>

        <!-- Active Sessions -->
        <?php if (!empty($activeSessions)): ?>
        <div class="bg-gradient-to-br from-slate-800 to-slate-700 rounded-xl mb-8 border border-slate-600 shadow-lg overflow-hidden">
            <div class="px-6 py-4 border-b border-slate-600">
                <h2 class="text-xl font-bold text-white flex items-center">
                    <i class="fas fa-user-clock mr-3 text-green-400"></i>Active Sessions
                </h2>
            </div>
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead class="bg-slate-700">
                        <tr>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">User</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">Role</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">Login Time</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">Duration</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">IP Address</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-600">
                        <?php foreach ($activeSessions as $session): ?>
                        <tr class="hover:bg-slate-700/50 transition-colors">
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm font-semibold text-white"><?= htmlspecialchars($session['username']) ?></div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold bg-green-500/20 text-green-400 border border-green-500/30">
                                    <?= ucfirst($session['user_role']) ?>
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-300">
                                <?= isset($session['created_at']) && $session['created_at'] ? date('M j, Y g:i A', strtotime($session['created_at'])) : 'N/A' ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-300">
                                <?= isset($session['created_at']) && $session['created_at'] ? UserLoginTracker::formatSessionDuration(time() - strtotime($session['created_at'])) : 'N/A' ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-400">
                                <?= htmlspecialchars($session['ip_address']) ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>

        <!-- Recent Login Activity -->
        <div class="bg-gradient-to-br from-slate-800 to-slate-700 rounded-xl mb-8 border border-slate-600 shadow-lg overflow-hidden">
            <div class="px-6 py-4 border-b border-slate-600">
                <div class="flex items-center justify-between">
                    <h2 class="text-xl font-bold text-white flex items-center">
                        <i class="fas fa-history mr-3 text-blue-400"></i>Recent Login Activity
                    </h2>
                    <div class="text-sm text-slate-400">
                        Showing <?= count($recentLogins) ?> records
                    </div>
                </div>
            </div>
            <div class="overflow-x-auto">
                <?php if (empty($recentLogins)): ?>
                <div class="p-8 text-center text-slate-400">
                    <i class="fas fa-sign-in-alt text-5xl mb-4 text-slate-500"></i>
                    <p class="text-lg">No login activity found for the selected filters.</p>
                </div>
                <?php else: ?>
                <table class="w-full">
                    <thead class="bg-slate-700">
                        <tr>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">User</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">Role</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">Status</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">Login Time</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">Logout Time</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">Duration</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">IP Address</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-600">
                        <?php foreach ($recentLogins as $login): ?>
                        <tr class="hover:bg-slate-700/50 transition-colors">
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm font-semibold text-white"><?= htmlspecialchars($login['username']) ?></div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold bg-blue-500/20 text-blue-400 border border-blue-500/30">
                                    <?= ucfirst($login['user_role']) ?>
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold <?= $login['login_status'] == 'success' ? 'bg-green-500/20 text-green-400 border border-green-500/30' : 'bg-red-500/20 text-red-400 border border-red-500/30' ?>">
                                    <?= ucfirst($login['login_status']) ?>
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-300">
                                <?= isset($login['created_at']) && $login['created_at'] ? date('M j, Y g:i A', strtotime($login['created_at'])) : 'N/A' ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-300">
                                <?= isset($login['logout_time']) && $login['logout_time'] ? date('M j, Y g:i A', strtotime($login['logout_time'])) : 'Active' ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-300">
                                <?= UserLoginTracker::formatSessionDuration($login['session_duration']) ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-400">
                                <?= htmlspecialchars($login['ip_address']) ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php endif; ?>
            </div>
        </div>

        <!-- Top Users by Login Frequency -->
        <?php if (!empty($topUsers)): ?>
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 mb-8">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-semibold text-gray-900">
                    <i class="fas fa-trophy mr-2"></i>Top Users by Login Frequency (Last <?= $days ?> days)
                </h2>
            </div>
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">User</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Role</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Login Count</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Last Login</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Avg Session</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <?php foreach ($topUsers as $user): ?>
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm font-medium text-gray-900"><?= htmlspecialchars($user['username']) ?></div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                    <?= ucfirst($user['user_role']) ?>
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                <?= number_format($user['login_count']) ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                <?= isset($user['last_login']) && $user['last_login'] ? date('M j, Y g:i A', strtotime($user['last_login'])) : 'N/A' ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                <?= UserLoginTracker::formatSessionDuration($user['avg_session_duration']) ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>

        <!-- Maintenance Actions -->
        <div class="bg-white rounded-lg shadow-sm border border-gray-200">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-semibold text-gray-900">
                    <i class="fas fa-tools mr-2"></i>Maintenance Actions
                </h2>
            </div>
            <div class="p-6">
                <form method="POST" action="index.php?page=user_activity" onsubmit="return confirm('Are you sure you want to clean old login logs? This action cannot be undone.')">
                    <input type="hidden" name="action" value="clean_logs">
                    <div class="flex items-center space-x-4">
                        <div>
                            <label for="clean_days" class="block text-sm font-medium text-gray-700">Clean logs older than</label>
                            <select id="clean_days" name="days" class="mt-1 block px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-accent-500 focus:border-accent-500">
                                <option value="30">30 days</option>
                                <option value="60">60 days</option>
                                <option value="90">90 days</option>
                                <option value="180">180 days</option>
                            </select>
                        </div>
                        <div class="flex items-end">
                            <button type="submit" class="bg-red-600 text-white px-4 py-2 rounded-md hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500">
                                <i class="fas fa-trash mr-2"></i>Clean Old Logs
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
