<?php
/**
 * File system log writer implementation.
 *
 * @package Awesomemotive\Rewardswp\Logging\Writers
 * @since 1.1.0
 */

namespace Awesomemotive\Rewardswp\Logging\Writers;

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

use Awesomemotive\Rewardswp\Interfaces\LogWriterInterface;

/**
 * Writes log entries to files stored under the uploads directory.
 *
 * @since 1.1.0
 */
class FileLogWriter implements LogWriterInterface {
	/**
	 * Base directory for log files.
	 *
	 * @since 1.1.0
	 * @var string
	 */
	private string $log_directory;

	/**
	 * FileLogWriter constructor.
	 *
	 * @since 1.1.0
	 *
	 * @param string|null $log_directory Optional directory path.
	 */
	public function __construct( ?string $log_directory = null ) {
		if ( null === $log_directory || '' === $log_directory ) {
			$log_directory = $this->resolve_default_directory();
		}

		$this->log_directory = $log_directory;
	}

	/**
	 * Write a log entry to the filesystem.
	 *
	 * @since 1.1.0
	 *
	 * @param string $level   Log level.
	 * @param string $message Log message.
	 * @param array  $context Contextual data.
	 */
	public function write( string $level, string $message, array $context = [] ): void {
		if ( empty( $this->log_directory ) ) {
			return;
		}

		if ( ! wp_mkdir_p( $this->log_directory ) ) {
			return;
		}

		$filename = trailingslashit( $this->log_directory ) . 'rewardswp-' . gmdate( 'Y-m-d' ) . '.log';

		$line = sprintf(
			'[%s] %s: %s',
			gmdate( 'c' ),
			strtoupper( $level ),
			$message
		);

		if ( ! empty( $context ) ) {
			$line .= ' ' . wp_json_encode( $context, JSON_PARTIAL_OUTPUT_ON_ERROR );
		}

		$line .= PHP_EOL;

		try {
			$file = new \SplFileObject( $filename, 'a' );
			$file->fwrite( $line );
		} catch ( \RuntimeException $e ) {
			// Best-effort logging; ignore failures.
			return;
		}
	}

	/**
	 * Resolve default log directory under uploads.
	 *
	 * @since 1.1.0
	 *
	 * @return string
	 */
	private function resolve_default_directory(): string {
		$uploads = wp_upload_dir();

		if ( empty( $uploads['basedir'] ) ) {
			return '';
		}

		return trailingslashit( $uploads['basedir'] ) . 'rewardswp/logs';
	}
}
