<?php
/**
 * Bridges plugin lifecycle hooks into the audit log so each release
 * does not need to know the table schema.
 *
 * @package KaizenCoders\MagicLink\AuditLog
 */

namespace KaizenCoders\MagicLink\AuditLog;

class EventCapture {

	/**
	 * Wire the listeners.
	 *
	 * @return void
	 */
	public function init() {
		add_action( 'kc_ml_link_generated', array( $this, 'on_generated' ), 10, 2 );
		add_action( 'kc_ml_link_opened', array( $this, 'on_opened' ), 10, 2 );
		add_action( 'kc_ml_login_link_sent', array( $this, 'on_sent' ), 10, 2 );
		add_action( 'magic_link_before_login', array( $this, 'on_used' ), 10, 2 );
		add_action( 'kc_ml_invalid_user', array( $this, 'on_failed_user' ) );
		add_action( 'kc_ml_invalid_token', array( $this, 'on_failed_token' ) );
		add_action( 'kc_ml_user_tokens_revoked', array( $this, 'on_revoked' ), 10, 2 );
	}

	public function on_generated( $user_id = 0, $context = array() ) {
		Logger::record( Events::GENERATED, array_merge(
			array( 'user_id' => (int) $user_id ),
			(array) $context
		) );
	}

	public function on_opened( $user_id = 0, $context = array() ) {
		Logger::record( Events::OPENED, array_merge(
			array( 'user_id' => (int) $user_id ),
			(array) $context
		) );
	}

	public function on_sent( $user_id = 0, $context = array() ) {
		Logger::record( Events::SENT, array_merge(
			array( 'user_id' => (int) $user_id ),
			(array) $context
		) );
	}

	public function on_used( $user = null, $context = array() ) {
		$uid = ( is_object( $user ) && isset( $user->ID ) ) ? (int) $user->ID : 0;
		$email = ( is_object( $user ) && isset( $user->user_email ) ) ? (string) $user->user_email : '';

		Logger::record( Events::USED, array_merge(
			array( 'user_id' => $uid, 'email' => $email ),
			(array) $context
		) );
	}

	public function on_failed_user() {
		Logger::record( Events::FAILED, array( 'meta' => array( 'reason' => 'invalid_user' ) ) );
	}

	public function on_failed_token() {
		Logger::record( Events::FAILED, array( 'meta' => array( 'reason' => 'invalid_token' ) ) );
	}

	public function on_revoked( $user_id = 0, $count = 0 ) {
		Logger::record( Events::REVOKED, array(
			'user_id' => (int) $user_id,
			'meta'    => array( 'count' => (int) $count ),
		) );
	}
}
