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

add_action('wp_ajax_iv1wpt_activity_load', 'iv1wpt_activity_load_ajax');
function iv1wpt_activity_load_ajax(): void {
    check_ajax_referer('iv1wpt_ajax');

    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    global $wpdb;

    $limit = isset($_POST['limit']) ? absint($_POST['limit']) : 100;

    $allowed_limits = [25, 50, 100, 250, 500];

    if (!in_array($limit, $allowed_limits, true)) {
        $limit = 100;
    }

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

    $logs = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT id, created_at, user_id, user_login, event_type, object_type, object_name, message, ip_address
             FROM {$table_name}
             ORDER BY created_at DESC
             LIMIT %d",
            $limit
        ),
        ARRAY_A
    );

    if (empty($logs)) {
        wp_send_json_success([
            'html' => '<div class="notice notice-info inline"><p>' .
                esc_html__('No activity entries found.', 'iv1-wp-tools') .
                '</p></div>',
        ]);
    }

    ob_start();
    ?>
    <table class="widefat striped">
        <thead>
            <tr>
                <th><?php esc_html_e('Date', 'iv1-wp-tools'); ?></th>
                <th><?php esc_html_e('User', 'iv1-wp-tools'); ?></th>
                <th><?php esc_html_e('Event', 'iv1-wp-tools'); ?></th>
                <th><?php esc_html_e('Object', 'iv1-wp-tools'); ?></th>
                <th><?php esc_html_e('Message', 'iv1-wp-tools'); ?></th>
                <th><?php esc_html_e('IP address', 'iv1-wp-tools'); ?></th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($logs as $log) : ?>
                <tr>
                    <td><?php echo esc_html(wp_date('d.m.Y H:i:s', strtotime($log['created_at']))); ?></td>
                    <td><?php echo esc_html($log['user_login'] ?: '—'); ?></td>
                    <td><code><?php echo esc_html($log['event_type']); ?></code></td>
                    <td>
                        <?php
                        $object = trim(($log['object_type'] ?? '') . ': ' . ($log['object_name'] ?? ''), ': ');
                        echo esc_html($object ?: '—');
                        ?>
                    </td>
                    <td><?php echo esc_html($log['message']); ?></td>
                    <td><?php echo esc_html($log['ip_address'] ?: '—'); ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php

    wp_send_json_success([
        'html'  => ob_get_clean(),
        'count' => count($logs),
    ]);
}

add_action('wp_ajax_iv1wpt_activity_clear', 'iv1wpt_activity_clear_ajax');
function iv1wpt_activity_clear_ajax(): void {
    check_ajax_referer('iv1wpt_ajax');

    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    global $wpdb;

    $table_name = $wpdb->prefix . 'iv1_activity_log';
    $wpdb->query("TRUNCATE TABLE {$table_name}");

    iv1wpt_activity_log(
        'activity_log_cleared',
        __('Activity log cleared.', 'iv1-wp-tools'),
        'activity_log',
        'iv1_activity_log'
    );

    wp_send_json_success([
        'message' => __('Activity log cleared.', 'iv1-wp-tools'),
    ]);
}