<?php
$page_title = "Activity Logs";
require_once 'header.php';

$db = Database::getInstance()->connect();

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

// Filters
$action = $_GET['action'] ?? '';
$user_type = $_GET['user_type'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$search = $_GET['search'] ?? '';

// Build query
$where = [];
$params = [];

if ($action) {
    $where[] = "l.action = ?";
    $params[] = $action;
}

if ($user_type) {
    if ($user_type == 'user') {
        $where[] = "l.user_id IS NOT NULL";
    } elseif ($user_type == 'admin') {
        $where[] = "l.admin_id IS NOT NULL";
    }
}

if ($date_from) {
    $where[] = "DATE(l.created_at) >= ?";
    $params[] = $date_from;
}

if ($date_to) {
    $where[] = "DATE(l.created_at) <= ?";
    $params[] = $date_to;
}

if ($search) {
    $where[] = "(l.details LIKE ? OR u.username LIKE ? OR a.username LIKE ? OR l.ip_address LIKE ?)";
    $search_term = "%$search%";
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
}

$where_clause = $where ? "WHERE " . implode(" AND ", $where) : "";

// Get total count
$count_sql = "SELECT COUNT(*) as total FROM activity_logs l 
              LEFT JOIN users u ON l.user_id = u.id 
              LEFT JOIN admin_users a ON l.admin_id = a.id 
              $where_clause";
$count_stmt = $db->prepare($count_sql);
$count_stmt->execute($params);
$total_logs = $count_stmt->fetch()['total'];
$total_pages = ceil($total_logs / $limit);

// Get logs
$sql = "SELECT l.*, u.username as user_username, u.email as user_email, 
               a.username as admin_username, a.email as admin_email
        FROM activity_logs l 
        LEFT JOIN users u ON l.user_id = u.id 
        LEFT JOIN admin_users a ON l.admin_id = a.id 
        $where_clause 
        ORDER BY l.created_at DESC 
        LIMIT $limit OFFSET $offset";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$logs = $stmt->fetchAll();

// Get distinct actions for filter
$actions_stmt = $db->query("SELECT DISTINCT action FROM activity_logs ORDER BY action");
$actions = $actions_stmt->fetchAll();

// Get stats
$stats_sql = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN user_id IS NOT NULL THEN 1 ELSE 0 END) as user_actions,
    SUM(CASE WHEN admin_id IS NOT NULL THEN 1 ELSE 0 END) as admin_actions,
    COUNT(DISTINCT ip_address) as unique_ips,
    COUNT(DISTINCT DATE(created_at)) as active_days
    FROM activity_logs 
    WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)";

$stats_stmt = $db->query($stats_sql);
$stats = $stats_stmt->fetch();
?>

