<?php
/**
 * Logs tab — recent events table with filters, pagination, quick-block.
 *
 * @package Brainwerk Security Suite
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

$filter_event = isset( $_GET['event'] ) ? sanitize_key( wp_unslash( $_GET['event'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
$filter_ip    = isset( $_GET['ip'] ) ? sanitize_text_field( wp_unslash( $_GET['ip'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
$paged        = max( 1, isset( $_GET['paged'] ) ? (int) $_GET['paged'] : 1 ); // phpcs:ignore WordPress.Security.NonceVerification
$per_page     = 50;
$offset       = ( $paged - 1 ) * $per_page;

$filters = array();
if ( $filter_event ) $filters['event_type'] = $filter_event;
if ( $filter_ip )    $filters['ip']         = $filter_ip;

$rows = Shieldforge_Logger::recent( $filters, $per_page, $offset );

global $wpdb;
$count_table = Shieldforge_Utils::table( 'log' );
$where  = array( '1=1' );
$params = array();
if ( $filter_event ) { $where[] = 'event_type = %s'; $params[] = $filter_event; }
if ( $filter_ip )    { $where[] = 'ip = %s';         $params[] = $filter_ip; }
$count_sql = "SELECT COUNT(*) FROM {$count_table} WHERE " . implode( ' AND ', $where );
$total     = (int) ( $params
    ? $wpdb->get_var( $wpdb->prepare( $count_sql, $params ) ) // phpcs:ignore WordPress.DB.PreparedSQL, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- custom security table; direct live read by design; not cacheable.
    : $wpdb->get_var( $count_sql ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- custom security table; direct live read by design; not cacheable.
$total_pages = max( 1, (int) ceil( $total / $per_page ) );
?>
<div class="shieldforge-card">
    <h2><?php esc_html_e( 'Event log', 'brainwerk-security-suite' ); ?></h2>

    <form method="get" class="shieldforge-filter">
        <input type="hidden" name="page" value="<?php echo esc_attr( Shieldforge_Admin::MENU_SLUG ); ?>">
        <input type="hidden" name="tab" value="logs">
        <label>
            <?php esc_html_e( 'Event type', 'brainwerk-security-suite' ); ?>
            <input type="text" name="event" value="<?php echo esc_attr( $filter_event ); ?>" placeholder="login_failure">
        </label>
        <label>
            <?php esc_html_e( 'IP', 'brainwerk-security-suite' ); ?>
            <input type="text" name="ip" value="<?php echo esc_attr( $filter_ip ); ?>">
        </label>
        <button type="submit" class="button"><?php esc_html_e( 'Filter', 'brainwerk-security-suite' ); ?></button>
        <a href="<?php echo esc_url( Shieldforge_Admin::tab_url( 'logs' ) ); ?>" class="button-link"><?php esc_html_e( 'Reset', 'brainwerk-security-suite' ); ?></a>
        <span class="sf-result-count">
            <?php
            printf(
                esc_html__( '%1$s entries · page %2$s of %3$s', 'brainwerk-security-suite' ),
                '<strong>' . esc_html( number_format_i18n( $total ) ) . '</strong>',
                esc_html( number_format_i18n( $paged ) ),
                esc_html( number_format_i18n( $total_pages ) )
            );
            ?>
        </span>
    </form>

    <?php if ( empty( $rows ) ) : ?>
        <p class="muted"><?php esc_html_e( 'No events match the current filters.', 'brainwerk-security-suite' ); ?></p>
    <?php else : ?>
        <table class="widefat striped">
            <thead>
                <tr>
                    <th><?php esc_html_e( 'When (UTC)', 'brainwerk-security-suite' ); ?></th>
                    <th><?php esc_html_e( 'Event', 'brainwerk-security-suite' ); ?></th>
                    <th><?php esc_html_e( 'Sev.', 'brainwerk-security-suite' ); ?></th>
                    <th><?php esc_html_e( 'IP', 'brainwerk-security-suite' ); ?></th>
                    <th><?php esc_html_e( 'User', 'brainwerk-security-suite' ); ?></th>
                    <th><?php esc_html_e( 'Request', 'brainwerk-security-suite' ); ?></th>
                    <th><?php esc_html_e( 'Action', 'brainwerk-security-suite' ); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ( $rows as $row ) : ?>
                    <tr>
                        <td><?php echo esc_html( $row->created_at ); ?></td>
                        <td><code><?php echo esc_html( $row->event_type ); ?></code></td>
                        <td>
                            <span class="sf-sev sf-sev-<?php echo esc_attr( (int) $row->severity ); ?>"><?php echo (int) $row->severity; ?></span>
                        </td>
                        <td><code><?php echo esc_html( $row->ip ?: '—' ); ?></code></td>
                        <td><?php echo esc_html( $row->username ?: '—' ); ?></td>
                        <td class="muted"><?php echo esc_html( mb_strimwidth( (string) $row->request_uri, 0, 60, '…' ) ); ?></td>
                        <td>
                            <?php if ( $row->ip && filter_var( $row->ip, FILTER_VALIDATE_IP ) ) : ?>
                                <button class="button button-small sf-quick-block" data-ip="<?php echo esc_attr( $row->ip ); ?>" data-minutes="60">
                                    <?php esc_html_e( 'Block 60m', 'brainwerk-security-suite' ); ?>
                                </button>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <?php if ( $total_pages > 1 ) :
            $base_url = add_query_arg(
                array_filter( array( 'event' => $filter_event, 'ip' => $filter_ip ) ),
                Shieldforge_Admin::tab_url( 'logs' )
            );
            $links = paginate_links( array(
                'base'      => add_query_arg( 'paged', '%#%', $base_url ),
                'format'    => '',
                'current'   => $paged,
                'total'     => $total_pages,
                'prev_text' => __( '« Prev', 'brainwerk-security-suite' ),
                'next_text' => __( 'Next »', 'brainwerk-security-suite' ),
                'type'      => 'plain',
            ) );
            ?>
            <div class="tablenav"><div class="tablenav-pages"><?php echo wp_kses_post( $links ); ?></div></div>
        <?php endif; ?>
    <?php endif; ?>
</div>
