<?php
/**
 * SecurityEventsTable — standalone class file.
 *
 * @package UltraguardPro\modules\db_tables\db
 */

namespace UltraguardPro\modules\db_tables\db;

use UltraguardPro\db\BaseTable;

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

/**
 * SecurityEventsTable — real-time security event stream.
 * @package UltraguardPro\modules\db_tables\db
 */
class SecurityEventsTable extends BaseTable {

    protected $table_name  = 'ultraguard_security_events';
    protected $cache_group = 'ultraguard_security_events';

    public function get_defaults(): array {
        return [
            'id'         => 0,
            'event_type' => '',
            'severity'   => 'info',
            'ip_address' => '',
            'user_id'    => null,
            'details'    => null,
            'module'     => null,
            'created_at' => '',
        ];
    }

    protected function validate_data( $data ) {
        if ( empty( $data['event_type'] ) ) {
            return false;
        }
        return $data;
    }

    protected function sanitize_data( $data ): array {
        $out = [];
        foreach ( $data as $k => $v ) {
            $out[ $k ] = match ( $k ) {
                'details' => ( is_array( $v ) ? wp_json_encode( $v ) : (string) $v ),
                'user_id' => $v === null ? null : absint( $v ),
                default   => is_string( $v ) ? sanitize_text_field( $v ) : $v,
            };
        }
        return $out;
    }

    public function emit( string $event_type, string $severity = 'info', string $module = '',
                          $details = null ): int|false {
        return $this->insert( [
            'event_type' => $event_type,
            'severity'   => $severity,
            'ip_address' => \UltraguardPro\core\Utils::get_client_ip() ?: '',
            'user_id'    => get_current_user_id() ?: null,
            'module'     => $module,
            'details'    => $details,
        ] );
    }

    public function get_recent_events( int $limit = 100, string $module = '' ): array {
        $conds = $module ? [ 'module' => $module ] : [];
        return $this->get_recent( $limit, 'created_at', $conds );
    }

    protected function get_searchable_fields(): array {
        return [ 'event_type', 'ip_address', 'module' ];
    }
}
