<?php
/**
 * Activity log integration helper.
 *
 * @package Polanger_Shield
 */

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

class Polanger_Shield_Activity {

  /**
   * Per-request cache for whether activity integration is enabled.
   *
   * @var bool|null
   */
  private static $enabled_cache = null;

  /**
   * Emit an activity log event if integration is enabled.
   *
   * @param string $action Action name.
   * @param array  $payload Optional payload.
   * @return void
   */
  public static function log( $action, $payload = array() ) {
    if ( ! self::is_enabled() ) {
      return;
    }

    $action = sanitize_key( $action );
    if ( '' === $action ) {
      return;
    }

    $event = wp_parse_args(
      $payload,
      array(
        'action'      => $action,
        'object_type' => 'shield',
        'object_id'   => 0,
        'object_name' => '',
        'meta'        => array(),
      )
    );

    $event['action'] = $action;
    do_action( 'pdt_log_activity', $event );
  }

  /**
   * Log block event with throttling.
   *
   * @param int   $rule_id Rule ID.
   * @param int   $user_id User ID.
   * @param array $meta Meta.
   * @return void
   */
  public static function log_page_blocked( $rule_id, $user_id, $meta = array() ) {
    if ( ! self::is_enabled() ) {
      return;
    }

    $rule_id = absint( $rule_id );
    $user_id = absint( $user_id );
    if ( ! $rule_id || ! $user_id ) {
      return;
    }

    $transient_key = 'psh_blk_' . md5( $rule_id . ':' . $user_id );
    if ( get_transient( $transient_key ) ) {
      return;
    }

    set_transient( $transient_key, 1, 10 * MINUTE_IN_SECONDS );

    self::log(
      'shield_page_blocked',
      array(
        'object_type' => 'shield_rule',
        'object_id'   => $rule_id,
        'meta'        => $meta,
      )
    );
  }

  /**
   * Whether Shield->Activity integration is active.
   *
   * @return bool
   */
  public static function is_enabled() {
    if ( null !== self::$enabled_cache ) {
      return self::$enabled_cache;
    }

    if ( ! function_exists( 'pdt_is_addon_active' ) || ! pdt_is_addon_active( 'admin-activity-log' ) ) {
      self::$enabled_cache = false;
      return self::$enabled_cache;
    }

    $activity_settings = get_option( 'pdt_activity_log_settings', array() );
    if ( empty( $activity_settings['enabled'] ) ) {
      self::$enabled_cache = false;
      return self::$enabled_cache;
    }

    $shield_settings = Polanger_Shield_Settings::instance()->get_settings();
    self::$enabled_cache = ! empty( $shield_settings['enable_activity_log'] );

    return self::$enabled_cache;
  }
}
