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

namespace UltraguardPro\modules\db_tables\db;

use UltraguardPro\db\BaseTable;

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

namespace UltraguardPro\modules\db_tables\db;

use UltraguardPro\db\BaseTable;

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

class SecurityAlertsTable extends BaseTable {

    protected $table_name  = 'ultraguard_security_alerts';
    protected $cache_group = 'ultraguard_security_alerts';

    public function get_defaults(): array {
        return [
            'id'          => 0,
            'alert_type'  => '',
            'severity'    => 'medium',
            'title'       => '',
            'message'     => '',
            'is_read'     => 0,
            'resolved'    => 0,
            'resolved_by' => null,
            'module'      => null,
            'created_at'  => '',
            'updated_at'  => '',
        ];
    }

    protected function validate_data( $data ) {
        if ( empty( $data['alert_type'] ) || empty( $data['title'] ) || empty( $data['message'] ) ) {
            return false;
        }
        return $data;
    }

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

    public function raise( string $alert_type, string $title, string $message,
                           string $severity = 'medium', string $module = '' ): int|false {
        return $this->insert( [
            'alert_type' => $alert_type,
            'title'      => $title,
            'message'    => $message,
            'severity'   => $severity,
            'module'     => $module,
        ] );
    }

    public function mark_read( int $id ): bool {
        return $this->update( $id, [ 'is_read' => 1 ] );
    }

    public function mark_resolved( int $id ): bool {
        return $this->update( $id, [
            'resolved'    => 1,
            'resolved_by' => get_current_user_id() ?: null,
        ] );
    }

    public function get_unread( int $limit = 50 ): array {
        return $this->get_by( [ 'is_read' => 0, 'resolved' => 0 ], $limit );
    }

    public function get_unread_count(): int {
        return $this->count( [ 'is_read' => 0, 'resolved' => 0 ] );
    }

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

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

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