<?php

namespace Emoxie\Expandable_Paywall;

class Logger {

	/**
	 * @var mixed|string
	 */
	private static $table_name = 'expandable_paywall_log';


	public static function enable_logging() {
		return get_option( EXPANDABLE_PAYWALL_SLUG . '_enable_debug', false );
	}


	public static function log( $action, $data, $post_id = 0, $user_id = 0 ) {

		if ( ! self::enable_logging() ) {
			return;
		}

		global $wpdb;
		$table_name = $wpdb->prefix . self::$table_name;

		$action = sanitize_key( $action );
		$data   = sanitize_textarea_field( print_r( $data, true ) );

		$user_agent = sanitize_text_field( $_SERVER['HTTP_USER_AGENT'] );


		if ( 0 === $post_id ) {
			if ( $id = get_the_ID() ) {
				$post_id = $id;
			}
		}

		if ( 0 === $user_id ) {
			$user_id = get_current_user_id();
		}


		$wpdb->insert(
			$table_name,
			[
				'post_id'    => $post_id,
				'user_id'    => $user_id,
				'action'     => $action,
				'data'       => $data,
				'user_agent' => $user_agent,
			],
			[
				'%d',
				'%d',
				'%s',
				'%s',
				'%s',
			]
		);


	}

}