<?php
/**
 * SecurityLogsTable — infrastructure table for general security events.
 *
 * @package UltraguardPro\modules\db_tables\db
 */

namespace UltraguardPro\modules\db_tables\db;

use UltraguardPro\db\BaseTable;

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

class SecurityLogsTable extends BaseTable {

    protected $table_name  = 'ultraguard_security_logs';
    protected $cache_group = 'ultraguard_security_logs';

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

    protected function validate_data( $data ) {
        if ( empty( $data['event_type'] ) || empty( $data['message'] ) ) {
            return false;
        }
        $valid_severities = [ 'debug', 'info', 'low', 'medium', 'high', 'critical' ];
        if ( isset( $data['severity'] ) && ! in_array( $data['severity'], $valid_severities, true ) ) {
            $data['severity'] = 'info';
        }
        return $data;
    }

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

    // ── Domain-specific methods ───────────────────────────────────────────────

    /**
     * Log a security event — convenience wrapper around insert().
     * Named log_event() (not log()) to avoid a signature conflict with
     * BaseTable::log($message, $level) which is an internal debug helper.
     */
    public function log_event( string $event_type, string $message, string $severity = 'info',
                         ?string $ip = null, ?int $user_id = null, ?string $module = null,
                         $context = null ): int|false {
        return $this->insert( [
            'event_type' => $event_type,
            'message'    => $message,
            'severity'   => $severity,
            'ip_address' => $ip ?? ( \UltraguardPro\core\Utils::get_client_ip() ?: '' ),
            'user_id'    => $user_id ?? ( get_current_user_id() ?: null ),
            'module'     => $module,
            'context'    => $context ? wp_json_encode( $context ) : null,
        ] );
    }

    public function get_by_module( string $module, int $limit = 100 ): array {
        return $this->get_by( [ 'module' => $module ], $limit );
    }

    public function get_critical_logs( int $limit = 50 ): array {
        return $this->get_by( [ 'severity' => 'critical' ], $limit );
    }

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