<?php
/**
 * VertivXMLImporter
 *
 * @package CommonFrameworkPlugin
 */

namespace CommonFrameworkPlugin;

use WP_Error;
use phpseclib3\Net\SFTP;

/**
 * Creates the CommonFrameworkPlugin post type and shortcodes to output them.
 */
class VertivXMLImporter extends \CommonFrameworkPlugin\Module {

	/**
	 * The priority of the module.
	 *
	 * Lower number will be initialized first.
	 *
	 * @var int
	 */
	public $load_order = 1;

	/**
	 * The URL for the SFTP server.
	 *
	 * @var string
	 */
	private $url;

	/**
	 * The username for SFTP login.
	 *
	 * @var string
	 */
	private $username;

	/**
	 * The password for SFTP login.
	 *
	 * @var string
	 */
	private $password;

	/**
	 * Indicates if WP-CLI is being used.
	 *
	 * @var bool
	 */
	private $cli;

	/**
	 * Only register if on an admin page and if fieldmanager plugin is active.
	 *
	 * @return bool
	 */
	public function can_register() {
		return true;
	}

	/**
	 * Register our hooks and initialize SFTP credentials.
	 *
	 * @return void
	 */
	public function register() {
		$this->url = isset( $_ENV['VERTIV_SFTP_URL'] ) ? sanitize_text_field( $_ENV['VERTIV_SFTP_URL'] ) : null;
		$this->username = isset( $_ENV['VERTIV_USERNAME'] ) ? sanitize_text_field( $_ENV['VERTIV_USERNAME'] ) : null;
		$this->password = isset( $_ENV['VERTIV_PASSWORD'] ) ? sanitize_text_field( $_ENV['VERTIV_PASSWORD'] ) : null;
		$this->cli = defined( 'WP_CLI' ) && WP_CLI;
	}

	/**
	 * Imports the XML files from the SFTP server.
	 *
	 * @return WP_Error|null
	 */
	public function import() {
		$this->register();

		if ( is_null( $this->url ) || is_null( $this->username ) || is_null( $this->password ) ) {
			return new WP_Error( 'empty', 'No credentials found.' );
		}

		$port = 22;
		$connect_timeout = 25;
		$read_timeout = 60;

		$sftp = new SFTP( $this->url, $port, $connect_timeout );
		$sftp->setTimeout( $read_timeout );

		if ( ! $sftp->login( $this->username, $this->password ) ) {
			return new WP_Error( 'empty', 'Login Failed' );
		}

		$upload_dir = wp_upload_dir();
		$xml_directory = $upload_dir['basedir'] . '/xml';

		if ( ! file_exists( $xml_directory ) ) {
			$dir = mkdir( $xml_directory, 0777, true );

			if ( ! $dir ) {
				return new WP_Error( 'empty', 'Failed to create xml directory' );
			}
		}

		$files = glob( trailingslashit( $xml_directory ) . '*' );
		foreach ( $files as $file ) {
			if ( is_file( $file ) ) {
				unlink( $file );
			}
		}

		$date = gmdate( 'Y-m-d', strtotime( '-10 days' ) );
		$date_format = strtotime( $date );
		$path = defined( 'WP_ENV' ) && 'production' === WP_ENV ? 'EPiProductsExport' : 'EPiProductsExportPrep';
		$top_level = $sftp->rawlist( $path );
		$filepath = null;
		$most_recent = null;

		foreach ( $top_level as $filename => $data ) {
			$new_path = $path . '/' . $filename;
			if ( isset( $data['type'] ) && isset( $data['mtime'] ) && 2 === $data['type'] && $date_format < $data['mtime'] ) {
				if ( is_null( $most_recent ) || $most_recent < $data['mtime'] ) {
					$most_recent = $data['mtime'];
					$filepath = $new_path;
				}
			}
		}

		if ( is_null( $filepath ) || is_null( $most_recent ) ) {
			return new WP_Error( 'empty', 'Nothing to do.' );
		}

		$filelist = $sftp->nlist( $filepath, true );
		foreach ( $filelist as $file ) {
			$publish_date = explode( '/', $file, 2 );
			$publish_date_format = strtotime( $publish_date[0] );
			if ( $date_format < $publish_date_format ) {
				continue;
			}

			$file_name = basename( $file );
			if ( false === strpos( $file_name, '_en_' ) ) {
				continue;
			}

			$remote_file = '/' . $filepath . '/' . $file;

			if ( $this->cli ) {
				WP_CLI::line( 'Retrieved file (en): ' . $remote_file );
			}

			$upload = $sftp->get( $remote_file, trailingslashit( $xml_directory ) . $file_name );
			if ( ! $upload ) {
				return new WP_Error( 'empty', 'Failed to get file - ' . $remote_file );
			}
		}
	}

	/**
	 * Returns an array of all the xml files in the xml folder.
	 *
	 * @return array
	 */
	public function get_xml_files() {
		$upload_dir = wp_upload_dir();
		$xml_directory = $upload_dir['basedir'] . '/xml';
		$xml_files = array();
		$files = glob( $xml_directory . '/*.xml' );
		$i = 0;

		foreach ( $files as $file ) {
			$xml_files[ $i ] = $file;
			if ( $this->cli ) {
				WP_CLI::line( 'XML File Retrieved: ' . $file );
			}
			$i++;
		}
		return $xml_files;
	}
}
