<?php

namespace WPD_Platform\Utils;

use WPD_Platform\Singleton;

class Helpers extends Singleton {

	/**
	 * Method fs_is_connected()
	 *
	 * Check if WP FileSystem is connected.
	 */
	public static function fs_is_connected() {
		self::get_wp_filesystem();
		global $wp_filesystem;
		if ( ! empty( $wp_filesystem ) && $wp_filesystem->connect() ) {
			return true;
		}
		return false;
	}


	/**
	 * Method check_dir()
	 *
	 * Check if the /platform/ direcorty is writable by server.
	 *
	 * @param string $dir Contains directory path.
	 * @param bool   $die_on_error If true, process will die on error, if false, process will continue.
	 * @param int    $chmod Contains information about the directory permissions settings.
	 *
	 * @throws \Exception Error message.
	 */
	public static function check_dir( $dir, $die_on_error, $chmod = 0755 ) {
		self::get_wp_filesystem();

		/**
		 * Global variable containing the instance of the (auto-)configured filesystem object after the filesystem "factory" has been run.
		 *
		 * @global object $wp_filesystem Filesystem object.
		 */
		global $wp_filesystem;

		if ( ! file_exists( $dir ) ) {
			if ( empty( $wp_filesystem ) ) {
				mkdir( $dir, $chmod, true );
			} else {
				if ( ( 'ftpext' === $wp_filesystem->method ) && defined( 'FTP_BASE' ) ) {
					$ftpBase = FTP_BASE;
					$ftpBase = trailingslashit( $ftpBase );
					$tmpdir  = str_replace( ABSPATH, $ftpBase, $dir );
				} else {
					$tmpdir = $dir;
				}
				$wp_filesystem->mkdir( $tmpdir, $chmod );
			}

			if ( ! file_exists( $dir ) ) {
				$error = esc_html__( 'Unable to create directory ', 'platform' ) . str_replace( ABSPATH, '', $dir ) . '.' . esc_html__( ' Is its parent directory writable by the server?', 'platform' );
				if ( $die_on_error ) {
					self::instance()->error( $error );
				} else {
					throw new \Exception( $error );
				}
			}
		}
	}

    /**
	 * Method get_wp_filesystem()
	 *
	 * Get the WordPress filesystem.
	 *
	 * @return mixed $init WordPress filesystem base.
	 */
	public static function get_wp_filesystem() {

		/**
		 * Global variable containing the instance of the (auto-)configured filesystem object after the filesystem "factory" has been run.
		 *
		 * @global object $wp_filesystem Filesystem object.
		 */
		global $wp_filesystem;

		if ( empty( $wp_filesystem ) ) {
			ob_start();
			if ( file_exists( ABSPATH . '/wp-admin/includes/screen.php' ) ) {
				include_once ABSPATH . '/wp-admin/includes/screen.php';
			}
			if ( file_exists( ABSPATH . '/wp-admin/includes/template.php' ) ) {
				include_once ABSPATH . '/wp-admin/includes/template.php';
			}
			
			if (! function_exists( 'request_filesystem_credentials' ) ) {
				include_once ABSPATH . '/wp-admin/includes/file.php';
			}

			$creds = request_filesystem_credentials( 'test' );
			ob_end_clean();
			if ( empty( $creds ) ) {
				if ( ! defined( 'PLATFORM_SAVE_FS_METHOD' ) ) {

					/**
					 * Defines save file system method.
					 *
					 * @const ( string ) Defined save file system method.
					 */
					define( 'PLATFORM_SAVE_FS_METHOD', get_filesystem_method() );
				}

				/**
				 * Defines file system method.
				 *
				 * @const ( string ) Defined file system method.
				 */
				if ( ! defined( 'FS_METHOD' ) ) {
					define( 'FS_METHOD', 'direct' );
				}
			}
			$init = \WP_Filesystem( $creds );
		} else {
			$init = true;
		}
		return $init;
	}

    /**
	 * Method check_wp_filesystem()
	 *
	 * Check the WordPress filesystem.
	 *
	 * @return mixed $wp_filesystem WordPress filesystem check result.
	 */
	public static function check_wp_filesystem() {

		$FTP_ERROR = 'Failed! Please, add FTP details for automatic updates.';

		self::get_wp_filesystem();

		/**
		 * Global variable containing the instance of the (auto-)configured filesystem object after the filesystem "factory" has been run.
		 *
		 * @global object $wp_filesystem Filesystem object.
		 */
		global $wp_filesystem;

		if ( empty( $wp_filesystem ) ) {
			self::instance()->error( $FTP_ERROR );
		} elseif ( is_wp_error( $wp_filesystem->errors ) ) {
			$errorCodes = $wp_filesystem->errors->get_error_codes();
			if ( ! empty( $errorCodes ) ) {
				self::instance()->error( esc_html__( 'WordPress Filesystem error: ', 'platform' ) . $wp_filesystem->errors->get_error_message() );
			}
		}
		return $wp_filesystem;
	}

