<?php
/**
 * AMVE_Upload_Trailer Class file.
 *
 * @package AMVE\Admin\Class
 */

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

/**
 * AMVE_Upload_Trailer class
 *
 * @since 1.0.0
 */
class AMVE_Upload_Trailer {
	/**
	 * Execute upload trailer.
	 *
	 * @param string  $trailer_url The url of the trailer to upload.
	 * @param integer $post_id     The post_id to attach the trailer to.
	 * @return string The url of the trailer uploaded on the server. Empty string if an parameters are bad or if an error happens.
	 */
	public function execute( $trailer_url = '', $post_id = 0 ) {
		if ( '' === $trailer_url ) {
			return '';
		}

		if ( 0 === $post_id ) {
			return '';
		}

		require_once ABSPATH . 'wp-admin/includes/media.php';
		require_once ABSPATH . 'wp-admin/includes/file.php';
		require_once ABSPATH . 'wp-admin/includes/image.php';

		/*
		* Build the $file_array with
		* $url = the url of the image
		* $temp = storing the image in WordPress
		*/
		$tmp = download_url( $trailer_url );

		/**
		 * Check for download errors
		 */
		if ( is_wp_error( $tmp ) ) {
			return '';
		}

		$trailer_url_without_query = preg_replace( '/\/?\?.*/', '', $trailer_url );
		$file_type                 = wp_check_filetype( $trailer_url_without_query );

		$file_name = sanitize_title( get_the_title( $post_id ) ) . '.' . $file_type['ext'];

		$file_array = array(
			'name'     => $file_name,
			'tmp_name' => $tmp,
		);

		$id = media_handle_sideload( $file_array, $post_id );

		if ( ! is_wp_error( $id ) ) {
			return wp_get_attachment_url( $id );
		}

		if ( is_string( $file_array['tmp_name'] ) ) {
			@unlink( $file_array['tmp_name'] );
		}

		return '';
	}
}