<div class="container-fluid">
    <!-- Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Logs</p>
                    <h3 class="text-2xl font-bold"><?php echo number_format($total_logs); ?></h3>
                </div>
                <i class="fas fa-history text-blue-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">User Actions</p>
                    <h3 class="text-2xl font-bold text-green-600"><?php echo number_format($stats['user_actions']); ?></h3>
                </div>
                <i class="fas fa-users text-green-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Admin Actions</p>
                    <h3 class="text-2xl font-bold text-purple-600"><?php echo number_format($stats['admin_actions']); ?></h3>
                </div>
                <i class="fas fa-user-shield text-purple-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Unique IPs</p>
                    <h3 class="text-2xl font-bold"><?php echo number_format($stats['unique_ips']); ?></h3>
                </div>
                <i class="fas fa-network-wired text-yellow-500 text-2xl"></i>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-xl shadow p-6 mb-6">
        <form method="GET" action="" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                <!-- Action Filter -->
                <div>
                    <label class="block text-gray-700 text-sm mb-2">Action Type</label>
                    <select name="action" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                        <option value="">All Actions</option>
                        <?php foreach ($actions as $act): ?>
                        <option value="<?php echo $act['action']; ?>" <?php echo $action == $act['action'] ? 'selected' : ''; ?>>
                            <?php echo ucfirst(str_replace('_', ' ', $act['action'])); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <!-- User Type -->
                <div>
                    <label class="block text-gray-700 text-sm mb-2">User Type</label>
                    <select name="user_type" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                        <option value="">All Users</option>
                        <option value="user" <?php echo $user_type == 'user' ? 'selected' : ''; ?>>Users Only</option>
                        <option value="admin" <?php echo $user_type == 'admin' ? 'selected' : ''; ?>>Admins Only</option>
                    </select>
                </div>
                
                <!-- Date From -->
                <div>
                    <label class="block text-gray-700 text-sm mb-2">From Date</label>
                    <input type="date" name="date_from" value="<?php echo htmlspecialchars($date_from); ?>"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                </div>
                
                <!-- Date To -->
                <div>
                    <label class="block text-gray-700 text-sm mb-2">To Date</label>
                    <input type="date" name="date_to" value="<?php echo htmlspecialchars($date_to); ?>"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                </div>
            </div>
            
            <!-- Search -->
            <div>
                <label class="block text-gray-700 text-sm mb-2">Search</label>
                <div class="flex">
                    <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>"
                           class="flex-1 px-4 py-2 border border-gray-300 rounded-l-lg focus:ring-2 focus:ring-purple-500"
                           placeholder="Search in details, usernames, or IP addresses">
                    <button type="submit" class="bg-purple-600 text-white px-4 py-2 rounded-r-lg hover:bg-purple-700">
                        <i class="fas fa-search"></i>
                    </button>
                </div>
            </div>
            
            <div class="flex justify-between items-center pt-4">
                <div>
                    <button type="submit" class="bg-purple-600 text-white px-4 py-2 rounded-lg hover:bg-purple-700">
                        <i class="fas fa-filter mr-2"></i>Apply Filters
                    </button>
                    <a href="logs.php" class="ml-2 text-gray-600 hover:text-gray-800">
                        Clear Filters
                    </a>
                </div>
                
                <div>
                    <button type="button" onclick="exportLogs()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
                        <i class="fas fa-download mr-2"></i>Export Logs
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- Activity Logs -->
    <div class="bg-white rounded-xl shadow overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="p-4 text-left">Time</th>
                        <th class="p-4 text-left">Action</th>
                        <th class="p-4 text-left">User</th>
                        <th class="p-4 text-left">Details</th>
                        <th class="p-4 text-left">IP Address</th>
                        <th class="p-4 text-left">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    <?php if (count($logs) > 0): ?>
                        <?php foreach ($logs as $log): 
                            $details = json_decode($log['details'] ?? '{}', true) ?: [];
                            $is_admin = !empty($log['admin_id']);
                        ?>
                        <tr class="hover:bg-gray-50">
                            <!-- Time -->
                            <td class="p-4">
                                <p><?php echo date('M d, Y', strtotime($log['created_at'])); ?></p>
                                <p class="text-sm text-gray-500"><?php echo date('H:i:s', strtotime($log['created_at'])); ?></p>
                            </td>
                            
                            <!-- Action -->
                            <td class="p-4">
                                <span class="px-3 py-1 rounded-full text-xs font-semibold <?php
                                    echo strpos($log['action'], 'login') !== false ? 'bg-green-100 text-green-800' :
                                        (strpos($log['action'], 'delete') !== false ? 'bg-red-100 text-red-800' :
                                        (strpos($log['action'], 'update') !== false ? 'bg-blue-100 text-blue-800' :
                                        (strpos($log['action'], 'create') !== false ? 'bg-purple-100 text-purple-800' :
                                        'bg-gray-100 text-gray-800')));
                                ?>">
                                    <?php echo ucfirst(str_replace('_', ' ', $log['action'])); ?>
                                </span>
                            </td>
                            
                            <!-- User -->
                            <td class="p-4">
                                <?php if ($is_admin): ?>
                                <div>
                                    <p class="font-medium"><?php echo htmlspecialchars($log['admin_username']); ?></p>
                                    <p class="text-sm text-gray-500">Admin</p>
                                    <p class="text-xs text-purple-600">ID: <?php echo $log['admin_id']; ?></p>
                                </div>
                                <?php elseif ($log['user_id']): ?>
                                <div>
                                    <p class="font-medium"><?php echo htmlspecialchars($log['user_username']); ?></p>
                                    <p class="text-sm text-gray-500">User</p>
                                    <p class="text-xs text-blue-600">ID: <?php echo $log['user_id']; ?></p>
                                </div>
                                <?php else: ?>
                                <span class="text-gray-500">System</span>
                                <?php endif; ?>
                            </td>
                            
                            <!-- Details -->
                            <td class="p-4">
                                <div class="max-w-xs">
                                    <?php if (!empty($details)): ?>
                                        <?php foreach ($details as $key => $value): ?>
                                        <p class="text-sm">
                                            <span class="text-gray-600"><?php echo ucfirst(str_replace('_', ' ', $key)); ?>:</span>
                                            <span class="font-medium">
                                                <?php 
                                                if (is_array($value)) {
                                                    echo json_encode($value);
                                                } elseif (is_bool($value)) {
                                                    echo $value ? 'Yes' : 'No';
                                                } else {
                                                    echo htmlspecialchars((string)$value);
                                                }
                                                ?>
                                            </span>
                                        </p>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <p class="text-gray-500 text-sm">No details</p>
                                    <?php endif; ?>
                                </div>
                            </td>
                            
                            <!-- IP Address -->
                            <td class="p-4">
                                <p class="font-mono text-sm"><?php echo $log['ip_address']; ?></p>
                                <?php if ($log['user_agent']): ?>
                                <p class="text-xs text-gray-500 truncate max-w-xs"><?php echo substr($log['user_agent'], 0, 50); ?>...</p>
                                <?php endif; ?>
                            </td>
                            
                            <!-- Actions -->
                            <td class="p-4">
                                <div class="flex flex-col space-y-2">
                                    <button onclick="viewLogDetails(<?php echo $log['id']; ?>)" 
                                            class="text-blue-600 hover:text-blue-800 text-sm font-medium">
                                        <i class="fas fa-eye mr-1"></i> View Details
                                    </button>
                                    
                                    <a href="?action=delete&id=<?php echo $log['id']; ?>" 
                                       onclick="return confirm('Delete this log entry?')"
                                       class="text-red-600 hover:text-red-800 text-sm font-medium">
                                        <i class="fas fa-trash mr-1"></i> Delete
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="6" class="p-8 text-center text-gray-500">
                                <i class="fas fa-history text-4xl mb-4 text-gray-300"></i>
                                <p class="text-lg">No activity logs found</p>
                                <?php if ($action || $date_from || $search): ?>
                                <p class="text-sm mt-2">Try changing your search filters</p>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="border-t border-gray-100 p-4">
            <div class="flex items-center justify-between">
                <div class="text-sm text-gray-600">
                    Showing <?php echo ($offset + 1); ?> to <?php echo min($offset + $limit, $total_logs); ?> of <?php echo number_format($total_logs); ?> logs
                </div>
                <div class="flex space-x-2">
                    <?php if ($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?><?php echo http_build_query(array_filter([
                        'action' => $action,
                        'user_type' => $user_type,
                        'date_from' => $date_from,
                        'date_to' => $date_to,
                        'search' => $search
                    ])); ?>"
                       class="px-3 py-2 bg-gray-100 rounded-lg hover:bg-gray-200">
                        <i class="fas fa-chevron-left"></i> Previous
                    </a>
                    <?php endif; ?>
                    
                    <?php
                    $start = max(1, $page - 2);
                    $end = min($total_pages, $start + 4);
                    
                    for ($i = $start; $i <= $end; $i++):
                    ?>
                    <a href="?page=<?php echo $i; ?><?php echo http_build_query(array_filter([
                        'action' => $action,
                        'user_type' => $user_type,
                        'date_from' => $date_from,
                        'date_to' => $date_to,
                        'search' => $search
                    ])); ?>"
                       class="px-3 py-2 rounded-lg <?php echo $i == $page ? 'bg-purple-600 text-white' : 'bg-gray-100 hover:bg-gray-200'; ?>">
                        <?php echo $i; ?>
                    </a>
                    <?php endfor; ?>
                    
                    <?php if ($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?><?php echo http_build_query(array_filter([
                        'action' => $action,
                        'user_type' => $user_type,
                        'date_from' => $date_from,
                        'date_to' => $date_to,
                        'search' => $search
                    ])); ?>"
                       class="px-3 py-2 bg-gray-100 rounded-lg hover:bg-gray-200">
                        Next <i class="fas fa-chevron-right"></i>
                    </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
    
    <!-- Log Management -->
    <div class="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
        <!-- Bulk Actions -->
        <div class="bg-white rounded-xl shadow p-6">
            <h4 class="text-lg font-bold mb-4">Log Management</h4>
            <div class="space-y-3">
                <button onclick="clearOldLogs()" class="w-full bg-yellow-600 text-white py-2 rounded-lg hover:bg-yellow-700">
                    <i class="fas fa-broom mr-2"></i>Clear Logs Older Than 30 Days
                </button>
                <button onclick="deleteAllLogs()" class="w-full bg-red-600 text-white py-2 rounded-lg hover:bg-red-700">
                    <i class="fas fa-trash-alt mr-2"></i>Delete All Logs
                </button>
                <button onclick="exportFiltered()" class="w-full bg-blue-600 text-white py-2 rounded-lg hover:bg-blue-700">
                    <i class="fas fa-file-export mr-2"></i>Export Filtered Logs
                </button>
            </div>
        </div>
        
        <!-- Statistics -->
        <div class="bg-white rounded-xl shadow p-6">
            <h4 class="text-lg font-bold mb-4">Activity Statistics</h4>
            <div class="space-y-3">
                <div class="flex justify-between">
                    <span>Today's Activities:</span>
                    <span class="font-bold">
                        <?php
                        $today_stmt = $db->query("SELECT COUNT(*) as count FROM activity_logs WHERE DATE(created_at) = CURDATE()");
                        echo $today_stmt->fetch()['count'];
                        ?>
                    </span>
                </div>
                <div class="flex justify-between">
                    <span>This Week:</span>
                    <span class="font-bold">
                        <?php
                        $week_stmt = $db->query("SELECT COUNT(*) as count FROM activity_logs WHERE YEARWEEK(created_at, 1) = YEARWEEK(CURDATE(), 1)");
                        echo $week_stmt->fetch()['count'];
                        ?>
                    </span>
                </div>
                <div class="flex justify-between">
                    <span>This Month:</span>
                    <span class="font-bold">
                        <?php
                        $month_stmt = $db->query("SELECT COUNT(*) as count FROM activity_logs WHERE MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE())");
                        echo $month_stmt->fetch()['count'];
                        ?>
                    </span>
                </div>
                <div class="flex justify-between">
                    <span>Most Active Day:</span>
                    <span class="font-bold">
                        <?php
                        $active_stmt = $db->query("SELECT DATE(created_at) as date, COUNT(*) 
                        ?>
                    </span>
                </div>
                <div class="flex justify-between">
                    <span>Most Common Action:</span>
                    <span class="font-bold">
                        <?php
                        $action_stmt = $db->query("SELECT action, COUNT(*) as count FROM activity_logs GROUP BY action ORDER BY count DESC LIMIT 1");
                        $most_common = $action_stmt->fetch();
                        echo $most_common ? ucfirst(str_replace('_', ' ', $most_common['action'])) : 'N/A';
                        ?>
                    </span>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- View Log Details Modal -->
<div id="logDetailsModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[90vh] overflow-hidden">
            <div class="flex justify-between items-center p-6 border-b">
                <h3 class="text-xl font-bold">Log Details</h3>
                <button onclick="closeModal()" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            <div class="p-6 overflow-y-auto max-h-[calc(90vh-120px)]">
                <div id="logDetailsContent">
                    <!-- Details will be loaded here -->
                </div>
            </div>
            <div class="border-t p-6">
                <button onclick="closeModal()" class="w-full bg-gray-600 text-white py-2 rounded-lg hover:bg-gray-700">
                    Close
                </button>
            </div>
        </div>
    </div>
</div>

<script>
function viewLogDetails(logId) {
    fetch('ajax/get_log_details.php?id=' + logId)
        .then(response => response.text())
        .then(html => {
            document.getElementById('logDetailsContent').innerHTML = html;
            document.getElementById('logDetailsModal').classList.remove('hidden');
            document.body.classList.add('overflow-hidden');
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('Error loading log details', 'error');
        });
}

function closeModal() {
    document.getElementById('logDetailsModal').classList.add('hidden');
    document.body.classList.remove('overflow-hidden');
}

function exportLogs() {
    const params = new URLSearchParams(window.location.search);
    window.open('export_logs.php?' + params.toString(), '_blank');
}

function exportFiltered() {
    exportLogs();
}

function clearOldLogs() {
    if (confirm('This will delete all logs older than 30 days. Continue?')) {
        fetch('ajax/clear_old_logs.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({})
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification(data.message, 'success');
                location.reload();
            } else {
                showNotification('Error: ' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('Error clearing logs', 'error');
        });
    }
}

function deleteAllLogs() {
    const confirmation = prompt('Type "DELETE" to confirm deletion of ALL logs:');
    if (confirmation === 'DELETE') {
        fetch('ajax/delete_all_logs.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({})
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification(data.message, 'success');
                location.reload();
            } else {
                showNotification('Error: ' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('Error deleting logs', 'error');
        });
    }
}
</script>

<?php
// Handle log deletion
if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    $logId = intval($_GET['id']);
    $delete_sql = "DELETE FROM activity_logs WHERE id = ?";
    $delete_stmt = $db->prepare($delete_sql);
    $delete_stmt->execute([$logId]);
    
    // Log the deletion
    $admin_id = $_SESSION['admin_id'] ?? null;
    $log_sql = "INSERT INTO activity_logs (action, admin_id, details, ip_address, user_agent) 
                VALUES (?, ?, ?, ?, ?)";
    $log_stmt = $db->prepare($log_sql);
    $log_stmt->execute([
        'log_deleted',
        $admin_id,
        json_encode(['log_id' => $logId, 'deleted_by_admin' => $admin_id]),
        $_SERVER['REMOTE_ADDR'],
        $_SERVER['HTTP_USER_AGENT'] ?? ''
    ]);
    
    header('Location: logs.php');
    exit;
}

require_once 'footer.php';