<?php
/**
 * IpWhitelistTable — 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 IpWhitelistTable extends BaseTable {

    protected $table_name  = 'ultraguard_ip_whitelist';
    protected $cache_group = 'ultraguard_ip_whitelist';

    public function get_defaults(): array {
        return [
            'id'         => 0,
            'ip_address' => '',
            'ip_range'   => null,
            'label'      => '',
            'is_active'  => 1,
            'added_by'   => null,
            'created_at' => '',
            'updated_at' => '',
        ];
    }

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

    protected function sanitize_data( $data ): array {
        $out = [];
        foreach ( $data as $k => $v ) {
            $out[ $k ] = match ( $k ) {
                'is_active' => (int) (bool) $v,
                'added_by'  => $v === null ? null : absint( $v ),
                default     => is_string( $v ) ? sanitize_text_field( $v ) : $v,
            };
        }
        return $out;
    }

    public function is_whitelisted( string $ip ): bool {
        $record = $this->get_by_field( 'ip_address', $ip );
        return $record && ! empty( $record['is_active'] );
    }

    public function add_ip( string $ip, string $label = '' ): int|false {
        if ( $this->exists( [ 'ip_address' => $ip ] ) ) { return false; }
        return $this->insert( [
            'ip_address' => $ip,
            'label'      => $label,
            'added_by'   => get_current_user_id() ?: null,
        ] );
    }

    public function get_active( int $limit = 500 ): array {
        return $this->get_by( [ 'is_active' => 1 ], $limit );
    }

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

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