<?php

namespace HulkPlugins\ElementorPro\Forms\AdvancedFields\Utils;

class FileUtil {

	/**
	 * Returns the directory path for uploaded files.
	 *
	 * @return string Directory path.
	 */
	public static function upload_tmp_dir(): string {
		$dir = path_join( self::upload_dir( 'dir' ), 'hulk_affef_dropzone_uploads' );
		wp_mkdir_p( $dir );
		return $dir;
	}

	/**
	 * Retrieves uploads directory information.
	 *
	 * @param string|bool $type Optional. Type of output. Default false.
	 * @return array|string Information about the upload directory.
	 */
	public static function upload_dir( $type = false ) {
		$uploads = wp_get_upload_dir();

		$uploads = apply_filters(
            'hulk_affef_dropzone_upload_dir',
            [
				'dir' => $uploads['basedir'],
				'url' => $uploads['baseurl'],
            ]
        );

		if ( $type === 'dir' ) {
			return $uploads['dir'];
		} if ( $type === 'url' ) {
			return $uploads['url'];
		}

		return $uploads;
	}

	/**
	 * Cleans up files in the temporary directory for uploaded files.
	 *
	 * @param int $seconds Files older than this are removed. Default 60.
	 * @param int $max Maximum number of files to be removed in a function call.
	 *                 Default 100.
	 */
	public static function cleanup_upload_files( int $seconds = 60, int $max = 100 ): void {
		$wp_filesystem = Filesystem::getInstance();

		$dir = trailingslashit( self::upload_tmp_dir() );

		// Check if directory is accessible
		if (
			! $wp_filesystem->is_dir( $dir ) ||
			! $wp_filesystem->is_readable( $dir ) ||
			! $wp_filesystem->is_writable( $dir )
		) {
			return;
		}

		$seconds = absint( $seconds );
		$max = absint( $max );
		$count = 0;

		// Get files in the directory
		$files = $wp_filesystem->dirlist( $dir );

		if ( $files && is_array( $files ) ) {
			foreach ( $files as $file => $file_info ) {

				// Skip special files
				if ( in_array( $file, [ '.', '..', '.htaccess' ], true ) ) {
					continue;
				}

				$file_path = trailingslashit( $dir ) . $file;
				$mtime = $wp_filesystem->mtime( $file_path );

				// Skip files less than $seconds old
				if ( $mtime && ( time() < ( $mtime + $seconds ) ) ) {
					continue;
				}

				// Remove the file/directory
				if ( $wp_filesystem->is_dir( $file_path ) ) {
					$wp_filesystem->rmdir( $file_path, true ); // Recursive removal for directories
				} else {
					$wp_filesystem->delete( $file_path );
				}

				++$count;

				// Stop if max deletions reached
				if ( $count >= $max ) {
					break;
				}
			}
		}
	}

	/**
	 * Remove upload directory
	 * @return bool
	 */
	public static function remove_upload_dir(): bool {
		$directory_path = path_join( self::upload_dir( 'dir' ), 'hulk_affef_dropzone_uploads' );
		$wp_filesystem = Filesystem::getInstance();
		if ( $wp_filesystem->is_dir( $directory_path ) ) {
			// Delete the directory forcefully
			return $wp_filesystem->delete( $directory_path, true ); // true ensures recursive deletion
		}
		return false;
	}
}
