<?php


namespace WDevs\CustomerOrderExport\Channels;


use WDevs\CustomerOrderExport\Generators\FileProcessor;

class EmailChannel extends ChannelProcessor implements ChannelInterface {

	public static $template_option_key = 'wdevs_coe_email_template_id';
	public static $file_format_option_key = 'wdevs_coe_email_file_format';
	public static $file_name_option_key = 'wdevs_coe_email_file_name';
	public static $csv_delimiter_option_key = 'wdevs_coe_email_csv_delimiter';

	/**
	 * Returns the WooCommerce field settings for this channel
	 *
	 * @param array $templates Available template configurations
	 *
	 * @return array Configured settings array for WooCommerce fields
	 * @since 1.0.0
	 */
	public function get_settings( $templates ) {
		$settings = array(
			array(
				'name' => __( 'E-mail settings', 'orderbridge-for-woocommerce' ),
				'type' => 'title',
				'id'   => 'wdevs_coe_section_email_title',
				'desc' => __( 'Attach an export file to  WooCommerce emails', 'orderbridge-for-woocommerce' ),
			)
		);

		$wc_emails       = WC()->mailer()->get_emails();
		$order_email_ids = $this->get_default_email_ids();

		$email_settings = array();
		$email_options  = array();

		foreach ( $wc_emails as $email ) {
			if ( $email->is_customer_email() && in_array( $email->id, $order_email_ids ) ) {
				$email_options[ $email->id ] = $email;
			}
		}

		uasort( $email_options, function ( $a, $b ) {
			return strcmp( $a->get_title(), $b->get_title() );
		} );

		$email_count = count( $email_options );
		$i           = 0;

		foreach ( $email_options as $email_id => $email ) {
			$group = '';

			if ( $i === 0 ) {
				$group = 'start';
			} elseif ( $i === $email_count - 1 ) {
				$group = 'end';
			}

			$email_settings[] = array(
				'title'         => $i === 0 ? __( 'Select the customer emails that should have the export file attached.', 'orderbridge-for-woocommerce' ) : '',
				'id'            => 'wdevs_coe_attach_emails[' . $email_id . ']',
				'type'          => 'checkbox',
				'checkboxgroup' => $group,
				'desc'          => $email->get_description(),
				/* translators: %s: WooCommerce email ID */
				'desc_tip'      => sprintf( __( 'WooCommerce email id: %s', 'orderbridge-for-woocommerce' ), $email_id ),
				'legend'        => $email->get_title()
			);

			$i ++;
		}

		$settings = array_merge( $settings, $email_settings );

		$email_file_settings = [
			array(
				'title'   => __( 'Template', 'orderbridge-for-woocommerce' ),
				'desc'    => __( 'Select a template.', 'orderbridge-for-woocommerce' ),
				'id'      => self::$template_option_key,
				'type'    => 'select',
				'class'   => 'wc-enhanced-select',
				'options' => $this->get_template_options( $templates ),
				'default' => ''
			),
			array(
				'title'   => __( 'File format', 'orderbridge-for-woocommerce' ),
				'desc'    => $this->get_file_name_description(),
				'id'      => self::$file_format_option_key,
				'type'    => 'select',
				'class'   => 'wc-enhanced-select wdevs_coe_file_format_select',
				'options' => FileProcessor::get_file_formats(),
				'default' => 'csv',
			),
			array(
				'title'   => __( 'CSV delimiter', 'orderbridge-for-woocommerce' ),
				'desc'    => __( 'Choose the delimiter to use in the CSV file.', 'orderbridge-for-woocommerce' ),
				'id'      => self::$csv_delimiter_option_key,
				'type'    => 'select',
				'class'   => 'wc-enhanced-select wdevs_coe_csv_delimiter_select',
				'options' => FileProcessor::get_csv_delimiters(),
				'default' => ',',
			),
			array(
				'title'             => __( 'File name', 'orderbridge-for-woocommerce' ),
				'desc'              => __( 'Enter the file name without an extension.', 'orderbridge-for-woocommerce' ) . ' <button type="button" class="button action wdevs-coe-variables-button">insert variable</button>',
				'id'                => self::$file_name_option_key,
				'class'             => 'wdevs_coe_file_name',
				'type'              => 'text',
				'desc_tip'          => __( 'Only letters (A-Z, a-z), numbers (0-9), underscores (_), hyphens (-), and curly braces { } are allowed.', 'orderbridge-for-woocommerce' ),
				'default'           => FileProcessor::get_default_file_name(),
				'custom_attributes' => array(
					'pattern' => '^[a-zA-Z0-9_\-\{\}]+$'
				),
				'required'          => true
			)
		];

		$settings = array_merge( $settings, $email_file_settings );

		$settings[] = array(
			'type' => 'sectionend',
			'id'   => 'wdevs_coe_section_email_end'
		);

		return $settings;
	}

