<?php
namespace TeknoTok\AiTranslator\Utils;

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

/**
 * Utility logger class.
 */
class Logger {
	/**
	 * Log a message to debug log if active.
	 *
	 * @param string $message The message.
	 * @param string $level   Level ('info', 'warning', 'error').
	 * @return void
	 */
	public static function log( $message, $level = 'info' ) {
		$prefix = sprintf( '[%s] [%s]: ', date( 'Y-m-d H:i:s' ), strtoupper( $level ) );
		$formatted_message = $prefix . ( is_array( $message ) || is_object( $message ) ? print_r( $message, true ) : $message ) . "\n";

		// Log to PHP error_log if WP_DEBUG is active
		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
			error_log( '[TeknoTok AI Translator] ' . trim( $formatted_message ) );
		}

		// Log to custom file
		$file = self::get_log_file_path();
		if ( $file ) {
			@file_put_contents( $file, $formatted_message, FILE_APPEND );
		}
	}

	/**
	 * Get the custom log file path.
	 *
	 * @return string|false
	 */
	public static function get_log_file_path() {
		if ( ! function_exists( 'wp_upload_dir' ) ) {
			return false;
		}
		$upload_dir = wp_upload_dir();
		if ( ! empty( $upload_dir['error'] ) ) {
			return false;
		}
		$dir = $upload_dir['basedir'] . '/teknotok-ait';
		if ( ! file_exists( $dir ) ) {
			@wp_mkdir_p( $dir );
		}
		return $dir . '/debug.log';
	}

	/**
	 * Read recent logs.
	 *
	 * @param int $lines Number of lines to read.
	 * @return string
	 */
	public static function read_logs( $lines = 100 ) {
		$file = self::get_log_file_path();
		if ( ! $file || ! file_exists( $file ) ) {
			return '';
		}

		$data = @file_get_contents( $file );
		if ( empty( $data ) ) {
			return '';
		}

		$all_lines = explode( "\n", trim( $data ) );
		$last_lines = array_slice( $all_lines, -$lines );
		return implode( "\n", $last_lines );
	}

	/**
	 * Clear the log file.
	 *
	 * @return void
	 */
	public static function clear_logs() {
		$file = self::get_log_file_path();
		if ( $file && file_exists( $file ) ) {
			@unlink( $file );
		}
	}
}