    /**
	 * Method starts_with()
	 *
	 * Check if the String 1 starts with the String 2.
	 *
	 * @param string $haystack Contains the String 1 for the comparison.
	 * @param string $needle Contains the String 2 for the comparison.
	 *
	 * @return bool true|false Return true if the comparison is positive, false if not.
	 */
	public static function starts_with( $haystack, $needle ) {
		return ! strncmp( $haystack, $needle, strlen( $needle ) );
	}

	/**
	 * Method ends_with()
	 *
	 * Check if the String 1 ends with the String 2.
	 *
	 * @param string $haystack Contains the String 1 for the comparison.
	 * @param string $needle Contains the String 2 for the comparison.
	 *
	 * @return bool true|false Return true if the comparison is positive, false if not.
	 */
	public static function ends_with( $haystack, $needle ) {
		$length = strlen( $needle );
		if ( 0 == $length ) {
			return true;
		}
		return ( substr( $haystack, - $length ) == $needle );
	}

    /**
	 * Method in_excludes()
	 *
	 * Check if the value is in the excludes list.
	 *
	 * @param array  $excludes Array containing the list of excludes.
	 * @param string $value Value to check.
	 *
	 * @return bool true|false If in excluded list, return true, if not, return false.
	 */
	public static function in_excludes( $excludes, $value ) {
		if ( empty( $value ) ) {
			return false;
		}
		if ( null != $excludes ) {
			foreach ( $excludes as $exclude ) {
				if ( self::ends_with( $exclude, '*' ) ) {
					if ( self::starts_with( $value, substr( $exclude, 0, strlen( $exclude ) - 1 ) ) ) {
						return true;
					}
				} elseif ( $value == $exclude ) {
					return true;
				} elseif ( self::starts_with( $value, $exclude . '/' ) ) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * Method sanitize_filename()
	 *
	 * Sanitize file name.
	 *
	 * @param string $filename Contains the file name to be sanitized.
	 *
	 * @return string $filename Sanitized filename.
	 */
	public static function sanitize_filename( $filename ) {
		if ( ! function_exists( 'mb_ereg_replace' ) ) {
			return sanitize_file_name( $filename );
		}
		// Remove anything which isn't a word, whitespace, number or any of the following caracters -_~,;:[]().
		// If you don't need to handle multi-byte characters you can use preg_replace rather than mb_ereg_replace.
		// Thanks @�?ukasz Rysiak!
		$filename = mb_ereg_replace( '([^\w\s\d\-_~,;:\[\]\(\).])', '', $filename );
		// Remove any runs of periods (thanks falstro!).
		$filename = mb_ereg_replace( '([\.]{2,})', '', $filename );
		return $filename;
	}
    
	/**
	 * Method set_limit()
	 *
	 * Set PHP Memory Limit and PHP Max Execution time values.
	 *
	 * @param int $timeout Contains the timeout value in seconds.
	 * @param int $mem Contains the memory limit value in MB.
	 */
	public static function set_limit( $timeout, $mem = false ) {
		// phpcs:disable -- required in order to achieve desired results, pull request solutions appreciated.
		if ( ! empty( $mem ) ) {
			ini_set( 'memory_limit', $mem );
		}
		set_time_limit( $timeout );
		ini_set( 'max_execution_time', $timeout );
		// phpcs:enable
	}

	/**
	 * Method is_archive()
	 *
	 * Check if the file is archive file.
	 *
	 * @param string $file_name Contains the file name.
	 * @param string $prefix    Contains the prefix.
	 * @param string $suffix    Contains the sufix.
	 *
	 * @return bool true|false If the file is archive, return true, if not, return false.
	 */
	public static function is_archive( $file_name, $prefix = '', $suffix = '' ) {
		return preg_match( '/' . $prefix . '(.*).(zip|tar|tar.gz|tar.bz2)' . $suffix . '$/', $file_name );
	}

	/**
	 * Method human_filesize()
	 *
	 * Convert filesize to more user-friendly format.
	 *
	 * @param int $bytes Contains the value in bytes to convert.
	 * @param int $decimals Contains the number of decimal places to round.
	 *
	 * @return string Value converted to more user-friendly format.
	 */
	public static function human_filesize( $bytes, $decimals = 2 ) {
		$size   = array( 'B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB' );
		$factor = floor( ( strlen( $bytes ) - 1 ) / 3 );

		return sprintf( "%.{$decimals}f", $bytes / pow( 1024, $factor ) ) . $size[ $factor ];
	}

	/**
	 * Method is_dir_empty()
	 *
	 * Check if a directory is empty.
	 *
	 * @param string $dir Contains the directory location path.
	 *
	 * @return bool true|false Return true if the directory is empty, false if not.
	 */
	public static function is_dir_empty( $dir ) {
		if ( ! is_readable( $dir ) ) {
			return null;
		}
		return ( 2 === count( scandir( $dir ) ) );
	}

	/**
	 * Method delete_dir()
	 *
	 * Delete wanted directory.
	 *
	 * @param string $dir Contains the directory location path.
	 */
	public static function delete_dir( $dir ) {
		$nodes = glob( $dir . '*' );

		if ( is_array( $nodes ) ) {
			foreach ( $nodes as $node ) {
				if ( is_dir( $node ) ) {
					self::delete_dir( $node . DIRECTORY_SEPARATOR );
				} else {
					unlink( $node );
				}
			}
		}
		rmdir( $dir );
	}

	/**
	 * Method funct_exists()
	 *
	 * Check if a function exists.
	 *
	 * @param string $func Contains the function name.
	 *
	 * @return bool true|false Return true if the function exists, false if not.
	 */
	public static function funct_exists( $func ) {
		if ( ! function_exists( $func ) ) {
			return false;
		}

		if ( extension_loaded( 'suhosin' ) ) {
			$suhosin = ini_get( 'suhosin.executor.func.blacklist' );
			if ( ! empty( $suhosin ) ) {
				$suhosin = explode( ',', $suhosin );
				$suhosin = array_map( 'trim', $suhosin );
				$suhosin = array_map( 'strtolower', $suhosin );

				return ( function_exists( $func ) && ! array_search( $func, $suhosin ) );
			}
		}
		return true;
	}

	/**
	 * Method get_timestamp()
	 *
	 * Get the timestamp and include GMT offset.
	 *
	 * @param string $timestamp Contains the timestamp value.
	 *
	 * @return string $timestamp The timestamp including the GMT offset.
	 */
	public static function get_timestamp( $timestamp = false ) {
		if ( false === $timestamp ) {
			$timestamp = time();
		}
		$gmtOffset = get_option( 'gmt_offset' );

		return ( $gmtOffset ? ( $gmtOffset * HOUR_IN_SECONDS ) + $timestamp : $timestamp );
	}

	/**
	 * Method format_date()
	 *
	 * Format date as per the WordPress general settings.
	 *
	 * @param string $timestamp Contains the timestamp value.
	 *
	 * @return string Formatted date.
	 */
	public static function format_date( $timestamp ) {
		return date_i18n( get_option( 'date_format' ), $timestamp );
	}

	/**
	 * Method format_time()
	 *
	 * Format time as per the WordPress general settings.
	 *
	 * @param string $timestamp Contains the timestamp value.
	 *
	 * @return string Formatted time.
	 */
	public static function format_time( $timestamp ) {
		return date_i18n( get_option( 'time_format' ), $timestamp );
	}

	/**
	 * Method format_timestamp()
	 *
	 * Format timestamp as per the WordPress general settings.
	 *
	 * @param string $timestamp Contains the timestamp value.
	 *
	 * @return string Formatted date and time.
	 */
	public static function format_timestamp( $timestamp ) {
		return date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $timestamp );
	}


	/**
	 * Method update_option()
	 *
	 * Update option.
	 *
	 * @param string $option_name Contains the option name.
	 * @param string $option_value Contains the option value.
	 * @param string $autoload Autoload? Yes or no.
	 *
	 * @return bool $success true|false Option updated.
	 */
	public static function update_option( $option_name, $option_value, $autoload = 'no' ) {
		$success = add_option( $option_name, $option_value, '', $autoload );
		if ( ! $success ) {
			$success = update_option( $option_name, $option_value );
		}
		return $success;
	}

	/**
	 * Method end_session()
	 *
	 * End session and flush the output buffer.
	 */
	public static function end_session() {
		session_write_close();
		ob_end_flush();
	}

	/**
	 * Method rand_string()
	 *
	 * Generate random string.
	 *
	 * @param int $length Contains the string lenghts.
	 *
	 * @return string $str Generated random string.
	 */
	public static function rand_string( $length ) {
		if ( ! function_exists( '\wp_generate_password' ) ) {
			include_once ABSPATH . WPINC . '/pluggable.php';
		}
		$str = \wp_generate_password( $length, false );
		return $str;
	}

}