<?php
/**
 * Activity Log System
 * Auto-logs all CRUD operations
 */

function logActivity($pdo, $action, $module, $record_id = null, $details = '') {
    $user_id = $_SESSION['user_id'] ?? null;
    if (!$user_id) return;

    $stmt = $pdo->prepare("INSERT INTO activity_log (user_id, action, module, record_id, details, ip_address, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())");
    $stmt->execute([$user_id, $action, $module, $record_id, $details, $_SERVER['REMOTE_ADDR'] ?? '']);
}

function getRecentActivity($pdo, $limit = 20) {
    $stmt = $pdo->prepare("SELECT a.*, u.full_name, u.role
                           FROM activity_log a
                           LEFT JOIN users u ON a.user_id = u.id
                           ORDER BY a.created_at DESC LIMIT ?");
    $stmt->execute([$limit]);
    return $stmt->fetchAll();
}

function getActivityIcon($action) {
    $icons = [
        'create' => '<i class="fas fa-plus-circle text-success"></i>',
        'update' => '<i class="fas fa-edit text-warning"></i>',
        'delete' => '<i class="fas fa-trash text-danger"></i>',
        'login'  => '<i class="fas fa-sign-in-alt text-info"></i>',
        'logout' => '<i class="fas fa-sign-out-alt text-secondary"></i>',
        'complete' => '<i class="fas fa-check-circle text-success"></i>',
        'cancel' => '<i class="fas fa-times-circle text-danger"></i>',
        'upload' => '<i class="fas fa-cloud-upload-alt text-primary"></i>',
    ];
    return $icons[$action] ?? '<i class="fas fa-circle text-muted"></i>';
}

function getActivityBadge($module) {
    $badges = [
        'dozar' => '<span class="badge bg-success">Dozar</span>',
        'tripper' => '<span class="badge bg-primary">Tripper</span>',
        'user' => '<span class="badge bg-info">User</span>',
        'vehicle' => '<span class="badge bg-warning text-dark">Vehicle</span>',
        'driver' => '<span class="badge bg-secondary">Driver</span>',
        'project' => '<span class="badge bg-dark">Project</span>',
        'group' => '<span class="badge bg-danger">Group</span>',
        'auth' => '<span class="badge bg-info">Auth</span>',
    ];
    return $badges[$module] ?? '<span class="badge bg-secondary">' . ucfirst($module) . '</span>';
}
