<?php
require_once '../functions.php';
requireAdminAuth();

$admin = getCurrentAdmin();

if ($admin['role'] !== 'super_admin') {
    setFlash('Access denied. Super Admin only.', 'error');
    header('Location: dashboard.php');
    exit();
}

$db = getDB();

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

// Get activity logs with user/admin info
$logs = $db->query("SELECT al.*, u.first_name as user_first, u.last_name as user_last, a.first_name as admin_first, a.last_name as admin_last, a.username as admin_user 
    FROM activity_logs al 
    LEFT JOIN users u ON al.user_id = u.id 
    LEFT JOIN admin_users a ON al.admin_id = a.id 
    ORDER BY al.created_at DESC 
    LIMIT $limit OFFSET $offset");

$totalRecords = $db->query("SELECT COUNT(*) as total FROM activity_logs")->fetch_assoc()['total'];
$totalPages = ceil($totalRecords / $limit);

// FIXED: Removed the non-existent lh.admin_id join to eliminate the SQL exception error
$loginHistory = $db->query("SELECT lh.*, u.first_name as user_first, u.last_name as user_last 
    FROM login_history lh 
    LEFT JOIN users u ON lh.user_id = u.id 
    ORDER BY lh.created_at DESC 
    LIMIT 20");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Activity Logs - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="../assets/css/style.css">
</head>
<body>
    <?php include 'includes/admin-sidebar.php'; ?>
    
    <div class="main-content">
        <?php include 'includes/admin-header.php'; ?>
        
        <div class="page-content">
            <div class="tabs">
                <a href="?tab=activity" class="tab-btn <?php echo ($_GET['tab'] ?? 'activity') === 'activity' ? 'active' : ''; ?>">Activity Logs</a>
                <a href="?tab=login" class="tab-btn <?php echo ($_GET['tab'] ?? '') === 'login' ? 'active' : ''; ?>">Login History</a>
            </div>
            
            <?php if (($_GET['tab'] ?? 'activity') === 'activity'): ?>
            <div class="card">
                <div class="card-body" style="padding: 0;">
                    <div class="table-container">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Action</th>
                                    <th>Description</th>
                                    <th>User</th>
                                    <th>IP Address</th>
                                    <th>Timestamp</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($logs && $logs->num_rows > 0): ?>
                                    <?php while ($log = $logs->fetch_assoc()): 
                                        // Dynamically compute admin full name
                                        $adminName = trim(($log['admin_first'] ?? '') . ' ' . ($log['admin_last'] ?? ''));
                                        if (empty($adminName)) { $adminName = $log['admin_user'] ?? 'Admin'; }
                                    ?>
                                        <tr>
                                            <td><span class="status-badge info" style="font-size: 11px;"><?php echo e($log['action']); ?></span></td>
                                            <td style="font-size: 13px;"><?php echo e($log['description'] ?? '-'); ?></td>
                                            <td>
                                                <?php if ($log['user_id']): ?>
                                                    <div style="font-size: 13px;"><?php echo e($log['user_first'] . ' ' . $log['user_last']); ?></div>
                                                    <div style="font-size: 11px; color: var(--gray);">User</div>
                                                <?php elseif ($log['admin_id']): ?>
                                                    <div style="font-size: 13px;"><?php echo e($adminName); ?></div>
                                                    <div style="font-size: 11px; color: var(--gray);">Admin</div>
                                                <?php else: ?>
                                                    <span style="color: var(--gray);">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <td><code style="font-size: 11px;"><?php echo e($log['ip_address'] ?? '-'); ?></code></td>
                                            <td style="font-size: 12px;"><?php echo formatDate($log['created_at']); ?></td>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr><td colspan="5" class="text-center" style="padding: 40px; color: var(--gray);">No activity logs found</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <?php if ($totalPages > 1): ?>
                    <div style="padding: 16px 24px;">
                        <div class="pagination">
                            <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                                <?php if ($i === $page): ?>
                                    <span><?php echo $i; ?></span>
                                <?php else: ?>
                                    <a href="?tab=activity&page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                <?php endif; ?>
                            <?php endfor; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>
            
            <?php if (($_GET['tab'] ?? '') === 'login'): ?>
            <div class="card">
                <div class="card-body" style="padding: 0;">
                    <div class="table-container">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Type</th>
                                    <th>User</th>
                                    <th>IP Address</th>
                                    <th>Device</th>
                                    <th>Location</th>
                                    <th>Status</th>
                                    <th>Login Time</th>
                                    <th>Logout Time</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($loginHistory && $loginHistory->num_rows > 0): ?>
                                    <?php while ($lh = $loginHistory->fetch_assoc()): ?>
                                        <tr>
                                            <td><span class="status-badge <?php echo $lh['login_type'] === 'admin' ? 'danger' : 'info'; ?>" style="font-size: 11px;"><?php echo ucfirst(e($lh['login_type'])); ?></span></td>
                                            <td>
                                                <?php if ($lh['user_id'] && !empty($lh['user_first'])): ?>
                                                    <?php echo e($lh['user_first'] . ' ' . $lh['user_last']); ?>
                                                <?php else: ?>
                                                    <span style="color: var(--gray); font-style: italic;">Staff / Account ID: <?php echo e($lh['user_id'] ?? 'System'); ?></span>
                                                <?php endif; ?>
                                            </td>
                                            <td><code style="font-size: 11px;"><?php echo e($lh['ip_address'] ?? '-'); ?></code></td>
                                            <td style="font-size: 12px;"><?php echo e(substr($lh['device_info'] ?? '-', 0, 30)); ?></td>
                                            <td style="font-size: 12px;"><?php echo e($lh['location'] ?? '-'); ?></td>
                                            <td><span class="status-badge <?php echo e($lh['status']); ?>" style="font-size: 11px;"><?php echo ucfirst(e($lh['status'])); ?></span></td>
                                            <td style="font-size: 12px;"><?php echo formatDate($lh['created_at']); ?></td>
                                            <td style="font-size: 12px;"><?php echo $lh['logout_at'] ? formatDate($lh['logout_at']) : '-'; ?></td>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr><td colspan="8" class="text-center" style="padding: 40px; color: var(--gray);">No login history found</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
    
    <script src="../assets/js/main.js"></script>
</body>
</html>