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

namespace UltraguardPro\modules\firewall\db;

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

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

class BlockedRequestsTable extends BaseTable {

    protected $table_name  = 'ultraguard_blocked_requests';
    protected $cache_group = 'ultraguard_blocked_requests';

    public function get_defaults(): array {
        return [
            'id'             => 0,
            'ip_address'     => '',
            'request_method' => 'GET',
            'request_uri'    => '',
            'user_agent'     => null,
            'block_reason'   => '',
            'rule_id'        => null,
            'threat_level'   => 'medium',
            'country_code'   => null,
            'user_id'        => null,
            'created_at'     => '',
        ];
    }

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

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

    public function record_block( string $ip, string $uri, string $reason, string $threat = 'medium',
                                   ?int $rule_id = null ): int|false {
        return $this->insert( [
            'ip_address'     => $ip,
            'request_method' => sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ?? 'GET' ) ),
            'request_uri'    => $uri,
            'user_agent'     => sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ?? '' ) ),
            'block_reason'   => $reason,
            'rule_id'        => $rule_id,
            'threat_level'   => $threat,
            'user_id'        => get_current_user_id() ?: null,
        ] );
    }

    public function get_top_blocked_ips( int $limit = 10, int $since_hours = 24 ): array {
        $results = $this->get_top_records( 'ip_address', 'id', 'COUNT', $limit, [
            'created_at >=' => gmdate( 'Y-m-d H:i:s', strtotime( "-{$since_hours} hours" ) ),
        ] );

        return is_array( $results['raw'] ?? null ) ? $results['raw'] : [];
    }

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

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