<?php

// Best-effort activity logger for PHP Admin (roleId=2,3).
// Stores events in MySQL table tb_usuarios_admin_log.

if (!function_exists('cpn_activity_log_event')) {
    function cpn_activity_log_event(string $section, string $eventKey, string $message, ?string $entityType = null, $entityId = null, ?array $extra = null): void
    {
        if (session_status() === PHP_SESSION_NONE) {
            @session_start();
        }

        $user = $_SESSION['user'] ?? null;
        if (!is_array($user)) return;

        $roleId = isset($user['roleId']) ? (int)$user['roleId'] : 0;
        if (!in_array($roleId, [2, 3], true)) return; // only log editor/impresor activity

        $idUsuarioAdmin = isset($user['id']) ? (int)$user['id'] : 0;
        if ($idUsuarioAdmin <= 0) return;

        $nombre = trim((string)($user['nombre'] ?? ''));
        $apellido = trim((string)($user['apellido'] ?? ''));
        $usuarioNombre = trim($nombre . ' ' . $apellido);
        if ($usuarioNombre === '') {
            $usuarioNombre = (string)($user['email'] ?? '');
        }

        $section = trim($section);
        $eventKey = trim($eventKey);
        $message = trim($message);
        if ($section === '' || $eventKey === '' || $message === '') return;

        $entityTypeDb = $entityType !== null ? trim((string)$entityType) : null;
        $entityIdDb = null;
        if ($entityId !== null && $entityId !== '') {
            $n = (int)$entityId;
            if ($n > 0) $entityIdDb = $n;
        }

        $ip = isset($_SERVER['REMOTE_ADDR']) ? (string)$_SERVER['REMOTE_ADDR'] : null;
        $ua = isset($_SERVER['HTTP_USER_AGENT']) ? (string)$_SERVER['HTTP_USER_AGENT'] : null;

        $extraJson = null;
        if (is_array($extra) && !empty($extra)) {
            $tmp = json_encode($extra, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
            if (is_string($tmp) && $tmp !== '') $extraJson = $tmp;
        }

        try {
            // Uses existing DB connection file (provides $conn as mysqli)
            require_once __DIR__ . '/../db/db.php';
            if (!isset($conn) || !($conn instanceof mysqli)) return;

            $sql = "INSERT INTO tb_usuarios_admin_log\n                (fecha, idUsuarioAdmin, usuarioNombre, roleId, section, eventKey, entityType, entityId, message, extraJson, ip, userAgent)\n                VALUES (NOW(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

            $stmt = $conn->prepare($sql);
            if (!$stmt) return;

            // Bind: i s i s s s i s s s s
            $stmt->bind_param(
                'isisssissss',
                $idUsuarioAdmin,
                $usuarioNombre,
                $roleId,
                $section,
                $eventKey,
                $entityTypeDb,
                $entityIdDb,
                $message,
                $extraJson,
                $ip,
                $ua
            );

            @$stmt->execute();
            @$stmt->close();
        } catch (Throwable $e) {
            // Never block business flow due to logging.
            return;
        }
    }
}
