<?php
/**
 * Plugin Name: Easy Digital Downloads - Per Product Emails
 * Plugin URI: https://easydigitaldownloads.com/downloads/per-product-emails/
 * Description: Custom purchase confirmation emails for your products.
 * Version: 2.0.1
 * Requires at least: 5.8
 * Requires PHP: 7.4
 * Author: Easy Digital Downloads
 * Author URI: https://easydigitaldownloads.com/
 * License: GPL-2.0+
 * License URI: http://www.opensource.org/licenses/gpl-license.php
 * Text Domain: edd-per-product-emails
 *
 * @package EDD\Per_Product_Emails
 */

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

if ( ! class_exists( 'EDD_Per_Product_Emails' ) ) {

	/**
	 * Main EDD_Per_Product_Emails class
	 */
	class EDD_Per_Product_Emails {

		/**
		 * Holds the instance
		 *
		 * Ensures that only one instance exists in memory at any one
		 * time and it also prevents needing to define globals all over the place.
		 *
		 * TL;DR This is a static property property that holds the singleton instance.
		 *
		 * @var object
		 * @static
		 * @since 1.0
		 */
		private static $instance;

		/**
		 * Plugin Version
		 *
		 * @var string
		 */
		private $version = '2.0.1';

		/**
		 * Plugin Title
		 *
		 * @var string
		 */
		public $title = 'EDD Per Product Emails';

		/**
		 * The EDD Software Licensing Integration
		 *
		 * @var EDD_PPE_Software_Licensing
		 */
		public static $edd_software_licensing;

		/**
		 * The plugin file.
		 *
		 * @var string
		 */
		public $file;

		/**
		 * The plugin basename.
		 *
		 * @var string
		 */
		public $basename;

		/**
		 * The plugin directory.
		 *
		 * @var string
		 */
		public $plugin_dir;

		/**
		 * The plugin URL.
		 *
		 * @var string
		 */
		public $plugin_url;

		/**
		 * The includes directory.
		 *
		 * @var string
		 */
		public $includes_dir;

		/**
		 * The includes URL.
		 *
		 * @var string
		 */
		public $includes_url;

		/**
		 * 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 get_instance() {
			if ( ! isset( self::$instance ) && ! ( self::$instance instanceof EDD_Per_Product_Emails ) ) {
				self::$instance = new EDD_Per_Product_Emails();
				self::$instance->setup_globals();
				self::$instance->includes();
				self::$instance->setup_actions();
				self::$instance->licensing();
				self::$instance->load_textdomain();

				// Set up integrations.
				self::$edd_software_licensing = new EDD_PPE_Software_Licensing();
			}

			return self::$instance;
		}

		/**
		 * Constructor Function
		 *
		 * @since 1.0
		 * @access private
		 */
		private function __construct() {
			self::$instance = $this;
		}

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

			// paths.
			$this->file       = __FILE__;
			$this->basename   = plugin_basename( $this->file );
			$this->plugin_dir = plugin_dir_path( $this->file );
			$this->plugin_url = plugin_dir_url( $this->file );

			// includes.
			$this->includes_dir = trailingslashit( $this->plugin_dir . 'includes' );
			$this->includes_url = trailingslashit( $this->plugin_url . 'includes' );
		}

		/**
		 * Setup the default hooks and actions
		 *
		 * @since 1.0
		 *
		 * @return void
		 */
		private function setup_actions() {

			add_action( 'admin_menu', array( $this, 'add_submenu_page' ) );
			add_filter( 'plugin_action_links_' . $this->basename, array( $this, 'settings_link' ), 10, 2 );

			if ( edd_ppe_are_email_templates_registered() ) {
				new EDD\PerProductEmails\Emails\Registry();
			}

			do_action( 'edd_ppe_setup_actions' );
		}

		/**
		 * Licensing
		 *
		 * @since 1.0
		 */
		private function licensing() {
			add_action(
				'edd_extension_license_init',
				function ( \EDD\Extensions\ExtensionRegistry $registry ) {
					$registry->addExtension(
						$this->file,
						'Per Product Emails',
						90781,
						$this->version
					);
				}
			);
		}

		/**
		 * Loads the plugin language files
		 *
		 * @access public
		 * @since 1.0.4
		 * @return void
		 */
		public function load_textdomain() {

			// Set filter for plugin's languages directory.
			$lang_dir = $this->plugin_dir . '/languages/';
			$lang_dir = apply_filters( 'edd_ppe_languages_directory', $lang_dir );

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

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

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

		/**
		 * Include required files.
		 *
		 * @since 1.0
		 *
		 * @return void
		 */
		private function includes() {

			require $this->includes_dir . 'receipt-functions.php';
			require $this->includes_dir . 'email-functions.php';
			require $this->includes_dir . 'email-tags.php';
			require_once $this->includes_dir . 'deprecated/functions.php';
			require_once $this->includes_dir . 'legacy/functions.php';

			// Include Integration files.
			require $this->includes_dir . 'integrations/plugin-software-licenses.php';

			do_action( 'edd_ppe_include_files' );

			if ( ! is_admin() ) {
				return;
			}

			require $this->includes_dir . 'receipt-actions.php';
			require $this->includes_dir . 'admin-notices.php';
			require $this->includes_dir . 'admin-settings.php';

			do_action( 'edd_ppe_include_admin_files' );
		}

		/**
		 * Plugin settings link
		 *
		 * @since 1.0
		 *
		 * @param array $links Plugin Action links.
		 *
		 * @return array
		 */
		public function settings_link( $links ) {
			if ( edd_ppe_are_email_templates_registered() ) {
				return $links;
			}
			$url          = add_query_arg(
				array(
					'post_type' => 'download',
					'page'      => 'edd-settings',
					'tab'       => 'emails',
					'section'   => 'purchase_receipts',
				),
				admin_url( 'edit.php' )
			);
			$plugin_links = array(
				'<a href="' . esc_url( $url ) . '">' . __( 'Settings', 'edd-per-product-emails' ) . '</a>',
			);

			return array_merge( $plugin_links, $links );
		}

		/**
		 * Add submenu page
		 *
		 * @since 1.0
		 */
		public function add_submenu_page() {
			if ( edd_ppe_are_email_templates_registered() ) {
				return;
			}
			add_submenu_page( 'edit.php?post_type=download', __( 'Per Product Emails', 'edd-per-product-emails' ), __( 'Per Product Emails', 'edd-per-product-emails' ), edd_ppe_capability_type(), 'edd-receipts', array( $this, 'admin_page' ) );
		}

		/**
		 * Receipts page
		 *
		 * @since 1.0
		 */
		public function admin_page() {

			$action = filter_input( INPUT_GET, 'edd-ppe-action', FILTER_SANITIZE_SPECIAL_CHARS );
			if ( $action && in_array( $action, array( 'add_receipt', 'edit_receipt' ), true ) ) {
				$this->render_email_editor();

				return;
			}
			require_once $this->includes_dir . 'class-receipts-table.php';
			$receipts_table = new EDD_Receipts_Table();
			$receipts_table->prepare_items();
			?>

			<div class="wrap">
				<h1 class="wp-heading-inline">
					<?php esc_html_e( 'Per Product Emails', 'edd-per-product-emails' ); ?>
				</h1>
				<?php
				$link_url = add_query_arg(
					array(
						'page'           => 'edd-receipts',
						'edd-ppe-action' => 'add_receipt',
					),
					admin_url( 'edit.php?post_type=download' )
				);
				?>
				<a href="<?php echo esc_url( $link_url ); ?>" class="add-new-h2 page-title-action">
					<?php esc_html_e( 'Add New', 'edd-per-product-emails' ); ?>
				</a>

				<?php do_action( 'edd_receipts_page_top' ); ?>

				<?php
				if ( ! empty( $receipts_table->total_count ) ) {
					$receipts_table->prepare_items();
					?>
					<form id="edd-receipts-filter" method="get" action="<?php echo esc_url( admin_url( 'edit.php?post_type=download&page=edd-receipts' ) ); ?>">
						<?php $receipts_table->search_box( __( 'Search', 'edd-per-product-emails' ), 'edd-receipts' ); ?>

						<input type="hidden" name="post_type" value="download" />
						<input type="hidden" name="page" value="edd-receipts" />

						<?php $receipts_table->views(); ?>
						<?php $receipts_table->display(); ?>
					</form>
					<?php
				} else {
					wp_enqueue_style( 'edd-ppe-admin', $this->plugin_url . 'assets/css/admin.css', array(), $this->version );
					?>
					<div class="edd-no-items">
						<img src="<?php echo esc_url( $this->plugin_url . 'assets/images/edd-no-items.svg' ); ?>" alt="">
						<h2><?php esc_html_e( 'Create Your First Email', 'edd-per-product-emails' ); ?></h2>
						<p><?php esc_html_e( 'Configure personalized email notifications for for specific products.', 'edd-per-product-emails' ); ?></p>
						<div class="edd-no-items__actions">
							<a class="button button-primary" href="<?php echo esc_url( $link_url ); ?>">
									<?php esc_html_e( 'Add Email', 'edd-per-product-emails' ); ?>
							</a>
							<a class="button button-secondary" href="<?php echo esc_url( 'https://easydigitaldownloads.com/docs/per-product-emails-documentation/' ); ?>" target="_blank">
									<?php esc_html_e( 'Learn More', 'edd-per-product-emails' ); ?>
							</a>
						</div>
					</div>
					<?php
				}
				?>
				<?php do_action( 'edd_receipts_page_bottom' ); ?>
			</div>
			<?php
		}

		/**
		 * Renders the email editor.
		 *
		 * @since 2.0.0
		 * @throws \Exception
		 */
		private function render_email_editor() {
			try {
				if ( ! current_user_can( edd_ppe_capability_type() ) ) {
					throw new \Exception( __( 'You do not have permission to edit this email.', 'edd-per-product-emails' ) );
				}

				$action = filter_input( INPUT_GET, 'edd-ppe-action', FILTER_SANITIZE_SPECIAL_CHARS );
				if ( ! in_array( $action, array( 'add_receipt', 'edit_receipt' ), true ) ) {
					throw new \Exception( __( 'Invalid action.', 'edd-per-product-emails' ) );
				}

				$email_id = filter_input( INPUT_GET, 'receipt', FILTER_SANITIZE_NUMBER_INT );
				if ( 'edit_receipt' === $action ) {
					if ( ! $email_id ) {
						throw new \Exception( __( 'Missing email ID.', 'edd-per-product-emails' ) );
					}
					require_once $this->includes_dir . 'edit-receipt.php';

					return;
				}

				require_once $this->includes_dir . 'add-receipt.php';
			} catch ( \Exception $e ) {
				wp_die( $e->getMessage() );
			}
		}

		/**
		 * Subtle styling to override CSS added by WP. By default the WP CSS causes the TinyMCE buttons to stretch
		 *
		 * @since 1.0
		 * @deprecated 2.0.0
		 */
		public function admin_css() {

			global $pagenow, $typenow;

			// only load CSS when we're adding or editing a purchase receipt.
			if ( ! ( isset( $_GET['edd-action'] ) && ( 'edit_receipt' == $_GET['edd-action'] || 'add_receipt' == $_GET['edd-action'] ) && 'download' == $typenow && 'edit.php' == $pagenow ) ) {
				return;
			}
			?>
			<style>.quicktags-toolbar input{width: auto;}</style>
			<?php
		}
	}

	/**
	 * Loads a single instance
	 *
	 * This follows the PHP singleton design pattern.
	 *
	 * Use this function like you would a global variable, except without needing
	 * to declare the global.
	 *
	 * @example <?php $edd_per_product_emails = edd_per_product_emails(); ?>
	 *
	 * @since 1.0
	 *
	 * @see EDD_Per_Product_Emails::get_instance()
	 *
	 * @return object Returns an instance of the EDD_Per_Product_Emails class
	 */
	function edd_per_product_emails() {
		return EDD_Per_Product_Emails::get_instance();
	}

	require_once __DIR__ . '/vendor/autoload.php';
	\EDD\ExtensionUtils\v1\ExtensionLoader::loadOrQuit(
		__FILE__,
		'edd_per_product_emails',
		array(
			'php'                    => '7.4',
			'wp'                     => '5.8',
			'easy-digital-downloads' => '3.2.0',
		)
	);
}
