<?php
/**
 * Supplier Logger Service
 *
 * @category   WordPress_Plugin
 * @package    Common
 * @subpackage Services\Logging
 * @author     miniOrange <info@miniorange.com>
 * @license    MIT/Expat
 * @link       https://plugins.miniorange.com/woocommerce-api-product-sync-with-woocommerce-rest-apis
 */

namespace MOWCPS\Common\Services\Logging;

use WP_Error;
use MOWCPS\Common\Models\Supplier_Model;

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

/**
 * The Supplier_Logger class handles supplier-specific debug logs.
 * It allows you to create, update, download and delete log files per supplier.
 */
class Supplier_Logger {

	/**
	 * Debug logs directory
	 */
	const LOG_DIR = MOWCPS_PLUGIN_DIR . 'logs';

	/**
	 * Constructor
	 */
	public function __construct() {
	}

	/**
	 * Add a log entry for a specific supplier
	 *
	 * Usage: Supplier_Logger::debug( $supplier_id, 'Your log message here' );
	 *
	 * @param int    $supplier_id The supplier ID.
	 * @param string $message     The message to log.
	 * @return void
	 */
	public static function debug( $supplier_id, $message ) {
		// Check if logging is enabled for this supplier.
		$supplier_model = new Supplier_Model();
		$supplier       = $supplier_model->get_by_id( $supplier_id );

		// Return early if supplier not found or logging is disabled.
		if ( ! $supplier || ! $supplier['debug_mode'] || ! $supplier['is_active'] ) {
			return;
		}

		$supplier_name = $supplier['name'];

		$file_name = self::get_log_filename( $supplier_name );
		$file_path = wp_normalize_path( self::LOG_DIR . DIRECTORY_SEPARATOR . $file_name );

		// Only create log file if logging is enabled and file doesn't exist.
		if ( ! file_exists( $file_path ) ) {
			self::create_log_file( $supplier_name );
		}

		$formatted_message = '[' . gmdate( 'Y-m-d H:i:s', time() ) . ' UTC] [' . $supplier_name . ']: ' . print_r( $message, true ) . PHP_EOL; //phpcs:ignore -- This is debug logs.

		// Ensure log directory exists.
		if ( wp_mkdir_p( self::LOG_DIR ) ) {
			// Log to the supplier-specific file.
			error_log( $formatted_message, 3, $file_path ); //phpcs:ignore -- This is debug logs.
		} else {
			error_log( 'Could not log due to insufficient permissions at ' . $file_path ); //phpcs:ignore -- This is debug logs.
		}
	}

	/**
	 * Delete logs for a specific supplier
	 *
	 * @param string $supplier_name The supplier name.
	 * @return array|WP_Error
	 */
	public function delete_supplier_logs( $supplier_name ) {
		if ( empty( $supplier_name ) ) {
			return new WP_Error(
				'missing_supplier_name',
				'Supplier name is required',
				array( 'status' => 400 )
			);
		}

		$file_name = self::get_log_filename( $supplier_name );
		$file_path = wp_normalize_path( self::LOG_DIR . DIRECTORY_SEPARATOR . $file_name );

		if ( function_exists( 'WP_Filesystem' ) && WP_Filesystem() ) {
			global $wp_filesystem;
			// Check if the file exists before attempting to delete.
			if ( $wp_filesystem->exists( $file_path ) ) {
				$deleted = $wp_filesystem->delete( $file_path );

				if ( ! $deleted ) {
					return new WP_Error(
						'file_delete_error',
						'Failed to delete log file',
						array( 'status' => 500 )
					);
				}

				// Create a new log file.
				self::create_log_file( $supplier_name );

				return array(
					'message'    => sprintf( 'Debug logs cleared successfully for supplier: %s', $supplier_name ),
					'cleared_at' => gmdate( 'Y-m-d H:i:s' ) . ' UTC',
				);
			} else {
				return new WP_Error(
					'log_file_not_found',
					'Log file does not exist for this supplier',
					array( 'status' => 404 )
				);
			}
		}

		return new WP_Error(
			'filesystem_error',
			'WordPress filesystem not available',
			array( 'status' => 500 )
		);
	}

	/**
	 * Download logs for a specific supplier
	 *
	 * @param string $supplier_name The supplier name.
	 * @return array|WP_Error File data array or error
	 */
	public function download_supplier_log_file( $supplier_name ) {
		$file_name = self::get_log_filename( $supplier_name );
		if ( ! $file_name ) {
			return new WP_Error(
				'no_log_file',
				'No log file found for this supplier',
				array( 'status' => 404 )
			);
		}

		$file_path = self::LOG_DIR . DIRECTORY_SEPARATOR . $file_name;

		if ( ! file_exists( $file_path ) ) {
			return new WP_Error(
				'log_file_not_exists',
				'Log file does not exist',
				array( 'status' => 404 )
			);
		}

		// Use WP_Filesystem for file operations.
		if ( function_exists( 'WP_Filesystem' ) && WP_Filesystem() ) {
			global $wp_filesystem;
			$file_content = $wp_filesystem->get_contents( $file_path );
		} else {
			$file_content = file_get_contents( $file_path ); //phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Fallback when WP_Filesystem not available.
		}

		if ( false === $file_content ) {
			return new WP_Error(
				'file_read_error',
				'Unable to read log file',
				array( 'status' => 500 )
			);
		}

		$download_name = 'miniorange-wcps-' . sanitize_file_name( $supplier_name ) . '-' . gmdate( 'd-m-y-H-i-s' ) . '.log';

		// Return file data for frontend to handle download.
		return array(
			'success'  => true,
			'filename' => $download_name,
			'content'  => $file_content,
			'size'     => strlen( $file_content ),
		);
	}

	/**
	 * Get log filename for a supplier
	 *
	 * @param string $supplier_name The supplier name.
	 * @return string Log filename.
	 */
	private static function get_log_filename( $supplier_name ) {
		// Sanitize supplier name to create a safe filename.
		$safe_name = sanitize_file_name( $supplier_name );
		return $safe_name . '.log';
	}

	/**
	 * Create a new log file for a supplier
	 *
	 * @param string $supplier_name The supplier name.
	 * @return void
	 */
	private static function create_log_file( $supplier_name ) {
		$file_name = self::get_log_filename( $supplier_name );
		$file_path = wp_normalize_path( self::LOG_DIR . DIRECTORY_SEPARATOR . $file_name );

		// Ensure directory exists.
		if ( ! wp_mkdir_p( self::LOG_DIR ) ) {
			return;
		}

		$initial_message = 'This is miniOrange Product Sync for WooCommerce Debug log file for supplier "' . $supplier_name . '" created on ' . gmdate( 'dS-M-Y H:i:s' ) . ' UTC' . PHP_EOL;

		// Create the file with initial message.
		if ( function_exists( 'WP_Filesystem' ) && WP_Filesystem() ) {
			global $wp_filesystem;
			$wp_filesystem->put_contents( $file_path, $initial_message );
		} else {
			file_put_contents( $file_path, $initial_message ); //phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- Fallback when WP_Filesystem not available.
		}
	}
}
