<?php
/**
 * Audit Logging Functions
 * Tracks user activities and system changes for audit trail
 */

/**
 * Log an activity/audit event
 * 
 * @param string $action Action performed (e.g., 'user_created', 'settings_updated', 'login_success', 'login_failed')
 * @param string $description Human-readable description
 * @param array $details Additional details (JSON encoded)
 * @param int|null $user_id User who performed the action (null for system actions)
 * @param string|null $ip_address IP address of the user
 */
function logActivity($action, $description, $details = [], $user_id = null, $ip_address = null) {
    global $pdo;
    
    if (!isset($pdo)) {
        return false;
    }
    
    // Ensure activity_logs table exists
    try {
        $pdo->query('SELECT 1 FROM activity_logs LIMIT 1');
    } catch (PDOException $e) {
        // Table doesn't exist, create it
        try {
            $pdo->exec("
                CREATE TABLE IF NOT EXISTS activity_logs (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    action VARCHAR(100) NOT NULL,
                    description TEXT NOT NULL,
                    details TEXT NULL,
                    user_id INT NULL,
                    username VARCHAR(50) NULL,
                    ip_address VARCHAR(45) NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    INDEX idx_action (action),
                    INDEX idx_user_id (user_id),
                    INDEX idx_created_at (created_at),
                    INDEX idx_ip_address (ip_address),
                    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            ");
        } catch (PDOException $e2) {
            // If creation fails, silently return
            return false;
        }
    }
    
    // Get user info if user_id is provided
    $username = null;
    if ($user_id) {
        try {
            $stmt = $pdo->prepare('SELECT username FROM users WHERE id = ?');
            $stmt->execute([$user_id]);
            $user = $stmt->fetch();
            if ($user) {
                $username = $user['username'];
            }
        } catch (PDOException $e) {
            // Ignore
        }
    }
    
    // Get IP address if not provided
    if ($ip_address === null) {
        $ip_address = $_SERVER['REMOTE_ADDR'] ?? null;
    }
    
    // Get current user_id from session if not provided
    if ($user_id === null && !empty($_SESSION['user_id'])) {
        $user_id = $_SESSION['user_id'];
    }
    
    try {
        $stmt = $pdo->prepare('
            INSERT INTO activity_logs (action, description, details, user_id, username, ip_address)
            VALUES (?, ?, ?, ?, ?, ?)
        ');
        
        $detailsJson = !empty($details) ? json_encode($details) : null;
        $stmt->execute([
            $action,
            $description,
            $detailsJson,
            $user_id,
            $username,
            $ip_address
        ]);
        
        return true;
    } catch (PDOException $e) {
        // Silently fail to avoid breaking the application
        error_log('Audit log error: ' . $e->getMessage());
        return false;
    }
}

/**
 * Log a failed login attempt
 */
function logFailedLogin($username, $reason = 'Invalid credentials', $ip_address = null) {
    return logActivity(
        'login_failed',
        "Failed login attempt for username: {$username}",
        ['username' => $username, 'reason' => $reason],
        null,
        $ip_address
    );
}

/**
 * Log a successful login
 */
function logSuccessfulLogin($user_id, $username) {
    return logActivity(
        'login_success',
        "User logged in: {$username}",
        ['username' => $username],
        $user_id
    );
}

/**
 * Log user creation
 */
function logUserCreated($created_by_user_id, $new_user_id, $new_username, $role) {
    return logActivity(
        'user_created',
        "Created new user: {$new_username} ({$role})",
        ['new_user_id' => $new_user_id, 'new_username' => $new_username, 'role' => $role],
        $created_by_user_id
    );
}

/**
 * Log user update
 */
function logUserUpdated($updated_by_user_id, $target_user_id, $target_username, $changes = []) {
    return logActivity(
        'user_updated',
        "Updated user: {$target_username}",
        ['target_user_id' => $target_user_id, 'target_username' => $target_username, 'changes' => $changes],
        $updated_by_user_id
    );
}

/**
 * Log user deletion
 */
function logUserDeleted($deleted_by_user_id, $deleted_username, $deleted_role) {
    return logActivity(
        'user_deleted',
        "Deleted user: {$deleted_username} ({$deleted_role})",
        ['deleted_username' => $deleted_username, 'deleted_role' => $deleted_role],
        $deleted_by_user_id
    );
}

/**
 * Log settings change
 */
function logSettingsChange($user_id, $setting_key, $old_value, $new_value) {
    return logActivity(
        'settings_updated',
        "Updated setting: {$setting_key}",
        ['setting_key' => $setting_key, 'old_value' => $old_value, 'new_value' => $new_value],
        $user_id
    );
}

/**
 * Log data cleanup
 */
function logDataCleanup($user_id, $tables_cleaned) {
    return logActivity(
        'data_cleaned',
        "Cleaned data from " . count($tables_cleaned) . " table(s)",
        ['tables' => $tables_cleaned],
        $user_id
    );
}

/**
 * Log backup creation
 */
function logBackupCreated($user_id, $backup_file) {
    return logActivity(
        'backup_created',
        "Created backup: {$backup_file}",
        ['backup_file' => $backup_file],
        $user_id
    );
}
