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

namespace UltraguardPro\modules\firewall\db;

use UltraguardPro\db\BaseTable;
use UltraguardPro\core\DataCodec;
use UltraguardPro\core\DatabaseCrud;

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

class AttackPatternsTable extends BaseTable {

    protected $table_name  = 'ultraguard_attack_patterns';
    protected $cache_group = 'ultraguard_attack_patterns';

    public function get_defaults(): array {
        return [
            'id'              => 0,
            'pattern_name'    => '',
            'pattern_type'    => 'regex',
            'pattern_value'   => '',
            'attack_category' => '',
            'severity'        => 'medium',
            'is_active'       => 1,
            'match_count'     => 0,
            'created_at'      => '',
            'updated_at'      => '',
        ];
    }

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

    protected function sanitize_data( $data ): array {
        $out = [];
        foreach ( $data as $k => $v ) {
            $out[ $k ] = match ( $k ) {
                // pattern_value is a regex — must not go through sanitize_textarea_field()
                'pattern_value' => AttackPatternsTable::sanitize_regex_pattern( (string) $v ),
                'match_count'   => absint( $v ),
                'is_active'     => (int) (bool) $v,
                default         => is_string( $v ) ? sanitize_text_field( $v ) : $v,
            };
        }
        return $out;
    }

    /** @deprecated Use BaseTable::sanitize_regex_pattern() directly. */
    public static function sanitize_regex_pattern( string $v ): string {
        return parent::sanitize_regex_pattern( $v );
    }

    public function get_active_patterns( string $category = '' ): array {
        $conds = [ 'is_active' => 1 ];
        if ( $category ) { $conds['attack_category'] = $category; }
        return $this->get_by( $conds, 2000 );
    }

    public function increment_match( int $id ): bool {
        return $this->increment_field( 'match_count', [ 'id' => $id ] );
    }

    // ── DataCodec integration ───────────────────────────────────────────────────

    /**
     * 'pattern_value' stores raw regex strings (e.g. /union\s+select/i) that
     * are corrupted by wp_strip_all_tags().
     *
     * @return string[]
     */
    protected function get_codec_fields(): array {
        return [ 'pattern_value' ];
    }

    protected function get_searchable_fields(): array {
        return [ 'pattern_name', 'attack_category', 'pattern_type' ];
    }
}

// ─────────────────────────────────────────────────────────────────────────────
