<?php


namespace WDevs\CustomerOrderExport\Channels;


use WDevs\CustomerOrderExport\Generators\FileProcessor;


class CustomerAccountChannel extends ChannelProcessor implements ChannelInterface {

	const ORDER_ACTION_DOWNLOAD = 'account_download_export_file';

	public static $template_option_key = 'wdevs_coe_customer_account_template_id';
	public static $file_format_option_key = 'wdevs_coe_customer_account_file_format';
	public static $file_name_option_key = 'wdevs_coe_customer_account_file_name';
	public static $csv_delimiter_option_key = 'wdevs_coe_customer_account_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 ) {
		$customer_account_settings = array(
			array(
				'name' => __( 'Customer dashboard settings', 'orderbridge-for-woocommerce' ),
				'type' => 'title',
				'id'   => 'wdevs_coe_section_customer_account_title',
				'desc' => __( 'Add a download link to each order in the customer account overview.', 'orderbridge-for-woocommerce' ),
			),
			array(
				'name'    => __( 'Enable', 'orderbridge-for-woocommerce' ),
				'type'    => 'checkbox',
				'desc'    => __( 'Enable in customer account', 'orderbridge-for-woocommerce' ),
				'id'      => 'wdevs_coe_customer_account_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 $customer_account_settings;
	}

	/**
	 * Checks if the channel is enabled
	 *
	 * @return bool
	 * @since 1.0.0
	 */
	public function is_enabled() {

		$is_enabled = get_option( 'wdevs_coe_customer_account_enabled', 'no' ) === 'yes';

		return apply_filters( 'wdevs_coe_section_customer_account_enabled', $is_enabled );

	}


	/**
	 * @param $actions
	 * @param $order
	 *
	 * @return array
	 * @since 1.0.0
	 */
	public function account_download_export_file_add(
		$actions, $order
	) {
		if($this->is_enabled()){
			$action_name = __( 'Download export file', 'orderbridge-for-woocommerce' );

			$action_name = apply_filters( 'wdevs_coe_customer_account_download_action_name', $action_name, $order );

			$actions[ self::ORDER_ACTION_DOWNLOAD ] = array(
				'url'  => wp_nonce_url( add_query_arg( 'wdevs_coe_order_id', $order->get_id() ), self::ORDER_ACTION_DOWNLOAD . '_order_' . $order->get_id() ),
				'name' => $action_name,
			);
		}


		return $actions;
	}

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

		if ( ! isset( $_GET['wdevs_coe_order_id'] ) || ! isset( $_GET['_wpnonce'] ) ) {
			return;
		}

		$order_id = absint( $_GET['wdevs_coe_order_id'] );

		if ( ! wp_verify_nonce( sanitize_key( wp_unslash( $_GET['_wpnonce'] ) ), self::ORDER_ACTION_DOWNLOAD . '_order_' . $order_id ) ) {
			wc_add_notice( __( 'Invalid nonce verification', 'orderbridge-for-woocommerce' ), 'error' );
			wp_safe_redirect( wc_get_account_endpoint_url( 'orders' ) );
			exit;

		}

		$order = wc_get_order( $order_id );

		if ( ! $order || ! current_user_can( 'view_order', $order_id ) ) {
			wc_print_notice(
				esc_html__( 'Invalid order.', 'orderbridge-for-woocommerce' ) . ' <a href="' . esc_url( wc_get_page_permalink( 'myaccount' ) ) . '" class="wc-forward">' . esc_html__( 'My account', 'orderbridge-for-woocommerce' ) . '</a>',
				'error'
			);
			wp_safe_redirect( wc_get_account_endpoint_url( 'orders' ) );
			exit;
		}

		try {
			if ( ! $this->can_generate() ) {
				wc_add_notice( __( 'Can\'t generate file', 'orderbridge-for-woocommerce' ), 'error' );

				return;
			}

			$original_file_path = $this->generate( $order->get_id() );
			$file_path          = apply_filters( 'wdevs_coe_get_customer_account_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 ) {

		}

		wp_safe_redirect( wc_get_account_endpoint_url( 'orders' ) );
		exit;

	}

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

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

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

}