<?php
defined('ABSPATH') || exit;

/**
 * Activity-Log Tabelle installieren
 */
function iv1wpt_activity_log_install(): void {
    global $wpdb;

    $table_name = $wpdb->prefix . 'iv1_activity_log';
    $charset_collate = $wpdb->get_charset_collate();

    require_once ABSPATH . 'wp-admin/includes/upgrade.php';

    $sql = "CREATE TABLE {$table_name} (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        created_at DATETIME NOT NULL,
        user_id BIGINT UNSIGNED NULL,
        user_login VARCHAR(100) NULL,
        event_type VARCHAR(100) NOT NULL,
        object_type VARCHAR(100) NULL,
        object_name VARCHAR(255) NULL,
        message TEXT NOT NULL,
        ip_address VARCHAR(100) NULL,
        PRIMARY KEY  (id),
        KEY event_type (event_type),
        KEY created_at (created_at),
        KEY user_id (user_id)
    ) {$charset_collate};";

    dbDelta($sql);
}

/**
 * IP-Adresse sicher ermitteln
 */
function iv1wpt_activity_log_get_ip(): string {
    $ip = $_SERVER['REMOTE_ADDR'] ?? '';

    return sanitize_text_field($ip);
}

/**
 * Aktivität schreiben
 */
function iv1wpt_activity_log(
    string $event_type,
    string $message,
    string $object_type = '',
    string $object_name = '',
    int $user_id = 0
): void {
    if (!iv1wpt_has_pro()) {
        return;
    }
    global $wpdb;

    $table_name = $wpdb->prefix . 'iv1_activity_log';

    if ($user_id <= 0) {
        $user_id = get_current_user_id();
    }

    $user_login = '';

    if ($user_id > 0) {
        $user = get_userdata($user_id);
        if ($user) {
            $user_login = $user->user_login;
        }
    }

    $wpdb->insert(
        $table_name,
        [
            'created_at'  => current_time('mysql'),
            'user_id'     => $user_id ?: null,
            'user_login'  => $user_login,
            'event_type'  => sanitize_key($event_type),
            'object_type' => sanitize_key($object_type),
            'object_name' => sanitize_text_field($object_name),
            'message'     => sanitize_textarea_field($message),
            'ip_address'  => iv1wpt_activity_log_get_ip(),
        ],
        [
            '%s',
            '%d',
            '%s',
            '%s',
            '%s',
            '%s',
            '%s',
            '%s',
        ]
    );
}

/**
 * Benutzer erstellt
 */
add_action('user_register', function(int $user_id): void {
    $user = get_userdata($user_id);
    $login = $user ? $user->user_login : (string) $user_id;

    iv1wpt_activity_log(
        'user_created',
        sprintf(
            /* translators: %s: username */
            __('User created: %s', 'iv1-wp-tools'),
            $login
        ),
        'user',
        $login,
        $user_id
    );
});

/**
 * Benutzer gelöscht
 */
add_action('delete_user', function(int $user_id): void {
    $user = get_userdata($user_id);
    $login = $user ? $user->user_login : (string) $user_id;

    iv1wpt_activity_log(
        'user_deleted',
        sprintf(
            /* translators: %s: username */
            __('User deleted: %s', 'iv1-wp-tools'),
            $login
        ),
        'user',
        $login,
        $user_id
    );
});

/**
 * WordPress-Core aktualisiert
 */
add_action('upgrader_process_complete', function($upgrader, array $hook_extra): void {
    if (($hook_extra['type'] ?? '') !== 'core') {
        return;
    }

    iv1wpt_activity_log(
        'core_updated',
        __('WordPress core updated.', 'iv1-wp-tools'),
        'core',
        get_bloginfo('version')
    );
}, 10, 2);


/**
 * Logout
 */
add_action('wp_logout', function(int $user_id): void {
    $user = get_userdata($user_id);
    $login = $user ? $user->user_login : (string) $user_id;

    iv1wpt_activity_log(
        'user_logout',
        sprintf(
            /* translators: %s: username */
            __('User logged out: %s', 'iv1-wp-tools'),
            $login
        ),
        'user',
        $login,
        $user_id
    );
});

/**
 * Login
 */
add_action('wp_login', 'iv1wpt_activity_log_user_login', 10, 2);
function iv1wpt_activity_log_user_login(string $user_login, WP_User $user): void {
    iv1wpt_activity_log(
        'user_login',
        sprintf(
            /* translators: %s: username */
            __('User logged in: %s', 'iv1-wp-tools'),
            $user_login
        ),
        'user',
        $user_login,
        (int) $user->ID
    );
}

/**
 * Plugin installiert / aktualisiert
 */
