<?php

declare(strict_types=1);

/**
 * Record an activity without interrupting the main application workflow.
 *
 * Logging errors are written to the PHP error log. They are not shown to
 * users and do not cancel the original operation.
 */
function logActivity(
    mysqli $conn,
    string $module,
    string $action,
    string $description = ''
): void {
    $userName = trim(
        (string)($_SESSION['fullname'] ?? '')
    );

    $role = trim(
        (string)($_SESSION['role'] ?? '')
    );

    if ($userName === '') {
        $userName = 'Unknown User';
    }

    if ($role === '') {
        $role = 'unknown';
    }

    $module = trim($module);
    $action = trim($action);
    $description = trim($description);

    if ($module === '' || $action === '') {
        error_log(
            'Activity log skipped: module or action was empty.'
        );

        return;
    }

    if (mb_strlen($userName) > 100) {
        $userName = mb_substr($userName, 0, 100);
    }

    if (mb_strlen($role) > 50) {
        $role = mb_substr($role, 0, 50);
    }

    if (mb_strlen($module) > 100) {
        $module = mb_substr($module, 0, 100);
    }

    if (mb_strlen($action) > 100) {
        $action = mb_substr($action, 0, 100);
    }

    $ipAddress = trim(
        (string)($_SERVER['REMOTE_ADDR'] ?? '')
    );

    if ($ipAddress !== '') {
        $validatedIp = filter_var(
            $ipAddress,
            FILTER_VALIDATE_IP
        );

        $ipAddress = $validatedIp !== false
            ? $ipAddress
            : '';
    }

    try {
        $statement = mysqli_prepare(
            $conn,
            'INSERT INTO activity_logs
            (
                log_time,
                user_name,
                role,
                module,
                action,
                description,
                ip_address
            )
            VALUES
            (
                NOW(),
                ?, ?, ?, ?, ?, ?
            )'
        );

        if (!$statement) {
            throw new RuntimeException(
                'Unable to prepare activity log statement.'
            );
        }

        mysqli_stmt_bind_param(
            $statement,
            'ssssss',
            $userName,
            $role,
            $module,
            $action,
            $description,
            $ipAddress
        );

        mysqli_stmt_execute($statement);
        mysqli_stmt_close($statement);
    } catch (Throwable $exception) {
        error_log(
            'Activity log error: ' .
            $exception->getMessage()
        );
    }
}
