<?php

namespace Storeplugin\PDFInvoice\App;

defined('ABSPATH') || exit;

use Storeplugin\PDFInvoice\Framework\Utils\File;

/**
 * Manages the temporary directory for mPDF and generated PDFs.
 *
 * @since 2.0.2
 */
class TempDir {
	/**
	 * Cached path so wp_upload_dir() is only called once per request.
	 *
	 * @var string|null
	 */
	private static ?string $path = null;

	/**
	 * Get the temporary directory path.
	 *
	 * Uses the plugin-specific uploads directory when available and falls back
	 * to the system temp directory otherwise.
	 *
	 * @return string Absolute path (no trailing slash).
	 */
	public static function path(): string {
		if ( self::$path !== null ) {
			return self::$path;
		}

		$path = File::getPluginUploadsPath( 'temp' );
		if ( ! is_string( $path ) || $path === '' ) {
			$plugin_slug = File::getPluginStorageSlug();
			$base_dir = wp_normalize_path( sys_get_temp_dir() );
			$path = trailingslashit( $base_dir ) . ( is_string( $plugin_slug ) && $plugin_slug !== '' ? $plugin_slug : 'plugin' ) . '/temp';
		}

		self::$path = $path;

		if ( ! is_dir( self::$path ) ) {
			File::hardenWebDirectory( self::$path );
		}

		return self::$path;
	}

	/**
	 * Store content as a file in the temp directory.
	 *
	 * @param string $filename The file name (basename only).
	 * @param string $content  The file content to write.
	 * @return string|false Full file path on success, false on failure.
	 */
	public static function store( string $filename, string $content ) {
		$filepath = self::path() . '/' . sanitize_file_name( $filename );

		File::putContents( $filepath, $content, 0644 );

		return file_exists( $filepath ) ? $filepath : false;
	}

	/**
	 * Remove a single file if it exists.
	 *
	 * @param string $filepath Absolute path to the file.
	 */
	public static function remove( string $filepath ): void {
		if ( file_exists( $filepath ) ) {
			wp_delete_file( $filepath );
		}
	}

	/**
	 * Remove all generated PDF files from the temp directory.
	 *
	 * Preserves security files such as .htaccess, index.php, and web.config.
	 */
	public static function cleanup(): void {
		$files = glob( self::path() . '/*.pdf' );
		if ( is_array( $files ) ) {
			array_map( 'wp_delete_file', $files );
		}
	}
}