	/**
	 * Gets the default email ids
	 *
	 * @return array The email ids
	 * @since 1.0.0
	 */
	public function get_default_email_ids() {
		return array(
			'customer_completed_order',
			'customer_failed_order',
			'customer_invoice',
			'customer_on_hold_order',
			'customer_processing_order',
			//'customer_refunded_order'
		);
	}

	/**
	 * Generates the attachment and attaches it to the selected emails
	 *
	 * @param array $attachments Array of existing email attachment file paths.
	 * @param string $email_id The ID of the WooCommerce email being sent.
	 * @param mixed $maybe_order Either a WC_Order object or possibly other value.
	 * @param \WC_Email|null $email_class (Optional) The WooCommerce email class instance.
	 *
	 * @return array array of attachment file paths.
	 * @since 1.0.0
	 */
	public function attach_export_to_email( $attachments, $email_id, $maybe_order, $email_class = null ) {
		if(!$this->is_enabled()){
			return $attachments;
		}

		if ( false === apply_filters( 'wdevs_coe_allow_email_attachment', true, $attachments, $email_id, $maybe_order, $email_class ) ) {
			return $attachments;
		}

		if ( ! $maybe_order instanceof \WC_Order ) {
			return $attachments;
		}

		if ( ! in_array( $email_id, $this->get_default_email_ids(), true ) ) {
			return $attachments;
		}

		$email_settings = get_option( 'wdevs_coe_attach_emails', [] );

		if ( empty( $email_settings[ $email_id ] ) || $email_settings[ $email_id ] !== 'yes' ) {
			return $attachments;
		}

		try {
			if ( ! $this->can_generate() ) {
				return $attachments;
			}

			$original_file_path = $this->generate( $maybe_order->get_id() );
			$file_path          = apply_filters( 'wdevs_coe_get_attachment_file_path', $original_file_path, $attachments, $email_id, $maybe_order, $email_class );

			if ( file_exists( $file_path ) && is_readable( $file_path ) ) {
				$attachments[] = $file_path;
			}
		} catch ( \Exception $e ) {
			return $attachments;
		}

		return $attachments;
	}

	/**
	 * Checks if the channel is enabled
	 *
	 * @return bool
	 * @since 1.0.0
	 */
	public function is_enabled() {
		$email_settings = get_option( 'wdevs_coe_attach_emails', [] );
		$is_enabled = !empty( array_filter( $email_settings, function( $value ) { return $value === 'yes'; } ) );

		return apply_filters( 'wdevs_coe_section_email_enabled', $is_enabled);
	}

	/**
	 * Get the channel name
	 *
	 * @return string
	 * @since 1.0.0
	 */
	public static function get_name() {
		return __( 'Email Attachments', 'orderbridge-for-woocommerce' );
	}

	/**
	 * Get the channel slug
	 *
	 * @return string
	 * @since 1.0.0
	 */
	public static function get_slug() {
		return 'email';
	}

	/**
	 * Check if the channel should show a save button
	 *
	 * @return bool True - show save button
	 * @since 1.0.0
	 */
	public function show_save_button() {
		return true;
	}
}