<?php
/**
 * AuditLogsTable — admin action audit trail.
 * @package UltraguardPro\modules\db_tables\db
 */

namespace UltraguardPro\modules\db_tables\db;

use UltraguardPro\db\BaseTable;

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

class AuditLogsTable extends BaseTable {

    protected $table_name  = 'ultraguard_audit_logs';
    protected $cache_group = 'ultraguard_audit_logs';

    public function get_defaults(): array {
        return [
            'id'          => 0,
            'action'      => '',
            'entity_type' => '',
            'entity_id'   => null,
            'user_id'     => null,
            'ip_address'  => '',
            'old_values'  => null,
            'new_values'  => null,
            'created_at'  => '',
        ];
    }

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

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

    /**
     * Record an admin audit event.
     */
    public function record( string $action, string $entity_type, $entity_id = null,
                            $old_values = null, $new_values = null ): int|false {
        return $this->insert( [
            'action'      => $action,
            'entity_type' => $entity_type,
            'entity_id'   => $entity_id,
            'user_id'     => get_current_user_id() ?: null,
            'ip_address'  => \UltraguardPro\core\Utils::get_client_ip() ?: '',
            'old_values'  => $old_values,
            'new_values'  => $new_values,
        ] );
    }

    public function get_by_entity( string $entity_type, $entity_id = null, int $limit = 100 ): array {
        $conds = [ 'entity_type' => $entity_type ];
        if ( $entity_id !== null ) {
            $conds['entity_id'] = (string) $entity_id;
        }
        return $this->get_by( $conds, $limit );
    }

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