add_action('upgrader_process_complete', function($upgrader, $hook_extra): void {

    if (!is_array($hook_extra)) {
        return;
    }

    $type   = $hook_extra['type'] ?? '';
    $action = $hook_extra['action'] ?? '';

    if ($type !== 'plugin') {
        return;
    }

    if (!in_array($action, ['install', 'update'], true)) {
        return;
    }

    $plugins = [];

    $skin_plugin = '';
    if (
        isset($upgrader->skin->plugin) &&
        !is_wp_error($upgrader->skin->plugin)
    ) {
        $skin_plugin = (string) $upgrader->skin->plugin;
    }

    $skin_result = $upgrader->skin->result ?? null;

    if (!empty($hook_extra['plugins']) && is_array($hook_extra['plugins'])) {
        $plugins = $hook_extra['plugins'];
    } elseif (!empty($hook_extra['plugin'])) {
        $plugins = [(string) $hook_extra['plugin']];
    } elseif (!empty($skin_plugin)) {
        $plugins = [$skin_plugin];
    } elseif (is_array($skin_result) && !empty($skin_result['destination_name'])) {
        $plugins = [(string) $skin_result['destination_name']];
    } elseif (is_array($skin_result) && !empty($skin_result['destination'])) {
        $plugins = [basename((string) $skin_result['destination'])];
    } elseif (is_wp_error($skin_result)) {
        $plugins = [
            sprintf(
				/* translators: %s: WordPress error message */
				__('Unknown plugin - error: %s', 'iv1-wp-tools'),			
                $skin_result->get_error_message()
            )
        ];
    }

    if (empty($plugins)) {
        $plugins = [__('Unknown plugin', 'iv1-wp-tools')];
    }

    foreach ($plugins as $plugin) {
        iv1wpt_activity_log(
            'plugin_' . $action,
            sprintf(
                /* translators: 1: action, 2: plugin path/name */
                __('Plugin %1$s: %2$s', 'iv1-wp-tools'),
                $action,
                $plugin
            ),
            'plugin',
            $plugin
        );
    }

}, 10, 2);

/**
 * Theme installiert / aktualisiert
 */
add_action('upgrader_process_complete', function($upgrader, $hook_extra): void {

    if (!is_array($hook_extra)) {
        return;
    }

    $type   = $hook_extra['type'] ?? '';
    $action = $hook_extra['action'] ?? '';

    if ($type !== 'theme') {
        return;
    }

    if (!in_array($action, ['install', 'update'], true)) {
        return;
    }

    $themes = [];

    $skin_theme = '';
    if (
        isset($upgrader->skin->theme) &&
        !is_wp_error($upgrader->skin->theme)
    ) {
        $skin_theme = (string) $upgrader->skin->theme;
    }

    $skin_result = $upgrader->skin->result ?? null;

    if (!empty($hook_extra['themes']) && is_array($hook_extra['themes'])) {
        $themes = $hook_extra['themes'];
    } elseif (!empty($hook_extra['theme'])) {
        $themes = [(string) $hook_extra['theme']];
    } elseif (!empty($skin_theme)) {
        $themes = [$skin_theme];
    } elseif (is_array($skin_result) && !empty($skin_result['destination_name'])) {
        $themes = [(string) $skin_result['destination_name']];
    } elseif (is_array($skin_result) && !empty($skin_result['destination'])) {
        $themes = [basename((string) $skin_result['destination'])];
    } elseif (is_wp_error($skin_result)) {
        $themes = [
            sprintf(
				/* translators: %s: WordPress error message */
                __('Unknown theme - error: %s', 'iv1-wp-tools'),
                $skin_result->get_error_message()
            )
        ];
    }

    if (empty($themes)) {
        $themes = [__('Unknown theme', 'iv1-wp-tools')];
    }

    foreach ($themes as $theme) {
        iv1wpt_activity_log(
            'theme_' . $action,
            sprintf(
                /* translators: 1: action, 2: theme slug/name */
                __('Theme %1$s: %2$s', 'iv1-wp-tools'),
                $action,
                $theme
            ),
            'theme',
            $theme
        );
    }

}, 10, 2);

/**
 * Plugin gelöscht
 */
add_action('deleted_plugin', function(string $plugin, bool $deleted): void {
    if (!$deleted) {
        return;
    }

    iv1wpt_activity_log(
        'plugin_deleted',
        sprintf(
            /* translators: %s: plugin path */
            __('Plugin deleted: %s', 'iv1-wp-tools'),
            $plugin
        ),
        'plugin',
        $plugin
    );
}, 10, 2);

/**
 * Theme gelöscht
 */
add_action('delete_site_transient_update_themes', function(): void {
    // Wird oft nach Theme-Änderungen/Deletes ausgelöst, aber nicht eindeutig genug.
});