<?php
/**
 * File: Debugger.php
 * Year: 2023
 */

namespace Tami\WooCommerce;

use WC_Logger;
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
if(!class_exists('\Tami\WooCommerce\Debugger')) {
	class Debugger {
		public static WC_Logger $logger;
		const WC_LOG_FILENAME = 'tami-payment';

		public static function isLuhn( $input ): bool {

			if ( ! is_numeric( $input ) ) {
				return false;
			}

			$numeric_string = (string) preg_replace( '/\D/', '', $input );

			$sum = 0;

			$numDigits = strlen( $numeric_string ) - 1;

			$parity = $numDigits % 2;

			for ( $i = $numDigits; $i >= 0; $i -- ) {
				$digit = substr( $numeric_string, $i, 1 );

				if ( ! $parity == ( $i % 2 ) ) {
					$digit <<= 1;
				}

				$digit = ( $digit > 9 )
					? ( $digit - 9 )
					: $digit;

				$sum += $digit;
			}

			return ( 0 == ( $sum % 10 ) );
		}

		public static function mask( $string ): string {
			$regex = '/(?:\d[ \t-]*?){13,19}/m';

			$matches = [];

			preg_match_all( $regex, $string, $matches );

			// No credit card found
			if ( empty( $matches[0] ) ) {
				return $string;
			}

			foreach ( $matches as $match_group ) {
				foreach ( $match_group as $match ) {
					$stripped_match = preg_replace( '/\D/', '', $match );

					// Is it a valid Luhn one?
					if ( false === self::isLuhn( $stripped_match ) ) {
						continue;
					}

					$card_length = strlen( $stripped_match );
					$replacement = str_pad( '', $card_length - 4, '*' ) . substr( $stripped_match, - 4 );

					// If so, replace the match
					$string = str_replace( $match, $replacement, $string );
				}
			}

			return $string;
		}

		public static function log( $message, $title = '', $noMask = false ) {
			if ( empty( self::$logger ) ) {
				self::$logger = new WC_Logger();
			}
			$log_entry = '// tami log started';
			if ( $title ) {
				$log_entry .= PHP_EOL . '#[' . $title . ']' . PHP_EOL;
			}
			if ( is_array( $message ) || is_object( $message ) ) {
				$message = wp_json_encode( $message, JSON_PRETTY_PRINT );
			}
			$log_entry .= $message;
			$log_entry .= PHP_EOL . '// tami log end ' . gmdate( 'Y-m-d H:i:s' );

			if ( ! $noMask ) {
				$log_entry = self::mask( $log_entry );
			}

			self::$logger->add( self::WC_LOG_FILENAME, $log_entry );
		}
	}
}