<?php
/**
 * Plugin Name: Easy Digital Downloads - Download Email Attachments
 * Plugin URI: https://easydigitaldownloads.com/downloads/download-email-attachments/
 * Description: Send download files as email attachments when purchased.
 * Version: 1.1.2
 * Author: Easy Digital Downloads
 * Requires PHP: 5.6
 * Requires at least: 4.9
 * Tested up to: 6.0
 * Text Domdain: edd-dea
 * Author URI: https://easydigitaldownloads.com/
 * License: GPL-2.0+
 * License URI: http://www.opensource.org/licenses/gpl-license.php
 */

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

if ( ! class_exists( 'EDD_Download_Email_Attachments' ) ) {

	class EDD_Download_Email_Attachments {

		/**
		 * The one instnace of this class.
		 *
		 * @var instance
		 */
		private static $instance;

		/**
		 * Main Instance
		 *
		 * Ensures that only one instance exists in memory at any one
		 * time. Also prevents needing to define globals all over the place.
		 *
		 * @since 1.0
		 */
		public static function instance() {
			if ( ! isset( self::$instance ) ) {
				self::$instance = new self();
			}

			return self::$instance;
		}

		/**
		 * Start your engines
		 *
		 * @since 1.0
		 *
		 * @return void
		 */
		public function __construct() {
			$this->setup_globals();
			$this->setup_actions();
		}

		/**
		 * Globals
		 *
		 * @since 1.0
		 *
		 * @return void
		 */
		private function setup_globals() {

			$this->version = '1.1.2';
			$this->title   = __( 'Download Email Attachments', 'edd-dea' );

			// Plugin file paths.
			$this->file        = __FILE__;
			$this->basename   = apply_filters( 'edd_dea_plugin_basenname', plugin_basename( $this->file ) );
			$this->plugin_dir = apply_filters( 'edd_dea_plugin_dir_path', plugin_dir_path( $this->file ) );
			$this->plugin_url = apply_filters( 'edd_dea_plugin_dir_url', plugin_dir_url( $this->file ) );

			if ( class_exists( '\\EDD\\Extensions\\ExtensionRegistry' ) ) {
				add_action( 'edd_extension_license_init', function( \EDD\Extensions\ExtensionRegistry $registry ) {
					$registry->addExtension( $this->file, 'Download Email Attachments', 133736, $this->version );
				} );
			} elseif ( class_exists( 'EDD_License' ) ) {
				new EDD_License( $this->file, 'Download Email Attachments', $this->version, 'Easy Digital Downloads', null, null, 133736 );
			}

		}

		/**
		 * Setup the default hooks and actions
		 *
		 * @since 1.0
		 *
		 * @return void
		 */
		private function setup_actions() {
			// Load our translation files.
			add_action( 'after_setup_theme', array( $this, 'load_textdomain' ) );

			// Add the Metabox to downloads.
			if ( edd_get_option( 'edd_dea_per_download_attachments', false ) ) {
				add_action( 'edd_meta_box_fields', array( $this, 'add_metabox' ), 18 );
				add_action( 'edd_metabox_fields_save', array( $this, 'save_metabox' ) );
			}

			// Add extension setting to Emails tab.
			add_filter( 'edd_settings_emails', array( $this, 'settings' ) );

			// Filter attachments.
			if ( function_exists( 'edd_get_order_items' ) ) {
				// Speicifc support for EDD 3.0.
				add_filter( 'edd_receipt_attachments', array( $this, 'add_attachments' ), 10, 3 );
			} else {
				// Support for EDD 2.x.
				add_filter( 'edd_receipt_attachments', array( $this, 'attachments' ), 10, 3 );
			}

			do_action( 'edd_dea_setup_actions' );
		}

		/**
		 * Loads the plugin language files
		 *
		 * @access public
		 * @since 1.0
		 * @return void
		 */
		public function load_textdomain() {
			// Set filter for plugin's languages directory.
			$lang_dir = dirname( plugin_basename( $this->file ) ) . '/languages/';
			$lang_dir = apply_filters( 'edd_dea_languages_directory', $lang_dir );

			// Traditional WordPress plugin locale filter.
			$locale = apply_filters( 'plugin_locale', get_locale(), 'edd-dea' );
			$mofile  = sprintf( '%1$s-%2$s.mo', 'edd-dea', $locale );

			// Setup paths to current locale file.
			$mofile_local  = $lang_dir . $mofile;
			$mofile_global = WP_LANG_DIR . '/edd-dea/' . $mofile;

			if ( file_exists( $mofile_global ) ) {
				// Look in global /wp-content/languages/edd-download-attachments folder.
				load_textdomain( 'edd-dea', $mofile_global );
			} elseif ( file_exists( $mofile_local ) ) {
				// Look in local /wp-content/plugins/edd-download-attachments/languages/ folder.
				load_textdomain( 'edd-dea', $mofile_local );
			} else {
				// Load the default language files.
				load_plugin_textdomain( 'edd-dea', false, $lang_dir );
			}
		}

		/**
		 * Filter attachments
		 *
		 * This is the EDD 3.x compatible method of adding attachments.
		 *
		 * @since 1.1.2
		 *
		 * @param array $attachments  The existing attachments for the receipt email.
		 * @param int   $order_id     The order ID we are sending the receipt for.
		 * @param array $payment_data The data supplied for the payment.
		 *
		 * @return array Array of attachments, possibly with file download URLs.
		 */
		public function add_attachments( $attachments = array(), $order_id = 0, $payment_data = array() ) {
			// If we don't get an order ID just return now.
			if ( empty( $order_id ) ) {
				return $attachments;
			}

			// Get the order items.
			$order_items = edd_get_order_items(
				array(
					'order_id' => $order_id,
				)
			);

			// No order items, nothing to attach.
			if ( empty( $order_items ) ) {
				return $attachments;
			}

			if ( $order_items ) {

				$files        = array();
				$attachments = array();

				foreach ( $order_items as $order_item ) {
					// if per download email attachments is enabled, only get downloads with checkbox enabled.
					if ( edd_get_option( 'edd_dea_per_download_attachments', false ) ) {
						if ( ! get_post_meta( $order_item->product_id, '_edd_dea_enabled', true ) ) {
							continue;
						}
					}

					if ( edd_is_bundled_product( $order_item->product_id ) ) {

						// This is a bundeled product.
						$bundled_ids = get_post_meta( $order_item->product_id, '_edd_bundled_products', true );

						if ( $bundled_ids ) {
							foreach ( $bundled_ids as $id ) {
								$files[] = get_post_meta( $id, 'edd_download_files', true );
							}
						}
					} else {
						// Normal Download.
						$price_id      = is_numeric( $order_item->price_id ) ? absint( $order_item->price_id ) : null;
						$download_files = edd_get_download_files( $order_item->product_id, $price_id );

						if ( empty( $download_files ) ) {
							continue;
						}

						foreach ( $download_files as $download_file ) {
							$files[] = $download_file;
						}
					}
				}

				// No files found for the order items.
				if ( empty( $files ) ) {
					return $attachments;
				}

				foreach ( $files as $file ) {
					$file_id = ! empty( $file['attachment_id'] ) ? intval( $file['attachment_id'] ) : attachment_url_to_postid( $file['file'] );

					if ( ! empty( $file_id ) ) {
						$attachments[] = get_attached_file( $file_id );
					}
				}
			}

			return $attachments;
		}

		/**
		 * Filter attachments
		 *
		 * This is the EDD 2.x compatible method of adding attachments.
		 *
		 * @since 1.0
		 *
		 * @param array $attachments  The existing attachments for the receipt email.
		 * @param int   $payment_id   The order ID we are sending the receipt for.
		 * @param array $payment_data The data supplied for the payment.
		 */
		public function attachments( $attachments, $payment_id, $payment_data ) {

			// get array of download IDs.
			$downloads = edd_get_payment_meta_downloads( $payment_id );

			if ( $downloads ) {

				$files = array();
				$attachments = array();

				foreach ( $downloads as $download ) {

					// if per download email attachments is enabled, only get downloads with checkbox enabled.
					if ( edd_get_option( 'edd_dea_per_download_attachments', false ) ) {
						if ( ! get_post_meta( $download['id'], '_edd_dea_enabled', true ) ) {
							continue;
						}
					}

					if ( edd_is_bundled_product( $download['id'] ) ) {
						// is bundled product.
						$bundled_ids = get_post_meta( $download['id'], '_edd_bundled_products', true );

						if ( $bundled_ids ) {
							foreach ( $bundled_ids as $id ) {
								$files[] = get_post_meta( $id, 'edd_download_files', true );
							}
						}
					} else {
						// normal download.
						$price_id = isset( $download['options']['price_id'] ) && is_numeric( $download['options']['price_id'] ) ? absint( $download['options']['price_id'] ) : null;
						$files[]   = edd_get_download_files( $download['id'], $price_id );
					}
				}

				if ( $files ) {
					$file_urls = array();

					foreach ( $files as $file ) {
						// get the file URLs.
						foreach ( $file as $value ) {
							$file_urls[] = $value['file'];
						}
					}

					if ( $file_urls ) {
						foreach ( $file_urls as $file_url ) {
							$file_id = attachment_url_to_postid( $file_url );
							if ( ! empty( $file_id ) ) {
								$attachments[] = get_attached_file( $file_id );
							}
						}
					}
				}
			}

			return $attachments;
		}

		/**
		 * Add Metabox if per download email attachments are enabled
		 *
		 * @since 1.0
		 *
		 * @param int $post_id The post ID being edited, to add the metabox to.
		 */
		public function add_metabox( $post_id ) {
			$checked = (boolean) get_post_meta( $post_id, '_edd_dea_enabled', true );
			?>
			<p><strong><?php apply_filters( 'edd_dea_header', printf( __( '%s Attachments', 'edd-dea' ), edd_get_label_singular() ) ); ?></strong></p>
			<p>
				<label for="edd_download_attachments">
					<input type="checkbox" name="_edd_dea_enabled" id="edd_download_attachments" value="1" <?php checked( true, $checked ); ?> />
					<?php apply_filters( 'edd_dea_header_label', _e( 'Send file downloads as email attachments', 'edd-dea' ) ); ?>
				</label>
			</p>
			<?php
		}

		/**
		 * Add to save function
		 *
		 * @since 1.0
		 *
		 * @param array $fields Array of fields being saved for a post.
		 *
		 * @return array The array of fields with _edd_dea_enabled added.
		*/
		public function save_metabox( $fields ) {
			$fields[] = '_edd_dea_enabled';

			return $fields;
		}

		/**
		 * Adds the extension settings to the emails tab (as of 1.1.2).
		 *
		 * @since 1.0
		 * @param array $settings The array of email settings.
		 * @return array
		 */
		public function settings( $settings ) {

			$new_settings = array(
				array(
					'id'   => 'edd_dea_header',
					'name' => '<h3>' . $this->title . '</h3>',
					'type' => 'header',
				),
				array(
					'id'   => 'edd_dea_per_download_attachments',
					'name' => __( 'Enable per download file attachments', 'edd-dea' ),
					'desc' => __( 'Enable this option to choose specific downloads to send as attachments. Otherwise, all downloads will be sent as attachments.', 'edd-dea' ),
					'type' => 'checkbox',
					'std'  => '',
				),
			);

			return array_merge( $settings, $new_settings );
		}

		/**
		 * Plugin action links
		 *
		 * @since 1.0
		 *
		 * @param array  $links       The links for the plugin row.
		 * @param string $plugin_link The plugin file to compare against.
		 *
		 * @return array The array of plugin row links.
		 */
		public function action_links( $links, $plugin_link ) {
			if ( 'edd-download-email-attachments/edd-download-email-attachments.php' !== $plugin_link ) {
				return $links;
			}

			$plugin_links = array(
				'<a href="' . admin_url( 'edit.php?post_type=download&page=edd-settings&tab=extensions' ) . '">' . __( 'Settings', 'edd-dea' ) . '</a>',
			);

			return array_merge( $plugin_links, $links );
		}
	}
}

/**
 * Get everything running
 *
 * @since 1.0
 * @sicne 1.1.2 Returns the intantiated class, so it can be used by other plugins.
 *
 * @return EDD_Download_Email_Attachments
 */
function edd_download_email_attachments() {
	return new EDD_Download_Email_Attachments();
}

require_once dirname( __FILE__ ) . '/vendor/autoload.php';
\EDD\ExtensionUtils\v1\ExtensionLoader::loadOrQuit( __FILE__, 'edd_download_email_attachments', array(
	'php'                    => '5.6',
	'easy-digital-downloads' => '2.10',
	'wp'                     => '4.9',
) );
