<?php
define('ROVO_APP', true);
require_once '../config.php';
require_once '../Auth.php';

$page_title = 'Activity Logs';

if (!$auth->isAdmin()) {
    $_SESSION['error'] = "You don't have permission to access this page";
    header('Location: dashboard.php');
    exit;
}

// Get filter parameters
$search = $_GET['search'] ?? '';
$user_filter = $_GET['user'] ?? '';
$action_filter = $_GET['action'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 50;
$offset = ($page - 1) * $limit;

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

if ($search) {
    $where[] = "(description LIKE ? OR entity_type LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($user_filter) {
    $where[] = "al.user_id = ?";
    $params[] = (int)$user_filter;
}

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

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

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

$where_sql = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';

$count_sql = "SELECT COUNT(*) as total FROM activity_logs al $where_sql";
$total = $db->fetchOne($count_sql, $params)['total'];
$total_pages = ceil($total / $limit);

$sql = "SELECT al.*, 
        CONCAT(u.first_name, ' ', u.last_name) as user_name,
        u.role as user_role
        FROM activity_logs al
        LEFT JOIN users u ON al.user_id = u.id
        $where_sql
        ORDER BY al.created_at DESC
        LIMIT $limit OFFSET $offset";

$logs = $db->fetchAll($sql, $params);

// Get all users for filter
$users = $db->fetchAll("SELECT id, CONCAT(first_name, ' ', last_name) as name FROM users ORDER BY first_name");

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

include 'includes/header.php';
?>

<div class="page-header">
    <h1>Activity Logs</h1>
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
            <li class="breadcrumb-item active">Activity Logs</li>
        </ol>
    </nav>
</div>

<div class="card">
    <div class="card-header">
        <h5 class="mb-0">
            <i class="fas fa-history"></i> System Activity Logs
            <span class="badge bg-primary"><?php echo number_format($total); ?></span>
        </h5>
    </div>
    
    <div class="card-body">
        <!-- Advanced Filters -->
        <form method="GET" class="mb-4">
            <div class="row g-3">
                <div class="col-md-3">
                    <div class="input-group">
                        <span class="input-group-text"><i class="fas fa-search"></i></span>
                        <input type="text" name="search" class="form-control" placeholder="Search..." 
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                </div>
                
                <div class="col-md-3">
                    <select name="user" class="form-select">
                        <option value="">All Users</option>
                        <?php foreach ($users as $user): ?>
                        <option value="<?php echo $user['id']; ?>" 
                                <?php echo $user_filter == $user['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($user['name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <select name="action" class="form-select">
                        <option value="">All Actions</option>
                        <?php foreach ($actions as $action): ?>
                        <option value="<?php echo htmlspecialchars($action['action']); ?>" 
                                <?php echo $action_filter === $action['action'] ? 'selected' : ''; ?>>
                            <?php echo ucfirst(str_replace('_', ' ', $action['action'])); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <input type="date" name="date_from" class="form-control" placeholder="From Date"
                           value="<?php echo htmlspecialchars($date_from); ?>">
                </div>
                
                <div class="col-md-2">
                    <input type="date" name="date_to" class="form-control" placeholder="To Date"
                           value="<?php echo htmlspecialchars($date_to); ?>">
                </div>
            </div>
            
            <div class="row mt-3">
                <div class="col-12">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-filter"></i> Apply Filters
                    </button>
                    <a href="activity-logs.php" class="btn btn-outline-secondary">
                        <i class="fas fa-times"></i> Clear Filters
                    </a>
                </div>
            </div>
        </form>
        
        <!-- Activity Logs Table -->
        <div class="table-responsive">
            <table class="table table-hover table-sm">
                <thead>
                    <tr>
                        <th style="width: 50px;">#</th>
                        <th>User</th>
                        <th>Action</th>
                        <th>Description</th>
                        <th>Entity</th>
                        <th>IP Address</th>
                        <th>Date & Time</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($logs)): ?>
                    <tr>
                        <td colspan="7" class="text-center py-4">
                            <i class="fas fa-history fa-3x text-muted mb-3 d-block"></i>
                            <p class="text-muted">No activity logs found</p>
                        </td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($logs as $index => $log): ?>
                        <tr>
                            <td><?php echo $offset + $index + 1; ?></td>
                            <td>
                                <?php if ($log['user_name']): ?>
                                <strong><?php echo htmlspecialchars($log['user_name']); ?></strong>
                                <br>
                                <small class="text-muted">
                                    <span class="badge bg-secondary" style="font-size: 0.7rem;">
                                        <?php echo ucfirst(str_replace('_', ' ', $log['user_role'])); ?>
                                    </span>
                                </small>
                                <?php else: ?>
                                <span class="text-muted">System</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php
                                $action_icons = [
                                    'login' => 'sign-in-alt text-success',
                                    'logout' => 'sign-out-alt text-info',
                                    'register' => 'user-plus text-primary',
                                    'create' => 'plus text-success',
                                    'update' => 'edit text-warning',
                                    'delete' => 'trash text-danger',
                                    'approve' => 'check text-success',
                                    'reject' => 'times text-danger',
                                    'suspend' => 'ban text-warning',
                                    'activate' => 'check-circle text-success'
                                ];
                                
                                $icon = $action_icons[$log['action']] ?? 'circle text-secondary';
                                ?>
                                <i class="fas fa-<?php echo $icon; ?>"></i>
                                <strong><?php echo ucfirst(str_replace('_', ' ', $log['action'])); ?></strong>
                            </td>
                            <td>
                                <small><?php echo htmlspecialchars($log['description']); ?></small>
                            </td>
                            <td>
                                <?php if ($log['entity_type']): ?>
                                <span class="badge bg-info">
                                    <?php echo ucfirst($log['entity_type']); ?>
                                    <?php if ($log['entity_id']): ?>
                                    #<?php echo $log['entity_id']; ?>
                                    <?php endif; ?>
                                </span>
                                <?php else: ?>
                                <span class="text-muted">-</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <small class="text-muted">
                                    <i class="fas fa-network-wired"></i>
                                    <?php echo htmlspecialchars($log['ip_address']); ?>
                                </small>
                            </td>
                            <td>
                                <?php 
                                $timestamp = strtotime($log['created_at']);
                                $now = time();
                                $diff = $now - $timestamp;
                                
                                if ($diff < 60) {
                                    $time_ago = 'Just now';
                                } elseif ($diff < 3600) {
                                    $time_ago = floor($diff / 60) . ' min ago';
                                } elseif ($diff < 86400) {
                                    $time_ago = floor($diff / 3600) . ' hr ago';
                                } else {
                                    $time_ago = date('M d, Y', $timestamp);
                                }
                                ?>
                                <small>
                                    <?php echo date('M d, Y', $timestamp); ?>
                                    <br>
                                    <span class="text-muted"><?php echo date('H:i:s', $timestamp); ?></span>
                                    <br>
                                    <span class="badge bg-light text-dark" style="font-size: 0.65rem;">
                                        <?php echo $time_ago; ?>
                                    </span>
                                </small>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <nav>
            <ul class="pagination justify-content-center">
                <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>">Previous</a>
                </li>
                
                <?php
                $start_page = max(1, $page - 2);
                $end_page = min($total_pages, $page + 2);
                
                if ($start_page > 1): ?>
                <li class="page-item">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => 1])); ?>">1</a>
                </li>
                <?php if ($start_page > 2): ?>
                <li class="page-item disabled"><span class="page-link">...</span></li>
                <?php endif; ?>
                <?php endif; ?>
                
                <?php for ($i = $start_page; $i <= $end_page; $i++): ?>
                <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>"><?php echo $i; ?></a>
                </li>
                <?php endfor; ?>
                
                <?php if ($end_page < $total_pages): ?>
                <?php if ($end_page < $total_pages - 1): ?>
                <li class="page-item disabled"><span class="page-link">...</span></li>
                <?php endif; ?>
                <li class="page-item">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $total_pages])); ?>"><?php echo $total_pages; ?></a>
                </li>
                <?php endif; ?>
                
                <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>">Next</a>
                </li>
            </ul>
        </nav>
        
        <p class="text-center text-muted">
            Showing <?php echo min($offset + 1, $total); ?> to <?php echo min($offset + $limit, $total); ?> 
            of <?php echo number_format($total); ?> logs
        </p>
        <?php endif; ?>
    </div>
</div>

<?php include 'includes/footer.php'; ?>