<?php
/**
 * Trait for unified logging across the plugin.
 *
 * @package automation-web-platform
 */

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

trait WAWP_Logging_Trait {

	/**
	 * Log a system event or message.
	 *
	 * @param string $status     'success', 'error', 'failed', 'info'.
	 * @param string $message    The log message.
	 * @param array  $data       Extra data to store (context).
	 * @param string $gateway    'system', 'whatsapp', 'email', etc.
	 * @param int    $user_id    Optional user ID.
	 * @param mixed  $related_id Optional related entity ID (e.g., order ID).
	 * @return void
	 */
	protected function log_action( $status, $message, $data = array(), $gateway = 'system', $user_id = 0, $related_id = null ) {
		if ( ! function_exists( 'wawp_log_message' ) ) {
			return;
		}

		$uid = $user_id ? $user_id : get_current_user_id();

		// Determine a better event type if General is passed.
		$event_type = $data['event_type'] ?? 'General';
		if ( 'General' === $event_type ) {
			if ( ! empty( $data['context'] ) ) {
				$event_type = $data['context'];
			} elseif ( ! empty( $data['type'] ) ) {
				$event_type = ucfirst( $data['type'] );
			} else {
				$event_type = ucfirst( $gateway );
			}
		}

		// Delegate to the unified helper.
		wawp_log_message(
			$data['phone'] ?? $data['recipient'] ?? $data['whatsapp_number'] ?? $data['email'] ?? '',
			$message,
			$event_type,
			$data,
			$uid,
			$gateway,
			$related_id,
			$status
		);
	}

	/**
	 * Log an authentication event.
	 *
	 * @param int    $user_id User ID.
	 * @param string $type    Event type.
	 * @param string $method  Auth method.
	 * @param string $status  Status.
	 * @param array  $meta    Additional meta data.
	 */
	protected function log_auth( $user_id, $type = 'login', $method = 'otp', $status = 'success', $meta = array() ) {
		if ( WAWP()->unified_log ) {
			WAWP()->unified_log->log_auth( $user_id, $type, $method, $status, $meta );
		}
	}

	/**
	 * Log a generic event.
	 *
	 * @param string $type       Event type.
	 * @param string $gateway    Gateway.
	 * @param string $status     Status.
	 * @param array  $details    Details.
	 * @param int    $user_id    User ID.
	 * @param mixed  $related_id Related ID.
	 */
	protected function log_event( $type, $gateway, $status, $details = array(), $user_id = null, $related_id = null ) {
		if ( WAWP()->unified_log ) {
			WAWP()->unified_log->log_event( $type, $gateway, $status, $details, $user_id, $related_id );
		}
	}
}
