<?php
/**
 * Admin view: registration attempts stopped by the bot shield.
 *
 * @package auctionforge
 */

if (!defined('ABSPATH')) {
    die('You shouldnt be here');
}
if (!current_user_can('manage_options')) {
    wp_die(esc_html__('You do not have permission to view this page.', 'auctionforge'));
}

global $wpdb;
$table = auctionforge_botshield_table_name();

if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table)) !== $table) {
    auctionforge_botshield_create_table();
}

$reasonFilter = isset($_GET['reason']) ? sanitize_text_field(wp_unslash($_GET['reason'])) : '';
$perPage      = 100;
$paged        = max(1, intval($_GET['paged'] ?? 1));
$offset       = ($paged - 1) * $perPage;

$where  = '1=1';
$params = array();
if ($reasonFilter !== '') {
    $where   .= ' AND rejection_reason = %s';
    $params[] = $reasonFilter;
}

$totalSql = "SELECT COUNT(*) FROM `$table` WHERE $where";
$total    = (int) ($params ? $wpdb->get_var($wpdb->prepare($totalSql, $params)) : $wpdb->get_var($totalSql));

$rowsSql = "SELECT * FROM `$table` WHERE $where ORDER BY created_at DESC LIMIT %d OFFSET %d";
$rows    = $wpdb->get_results($wpdb->prepare($rowsSql, array_merge($params, array($perPage, $offset))), ARRAY_A);

$summary = $wpdb->get_results(
    "SELECT rejection_reason, COUNT(*) AS n
       FROM `$table`
      WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
      GROUP BY rejection_reason
      ORDER BY n DESC",
    ARRAY_A
);
$last24 = (int) $wpdb->get_var(
    "SELECT COUNT(*) FROM `$table` WHERE created_at >= DATE_SUB(NOW(), INTERVAL 1 DAY)"
);

$reasonLabels = array(
    'name_validation' => __('Machine-generated name', 'auctionforge'),
    'email_pattern'   => __('Suspicious email pattern', 'auctionforge'),
    'honeypot'        => __('Honeypot field filled', 'auctionforge'),
    'rate_limit'      => __('Rate limit exceeded', 'auctionforge'),
    'user_agent'      => __('Automated client', 'auctionforge'),
    'form_timing'     => __('Form filled too fast', 'auctionforge'),
    'combined_score'  => __('Combined signals', 'auctionforge'),
);
$labelFor = function ($reason) use ($reasonLabels) {
    return isset($reasonLabels[$reason]) ? $reasonLabels[$reason] : ($reason ?: '—');
};

$baseUrl = admin_url('edit.php?post_type=lot&page=auctionforge-blocked-signups');
?>
<div class="wrap">
    <h1><?php esc_html_e('Blocked Signups', 'auctionforge'); ?></h1>

    <p class="description">
        <?php esc_html_e('Registration attempts the bot shield stopped before they reached BidSpirit. Blocked visitors are shown a normal confirmation message, so an attacker cannot tell a block from an acceptance.', 'auctionforge'); ?>
    </p>

    <div class="notice notice-info inline" style="margin:12px 0;padding:10px 12px;">
        <strong><?php echo esc_html(sprintf(
            /* translators: %d: number of blocked attempts */
            _n('%d attempt blocked in the last 24 hours.', '%d attempts blocked in the last 24 hours.', $last24, 'auctionforge'),
            $last24
        )); ?></strong>
        <?php if ($summary) : ?>
            <span style="margin-left:8px;"><?php esc_html_e('Last 7 days:', 'auctionforge'); ?></span>
            <?php foreach ($summary as $s) : ?>
                <span style="margin-left:8px;">
                    <?php echo esc_html($labelFor($s['rejection_reason'])); ?>
                    <code><?php echo esc_html($s['n']); ?></code>
                </span>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <ul class="subsubsub">
        <li>
            <a href="<?php echo esc_url($baseUrl); ?>" class="<?php echo $reasonFilter === '' ? 'current' : ''; ?>">
                <?php esc_html_e('All', 'auctionforge'); ?>
            </a>
        </li>
        <?php foreach ($reasonLabels as $key => $label) : ?>
            <li> |
                <a href="<?php echo esc_url(add_query_arg('reason', $key, $baseUrl)); ?>"
                   class="<?php echo $reasonFilter === $key ? 'current' : ''; ?>">
                    <?php echo esc_html($label); ?>
                </a>
            </li>
        <?php endforeach; ?>
    </ul>

    <table class="wp-list-table widefat fixed striped" style="margin-top:12px;">
        <thead>
            <tr>
                <th style="width:140px;"><?php esc_html_e('When', 'auctionforge'); ?></th>
                <th style="width:180px;"><?php esc_html_e('Name given', 'auctionforge'); ?></th>
                <th style="width:220px;"><?php esc_html_e('Email', 'auctionforge'); ?></th>
                <th style="width:130px;"><?php esc_html_e('IP', 'auctionforge'); ?></th>
                <th style="width:160px;"><?php esc_html_e('Reason', 'auctionforge'); ?></th>
                <th style="width:60px;"><?php esc_html_e('Score', 'auctionforge'); ?></th>
                <th><?php esc_html_e('Signals', 'auctionforge'); ?></th>
            </tr>
        </thead>
        <tbody>
        <?php if (!$rows) : ?>
            <tr><td colspan="7"><?php esc_html_e('Nothing blocked yet.', 'auctionforge'); ?></td></tr>
        <?php else : foreach ($rows as $row) : ?>
            <tr>
                <td><?php echo esc_html(mysql2date('Y-m-d H:i', $row['created_at'])); ?></td>
                <td><?php echo esc_html(trim($row['first_name'] . ' ' . $row['last_name'])); ?></td>
                <td>
                    <?php echo esc_html($row['email']); ?>
                    <?php if (!empty($row['email_normalized']) && $row['email_normalized'] !== strtolower($row['email'])) : ?>
                        <br><small style="color:#666;">
                            <?php esc_html_e('same inbox as', 'auctionforge'); ?>
                            <?php echo esc_html($row['email_normalized']); ?>
                        </small>
                    <?php endif; ?>
                </td>
                <td><?php echo esc_html($row['ip_address']); ?></td>
                <td><?php echo esc_html($labelFor($row['rejection_reason'])); ?></td>
                <td><?php echo esc_html($row['score']); ?></td>
                <td><small><?php echo esc_html($row['rejection_details']); ?></small></td>
            </tr>
        <?php endforeach; endif; ?>
        </tbody>
    </table>

    <?php
    $totalPages = (int) ceil($total / $perPage);
    if ($totalPages > 1) :
        echo '<div class="tablenav"><div class="tablenav-pages">';
        echo wp_kses_post(paginate_links(array(
            'base'      => add_query_arg('paged', '%#%', $reasonFilter !== '' ? add_query_arg('reason', $reasonFilter, $baseUrl) : $baseUrl),
            'format'    => '',
            'current'   => $paged,
            'total'     => $totalPages,
        )));
        echo '</div></div>';
    endif;
    ?>
</div>
