<?php


namespace WDevs\CustomerOrderExport\Channels;


use WDevs\CustomerOrderExport\Generators\FileProcessor;

class OrderChannel extends ChannelProcessor implements ChannelInterface {

	const ORDER_ACTION_DOWNLOAD = 'download_export_file';

	public static $template_option_key = 'wdevs_coe_order_edit_template_id';
	public static $file_format_option_key = 'wdevs_coe_order_edit_file_format';
	public static $file_name_option_key = 'wdevs_coe_order_edit_file_name';
	public static $csv_delimiter_option_key = 'wdevs_coe_order_edit_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 ) {
		$order_settings = array(
			array(
				'name' => __( 'Order edit page', 'orderbridge-for-woocommerce' ),
				'type' => 'title',
				'id'   => 'wdevs_coe_section_order_edit_title',
				'desc' => __( 'Add a download action to the order edit page', 'orderbridge-for-woocommerce' ),
			),
			array(
				'name'    => __( 'Enable', 'orderbridge-for-woocommerce' ),
				'type'    => 'checkbox',
				'desc'    => __( 'Enable in the order edit page', 'orderbridge-for-woocommerce' ),
				'id'      => 'wdevs_coe_order_edit_enabled',
				'default' => 'no'
			),
			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
			),
			array(
				'type' => 'sectionend',
				'id'   => 'wdevs_coe_section_customer_account_end'
			)
		);

		return $order_settings;
	}

	/**
	 * Checks if the channel is enabled
	 *
	 * @return bool
	 * @since 1.0.0
	 */
	public function is_enabled() {
		$is_enabled = get_option( 'wdevs_coe_order_edit_enabled', 'no' ) === 'yes';

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

	/**
	 * @param $actions
	 * @param $order
	 *
	 * @return array
	 * @since 1.0.0
	 */
	public function download_export_file_add( $actions, $order ) {
		if($this->is_enabled()){
			$actions[ self::ORDER_ACTION_DOWNLOAD ] = __( 'Download export file', 'orderbridge-for-woocommerce' );
		}

		return $actions;
	}

	/**
	 * @param $order
	 *
	 * @return void
	 * @since 1.0.0
	 */
	public function download_export_file_action( $order ) {
		if(!$this->is_enabled()){
			wp_die( -1 );
		}

		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( -1 );
		}

		if ( false === apply_filters( 'wdevs_coe_allow_order_edit_download', true, $order ) ) {
			exit;
		}

		if ( ! $order instanceof \WC_Order ) {
			exit;
		}

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

			$original_file_path = $this->generate( $order->get_id() );
			$file_path          = apply_filters( 'wdevs_coe_get_order_edit_file_path', $original_file_path, $order );

			if ( file_exists( $file_path ) && is_readable( $file_path ) ) {
				$file_name = basename( $file_path );

				header( 'Content-Type: application/octet-stream' );
				header( 'Content-Disposition: attachment; filename="' . esc_attr( $file_name ) . '"' );

				// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_readfile
				readfile( $file_path );
				exit;
			}
		} catch ( \Exception $e ) {
			exit;
		}

		exit;
	}

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

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

	/**
	 * 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;
	}
}