<?php
require_once 'auth_rbac.php';
require_once '../db_config.php';

requirePermission('activity_log', 'view');

$currentPage = 'activity_log';
$pageTitle = 'Unified Activity Log';

// Pagination
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$limit = 50;
$offset = ($page - 1) * $limit;

// Filters
$userFilter = $_GET['user'] ?? '';
$activityFilter = $_GET['activity'] ?? '';
$severityFilter = $_GET['severity'] ?? '';
$sourceFilter = $_GET['source'] ?? '';
$dateFrom = $_GET['date_from'] ?? '';
$dateTo = $_GET['date_to'] ?? '';
$search = $_GET['search'] ?? '';

try {
    $pdo = getDBConnection();
    
    // Build the unified query
    $whereConditions = [];
    $params = [];
    $query = '';
    
    // Add filters
    if ($userFilter) {
        $whereConditions[] = "CAST(user_name AS CHAR) LIKE ?";
        $params[] = "%$userFilter%";
    }
    
    if ($activityFilter) {
        $whereConditions[] = "CAST(activity_type AS CHAR) LIKE ?";
        $params[] = "%$activityFilter%";
    }
    
    if ($severityFilter) {
        $whereConditions[] = "CAST(severity AS CHAR) = ?";
        $params[] = $severityFilter;
    }
    
    if ($sourceFilter) {
        $whereConditions[] = "CAST(log_source AS CHAR) = ?";
        $params[] = $sourceFilter;
    }
    
    if ($dateFrom) {
        $whereConditions[] = "DATE(created_at) >= ?";
        $params[] = $dateFrom;
    }
    
    if ($dateTo) {
        $whereConditions[] = "DATE(created_at) <= ?";
        $params[] = $dateTo;
    }
    
    if ($search) {
        $whereConditions[] = "(CAST(action_description AS CHAR) LIKE ? OR CAST(registration_number AS CHAR) LIKE ? OR CAST(target_type AS CHAR) LIKE ?)";
        $searchParam = "%$search%";
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
    }
    
    $whereClause = $whereConditions ? 'WHERE ' . implode(' AND ', $whereConditions) : '';
    
    // Get total count for pagination
    $countQuery = "
        SELECT COUNT(*) as total FROM (
            SELECT 
                CAST('admin' AS CHAR(20)) COLLATE utf8mb4_general_ci as log_source,
                id,
                admin_user_id as user_id,
                CAST(NULL AS CHAR(255)) COLLATE utf8mb4_general_ci as user_name,
                CAST(action AS CHAR(100)) COLLATE utf8mb4_general_ci as activity_type,
                NULL as registration_id,
                CAST(NULL AS CHAR(50)) COLLATE utf8mb4_general_ci as registration_number,
                NULL as product_id,
                NULL as delegate_id,
                CAST(target_type AS CHAR(50)) COLLATE utf8mb4_general_ci as target_type,
                target_id,
                CAST(details AS CHAR(1000)) COLLATE utf8mb4_general_ci as action_description,
                CAST(NULL AS CHAR(5000)) COLLATE utf8mb4_general_ci as old_values,
                CAST(NULL AS CHAR(5000)) COLLATE utf8mb4_general_ci as new_values,
                CAST('medium' AS CHAR(20)) COLLATE utf8mb4_general_ci as severity,
                CAST(NULL AS CHAR(500)) COLLATE utf8mb4_general_ci as tags,
                CAST(ip_address AS CHAR(45)) COLLATE utf8mb4_general_ci as ip_address,
                CAST(user_agent AS CHAR(500)) COLLATE utf8mb4_general_ci as user_agent,
                created_at
            FROM admin_activity_log
            
            UNION ALL
            
            SELECT 
                CAST('product' AS CHAR(20)) COLLATE utf8mb4_general_ci as log_source,
                id,
                user_id,
                CAST(user_name AS CHAR(255)) COLLATE utf8mb4_general_ci as user_name,
                CAST(activity_type AS CHAR(100)) COLLATE utf8mb4_general_ci as activity_type,
                registration_id,
                CAST(NULL AS CHAR(50)) COLLATE utf8mb4_general_ci as registration_number,
                product_id,
                NULL as delegate_id,
                CAST(NULL AS CHAR(50)) COLLATE utf8mb4_general_ci as target_type,
                NULL as target_id,
                CAST(action_description AS CHAR(1000)) COLLATE utf8mb4_general_ci as action_description,
                CAST(old_values AS CHAR(5000)) COLLATE utf8mb4_general_ci as old_values,
                CAST(new_values AS CHAR(5000)) COLLATE utf8mb4_general_ci as new_values,
                CAST(severity AS CHAR(20)) COLLATE utf8mb4_general_ci as severity,
                CAST(tags AS CHAR(500)) COLLATE utf8mb4_general_ci as tags,
                CAST(ip_address AS CHAR(45)) COLLATE utf8mb4_general_ci as ip_address,
                CAST(user_agent AS CHAR(500)) COLLATE utf8mb4_general_ci as user_agent,
                created_at
            FROM product_activity_log
            
            UNION ALL
            
            SELECT 
                CAST('registration' AS CHAR(20)) COLLATE utf8mb4_general_ci as log_source,
                ral.id,
                ral.user_id,
                CAST(ral.user_name AS CHAR(255)) COLLATE utf8mb4_general_ci as user_name,
                CAST(ral.activity_type AS CHAR(100)) COLLATE utf8mb4_general_ci as activity_type,
                ral.registration_id,
                CAST(r.registration_number AS CHAR(50)) COLLATE utf8mb4_general_ci as registration_number,
                NULL as product_id,
                ral.delegate_id,
                CAST(NULL AS CHAR(50)) COLLATE utf8mb4_general_ci as target_type,
                NULL as target_id,
                CAST(ral.action_description AS CHAR(1000)) COLLATE utf8mb4_general_ci as action_description,
                CAST(ral.old_values AS CHAR(5000)) COLLATE utf8mb4_general_ci as old_values,
                CAST(ral.new_values AS CHAR(5000)) COLLATE utf8mb4_general_ci as new_values,
                CAST(ral.severity AS CHAR(20)) COLLATE utf8mb4_general_ci as severity,
                CAST(ral.tags AS CHAR(500)) COLLATE utf8mb4_general_ci as tags,
                CAST(ral.ip_address AS CHAR(45)) COLLATE utf8mb4_general_ci as ip_address,
                CAST(ral.user_agent AS CHAR(500)) COLLATE utf8mb4_general_ci as user_agent,
                ral.created_at
            FROM registration_activity_log ral
            LEFT JOIN registrations r ON ral.registration_id = r.id
        ) unified_log
        $whereClause
    ";
    
    // Remove debug logging temporarily
    $countStmt = $pdo->prepare($countQuery);
    
    // Only execute with params if we have any
    if (empty($params)) {
        $countStmt->execute();
    } else {
        $countStmt->execute($params);
    }
    
    $totalRecords = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];
    $totalPages = ceil($totalRecords / $limit);
    
    // Get activity log entries with pagination
    $query = "
        SELECT * FROM (
            SELECT 
                CAST('admin' AS CHAR(20)) COLLATE utf8mb4_general_ci as log_source,
                id,
                admin_user_id as user_id,
                CAST(NULL AS CHAR(255)) COLLATE utf8mb4_general_ci as user_name,
                CAST(action AS CHAR(100)) COLLATE utf8mb4_general_ci as activity_type,
                NULL as registration_id,
                CAST(NULL AS CHAR(50)) COLLATE utf8mb4_general_ci as registration_number,
                NULL as product_id,
                NULL as delegate_id,
                CAST(target_type AS CHAR(50)) COLLATE utf8mb4_general_ci as target_type,
                target_id,
                CAST(details AS CHAR(1000)) COLLATE utf8mb4_general_ci as action_description,
                CAST(NULL AS CHAR(5000)) COLLATE utf8mb4_general_ci as old_values,
                CAST(NULL AS CHAR(5000)) COLLATE utf8mb4_general_ci as new_values,
                CAST('medium' AS CHAR(20)) COLLATE utf8mb4_general_ci as severity,
                CAST(NULL AS CHAR(500)) COLLATE utf8mb4_general_ci as tags,
                CAST(ip_address AS CHAR(45)) COLLATE utf8mb4_general_ci as ip_address,
                CAST(user_agent AS CHAR(500)) COLLATE utf8mb4_general_ci as user_agent,
                created_at
            FROM admin_activity_log
            
            UNION ALL
            
            SELECT 
                CAST('product' AS CHAR(20)) COLLATE utf8mb4_general_ci as log_source,
                id,
                user_id,
                CAST(user_name AS CHAR(255)) COLLATE utf8mb4_general_ci as user_name,
                CAST(activity_type AS CHAR(100)) COLLATE utf8mb4_general_ci as activity_type,
                registration_id,
                CAST(NULL AS CHAR(50)) COLLATE utf8mb4_general_ci as registration_number,
                product_id,
                NULL as delegate_id,
                CAST(NULL AS CHAR(50)) COLLATE utf8mb4_general_ci as target_type,
                NULL as target_id,
                CAST(action_description AS CHAR(1000)) COLLATE utf8mb4_general_ci as action_description,
                CAST(old_values AS CHAR(5000)) COLLATE utf8mb4_general_ci as old_values,
                CAST(new_values AS CHAR(5000)) COLLATE utf8mb4_general_ci as new_values,
                CAST(severity AS CHAR(20)) COLLATE utf8mb4_general_ci as severity,
                CAST(tags AS CHAR(500)) COLLATE utf8mb4_general_ci as tags,
                CAST(ip_address AS CHAR(45)) COLLATE utf8mb4_general_ci as ip_address,
                CAST(user_agent AS CHAR(500)) COLLATE utf8mb4_general_ci as user_agent,
                created_at
            FROM product_activity_log
            
            UNION ALL
            
            SELECT 
                CAST('registration' AS CHAR(20)) COLLATE utf8mb4_general_ci as log_source,
                ral.id,
                ral.user_id,
                CAST(ral.user_name AS CHAR(255)) COLLATE utf8mb4_general_ci as user_name,
                CAST(ral.activity_type AS CHAR(100)) COLLATE utf8mb4_general_ci as activity_type,
                ral.registration_id,
                CAST(r.registration_number AS CHAR(50)) COLLATE utf8mb4_general_ci as registration_number,
                NULL as product_id,
                ral.delegate_id,
                CAST(NULL AS CHAR(50)) COLLATE utf8mb4_general_ci as target_type,
                NULL as target_id,
                CAST(ral.action_description AS CHAR(1000)) COLLATE utf8mb4_general_ci as action_description,
                CAST(ral.old_values AS CHAR(5000)) COLLATE utf8mb4_general_ci as old_values,
                CAST(ral.new_values AS CHAR(5000)) COLLATE utf8mb4_general_ci as new_values,
                CAST(ral.severity AS CHAR(20)) COLLATE utf8mb4_general_ci as severity,
                CAST(ral.tags AS CHAR(500)) COLLATE utf8mb4_general_ci as tags,
                CAST(ral.ip_address AS CHAR(45)) COLLATE utf8mb4_general_ci as ip_address,
                CAST(ral.user_agent AS CHAR(500)) COLLATE utf8mb4_general_ci as user_agent,
                ral.created_at
            FROM registration_activity_log ral
            LEFT JOIN registrations r ON ral.registration_id = r.id
        ) unified_log
        $whereClause
        ORDER BY created_at DESC
        LIMIT $limit OFFSET $offset
    ";
    
    $stmt = $pdo->prepare($query);
    
    // Only execute with params if we have any
    if (empty($params)) {
        $stmt->execute();
    } else {
        $stmt->execute($params);
    }
    
    $activities = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get user names for admin logs (where user_name is NULL)
    $userIds = [];
    if (!empty($activities)) {
        $userIds = array_unique(array_filter(array_column($activities, 'user_id')));
    }
    
    // Remove any null or 0 values and reindex the array
    $userIds = array_values(array_filter($userIds, function($id) { return $id !== null && $id !== 0 && is_numeric($id); }));
    
    $userNames = [];
    if (!empty($userIds) && count($userIds) > 0) {
        $placeholders = implode(',', array_fill(0, count($userIds), '?'));
        
        try {
            $userStmt = $pdo->prepare("SELECT id, username, full_name FROM admin_users WHERE id IN ($placeholders)");
            $userStmt->execute($userIds);
            foreach ($userStmt->fetchAll(PDO::FETCH_ASSOC) as $user) {
                $userNames[$user['id']] = [
                    'username' => $user['username'],
                    'full_name' => $user['full_name']
                ];
            }
        } catch (Exception $e) {
            error_log("Error fetching user names: " . $e->getMessage());
        }
    }
    
    // Get unique activity types for filter dropdown
    $activityTypesQuery = "
        SELECT DISTINCT activity_type FROM (
            SELECT DISTINCT CAST(action AS CHAR(100)) COLLATE utf8mb4_general_ci as activity_type FROM admin_activity_log
            UNION
            SELECT DISTINCT CAST(activity_type AS CHAR(100)) COLLATE utf8mb4_general_ci FROM product_activity_log
            UNION
            SELECT DISTINCT CAST(activity_type AS CHAR(100)) COLLATE utf8mb4_general_ci FROM registration_activity_log
        ) all_activities
        ORDER BY activity_type
    ";
    $activityTypes = $pdo->query($activityTypesQuery)->fetchAll(PDO::FETCH_COLUMN);
    
} catch (Exception $e) {
    $activities = [];
    $totalRecords = 0;
    $totalPages = 0;
    $activityTypes = [];
    $error = "Error fetching activity log: " . $e->getMessage();
    error_log("Unified Activity Log Error: " . $e->getMessage());
    error_log("Error type: " . get_class($e));
    error_log("SQL Query that failed: " . (isset($countQuery) ? substr($countQuery, 0, 200) : 'no count query'));
    error_log("Params array: " . print_r($params, true));
    error_log("Stack trace: " . $e->getTraceAsString());
}

