<?php
/**
 * UserActivityTable — User login/logout/profile-change audit log.
 *
 * @package UltraguardPro\modules\loginlimiter\db
 * @since   6.5.0
 */

namespace UltraguardPro\modules\loginlimiter\db;

use UltraguardPro\db\BaseTable;
use UltraguardPro\core\Utils;

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

class UserActivityTable extends BaseTable {

    protected $table_name  = 'ultraguard_user_activity';
    protected $cache_group = 'ultraguard_user_activity';

    public function get_defaults(): array {
        return [
            'id'            => 0,
            'user_id'       => 0,
            'activity_type' => '',
            'description'   => null,
            'ip_address'    => null,
            'user_agent'    => null,
            'object_type'   => null,
            'object_id'     => null,
            'created_at'    => '',
        ];
    }

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

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

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

    // ── Domain methods ─────────────────────────────────────────────────────────

    /**
     * Record a single activity event.
     *
     * @param  int         $user_id
     * @param  string      $type         e.g. 'login', 'logout', 'profile_update'
     * @param  string      $description  Human-readable note.
     * @param  array|null  $object       Optional [ 'type' => ..., 'id' => ... ]
     * @return int|false
     */
    public function record( int $user_id, string $type, string $description = '', ?array $object = null ): int|false {
        return $this->insert( [
            'user_id'       => $user_id,
            'activity_type' => $type,
            'description'   => $description,
            'ip_address'    => Utils::get_client_ip(),
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- User agent is unslashed, length-limited, and sanitized immediately.
            'user_agent'    => sanitize_text_field( substr( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ?? '' ), 0, 500 ) ),
            'object_type'   => $object['type'] ?? null,
            'object_id'     => isset( $object['id'] ) ? absint( $object['id'] ) : null,
        ] );
    }

    /**
     * Get recent activity for a specific user.
     *
     * @param  int $user_id
     * @param  int $limit
     * @return array
     */
    public function get_for_user( int $user_id, int $limit = 50 ): array {
        return $this->get_by( [ 'user_id' => $user_id ], $limit, 'created_at', 'DESC' );
    }
}