// Helper function to get badge class for severity
function getSeverityClass($severity) {
    switch($severity) {
        case 'low': return 'badge-success';
        case 'medium': return 'badge-info';
        case 'high': return 'badge-warning';
        case 'critical': return 'badge-danger';
        default: return 'badge-secondary';
    }
}

// Helper function to get badge class for log source
function getSourceClass($source) {
    switch($source) {
        case 'admin': return 'badge-purple';
        case 'product': return 'badge-blue';
        case 'registration': return 'badge-green';
        default: return 'badge-secondary';
    }
}

// Helper function to format activity type for display
function formatActivityType($type) {
    return ucwords(str_replace('_', ' ', $type));
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - XChange 2025 Admin</title>
    <?php include '../includes/favicon.php'; ?>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../styles.css">
    <link rel="stylesheet" href="admin.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        /* Page-specific styles for unified activity log */
        .stats-bar {
            display: flex;
            gap: 1rem;
            align-items: center;
            font-size: 0.9rem;
            color: #666;
        }

        .card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
            margin-bottom: 2rem;
        }

        .card-header {
            background: #f8f9fa;
            padding: 1rem 1.5rem;
            border-bottom: 1px solid #dee2e6;
            display: flex;
            justify-content: space-between;
            align-items: center;
            cursor: pointer;
            user-select: none;
            transition: background-color 0.2s ease;
        }

        .card-header:hover {
            background: #f1f3f5;
        }

        .card-header.collapsed ~ .card-body {
            display: none;
        }

        .card-title {
            margin: 0;
            color: #2c3e50;
            font-size: 1.25rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .card-toggle {
            color: #667eea;
            font-size: 0.9rem;
            font-weight: 500;
            transition: transform 0.3s ease;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .card-toggle i {
            transition: transform 0.3s ease;
        }

        .card-header.collapsed .card-toggle i {
            transform: rotate(180deg);
        }

        .card-body {
            padding: 1.5rem;
        }

        .filter-bar {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
            gap: 1.5rem;
            align-items: end;
        }

        .form-group {
            margin-bottom: 0;
        }

        .form-label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
            color: #2c3e50;
            font-size: 0.85rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .form-control {
            width: 100%;
            padding: 0.85rem;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            font-size: 0.95rem;
            transition: all 0.2s ease;
            background: white;
        }

        .form-control:hover {
            border-color: #cbd5e0;
        }

        .form-control:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .filter-actions {
            display: flex;
            gap: 0.75rem;
            grid-column: span 2;
        }
        
        .filter-actions .btn {
            flex: 1;
            min-width: 120px;
            justify-content: center;
        }

        .btn {
            padding: 0.75rem 1.5rem;
            border: none;
            border-radius: 5px;
            text-decoration: none;
            font-weight: 500;
            transition: all 0.3s ease;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.95rem;
        }

        .btn-primary {
            background: #3498db;
            color: white;
        }

        .btn-primary:hover {
            background: #2980b9;
        }

        .btn-secondary {
            background: #95a5a6;
            color: white;
        }

        .btn-secondary:hover {
            background: #7f8c8d;
        }

        .table-container {
            overflow-x: auto;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 1rem;
        }

        .table th,
        .table td {
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid #dee2e6;
            font-size: 0.9rem;
        }

        .table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #2c3e50;
            white-space: nowrap;
        }

        .table tbody tr:hover {
            background-color: #f8f9ff;
        }

        .badge {
            padding: 0.25rem 0.75rem;
            border-radius: 15px;
            font-size: 0.75rem;
            font-weight: 500;
            text-transform: uppercase;
            display: inline-block;
        }

        .badge-info {
            background: #d1ecf1;
            color: #0c5460;
        }

        .badge-success {
            background: #d4edda;
            color: #155724;
        }

        .badge-warning {
            background: #fff3cd;
            color: #856404;
        }

        .badge-danger {
            background: #f8d7da;
            color: #721c24;
        }

        .badge-secondary {
            background: #e2e3e5;
            color: #383d41;
        }

        .badge-purple {
            background: #e7d5f7;
            color: #6c2c91;
        }

        .badge-blue {
            background: #cfe2ff;
            color: #084298;
        }

        .badge-green {
            background: #d1e7dd;
            color: #0f5132;
        }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 0.5rem;
            margin-top: 2rem;
            flex-wrap: wrap;
        }

        .pagination a,
        .pagination span {
            padding: 0.5rem 1rem;
            text-decoration: none;
            border: 1px solid #ddd;
            border-radius: 5px;
            color: #333;
            font-size: 0.9rem;
        }

        .pagination a:hover {
            background: #f8f9fa;
        }

        .pagination .current {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        .activity-details {
            font-size: 0.85rem;
            color: #666;
            margin-top: 0.25rem;
        }

        .ip-address {
            font-family: monospace;
            background: #f8f9fa;
            padding: 0.25rem 0.5rem;
            border-radius: 3px;
            font-size: 0.75rem;
        }

        .alert {
            padding: 1rem;
            border-radius: 5px;
            margin-bottom: 1rem;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .no-data {
            text-align: center;
            color: #999;
            padding: 3rem;
            font-size: 1.1rem;
        }

        .activity-description {
            max-width: 400px;
        }

        @media (max-width: 768px) {
            .filter-bar {
                grid-template-columns: 1fr;
            }
            
            .table {
                font-size: 0.8rem;
            }
            
            .table th,
            .table td {
                padding: 0.5rem;
            }

            .activity-description {
                max-width: 200px;
            }
        }
    </style>
</head>
<body>
    <?php include 'includes/admin_nav.php'; ?>

    <div class="admin-content">
        <div class="page-header">
            <h1 class="page-title">
                <i class="fas fa-history"></i> Unified Activity Log
            </h1>
            <div class="stats-bar">
                <span><strong><?php echo number_format($totalRecords); ?></strong> total activities</span>
            </div>
        </div>

        <?php if (isset($error)): ?>
        <div class="alert alert-error">
            <i class="fas fa-exclamation-triangle"></i> <?php echo htmlspecialchars($error); ?>
        </div>
        <?php endif; ?>

        <div class="card">
            <div class="card-header" onclick="this.classList.toggle('collapsed')">
                <h3 class="card-title"><i class="fas fa-filter"></i> Filter Activities</h3>
                <span class="card-toggle">
                    <i class="fas fa-chevron-down"></i>
                </span>
            </div>
            <div class="card-body">
                <form method="GET">
                    <div class="filter-bar">
                        <div class="form-group">
                            <label class="form-label">Search</label>
                            <input type="text" name="search" class="form-control" 
                                   value="<?php echo htmlspecialchars($search); ?>" 
                                   placeholder="Reg #, description...">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">User</label>
                            <input type="text" name="user" class="form-control" 
                                   value="<?php echo htmlspecialchars($userFilter); ?>" 
                                   placeholder="Username">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Activity Type</label>
                            <select name="activity" class="form-control">
                                <option value="">All Activities</option>
                                <?php foreach ($activityTypes as $type): ?>
                                <option value="<?php echo htmlspecialchars($type); ?>" 
                                        <?php echo $activityFilter === $type ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars(formatActivityType($type)); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Source</label>
                            <select name="source" class="form-control">
                                <option value="">All Sources</option>
                                <option value="admin" <?php echo $sourceFilter === 'admin' ? 'selected' : ''; ?>>Admin</option>
                                <option value="product" <?php echo $sourceFilter === 'product' ? 'selected' : ''; ?>>Product</option>
                                <option value="registration" <?php echo $sourceFilter === 'registration' ? 'selected' : ''; ?>>Registration</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Severity</label>
                            <select name="severity" class="form-control">
                                <option value="">All Levels</option>
                                <option value="low" <?php echo $severityFilter === 'low' ? 'selected' : ''; ?>>Low</option>
                                <option value="medium" <?php echo $severityFilter === 'medium' ? 'selected' : ''; ?>>Medium</option>
                                <option value="high" <?php echo $severityFilter === 'high' ? 'selected' : ''; ?>>High</option>
                                <option value="critical" <?php echo $severityFilter === 'critical' ? 'selected' : ''; ?>>Critical</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Date From</label>
                            <input type="date" name="date_from" class="form-control" 
                                   value="<?php echo htmlspecialchars($dateFrom); ?>">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Date To</label>
                            <input type="date" name="date_to" class="form-control" 
                                   value="<?php echo htmlspecialchars($dateTo); ?>">
                        </div>
                        
                        <div class="filter-actions">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-search"></i> Filter
                            </button>
                            <a href="unified_activity_log.php" class="btn btn-secondary">
                                <i class="fas fa-times"></i> Clear
                            </a>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    Activity Timeline
                </h3>
            </div>
            <div class="card-body">
                <div class="table-container">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Date/Time</th>
                                <th>Source</th>
                                <th>User</th>
                                <th>Activity</th>
                                <th>Description</th>
                                <th>Target</th>
                                <th>Severity</th>
                                <th>IP Address</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($activities)): ?>
                            <tr>
                                <td colspan="8" class="no-data">
                                    <i class="fas fa-inbox"></i><br>
                                    No activity records found.
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($activities as $activity): ?>
                            <tr>
                                <td>
                                    <strong><?php echo date('M j, Y', strtotime($activity['created_at'])); ?></strong><br>
                                    <small><?php echo date('g:i A', strtotime($activity['created_at'])); ?></small>
                                </td>
                                <td>
                                    <span class="badge <?php echo getSourceClass($activity['log_source']); ?>">
                                        <?php echo htmlspecialchars($activity['log_source']); ?>
                                    </span>
                                </td>
                                <td>
                                    <?php 
                                    $userName = $activity['user_name'];
                                    $fullName = '';
                                    if (!$userName && isset($userNames[$activity['user_id']])) {
                                        $userName = $userNames[$activity['user_id']]['username'];
                                        $fullName = $userNames[$activity['user_id']]['full_name'];
                                    }
                                    ?>
                                    <strong><?php echo htmlspecialchars($userName ?: 'System'); ?></strong>
                                    <?php if ($fullName): ?>
                                    <br><small><?php echo htmlspecialchars($fullName); ?></small>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge badge-info">
                                        <?php echo htmlspecialchars(formatActivityType($activity['activity_type'])); ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="activity-description">
                                        <?php echo htmlspecialchars($activity['action_description']); ?>
                                    </div>
                                </td>
                                <td>
                                    <?php if ($activity['registration_number']): ?>
                                        <small>Reg: <?php echo htmlspecialchars($activity['registration_number']); ?></small>
                                    <?php elseif ($activity['product_id']): ?>
                                        <small>Product ID: <?php echo $activity['product_id']; ?></small>
                                    <?php elseif ($activity['target_type']): ?>
                                        <small><?php echo htmlspecialchars($activity['target_type']); ?>
                                        <?php if ($activity['target_id']): ?>
                                            #<?php echo $activity['target_id']; ?>
                                        <?php endif; ?>
                                        </small>
                                    <?php else: ?>
                                        <span style="color: #999;">—</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge <?php echo getSeverityClass($activity['severity']); ?>">
                                        <?php echo htmlspecialchars($activity['severity']); ?>
                                    </span>
                                </td>
                                <td>
                                    <?php if ($activity['ip_address']): ?>
                                        <span class="ip-address"><?php echo htmlspecialchars($activity['ip_address']); ?></span>
                                    <?php else: ?>
                                        <span style="color: #999;">—</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($totalPages > 1): ?>
                <div class="pagination">
                    <?php
                    // Build query string for pagination
                    $queryParams = [
                        'user' => $userFilter,
                        'activity' => $activityFilter,
                        'severity' => $severityFilter,
                        'source' => $sourceFilter,
                        'date_from' => $dateFrom,
                        'date_to' => $dateTo,
                        'search' => $search
                    ];
                    $queryString = http_build_query(array_filter($queryParams));
                    $queryString = $queryString ? '&' . $queryString : '';
                    ?>
                    
                    <?php if ($page > 1): ?>
                        <a href="?page=1<?php echo $queryString; ?>">First</a>
                        <a href="?page=<?php echo $page - 1; ?><?php echo $queryString; ?>">Previous</a>
                    <?php endif; ?>

                    <?php
                    $startPage = max(1, $page - 2);
                    $endPage = min($totalPages, $page + 2);
                    
                    for ($i = $startPage; $i <= $endPage; $i++):
                    ?>
                        <?php if ($i == $page): ?>
                            <span class="current"><?php echo $i; ?></span>
                        <?php else: ?>
                            <a href="?page=<?php echo $i; ?><?php echo $queryString; ?>"><?php echo $i; ?></a>
                        <?php endif; ?>
                    <?php endfor; ?>

                    <?php if ($page < $totalPages): ?>
                        <a href="?page=<?php echo $page + 1; ?><?php echo $queryString; ?>">Next</a>
                        <a href="?page=<?php echo $totalPages; ?><?php echo $queryString; ?>">Last</a>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
<?php include 'includes/footer.php'; ?>
</body>
</html>

