<?php

namespace WDevs\CustomerOrderExport\Channels;

use WDevs\CustomerOrderExport\Generators\FileGeneratorFactory;
use WDevs\CustomerOrderExport\Generators\FileProcessor;
use WDevs\CustomerOrderExport\Helper;
use WDevs\CustomerOrderExport\Template;
use WDevs\CustomerOrderExport\Variables;

abstract class ChannelProcessor {
	use Helper;

	public static $template_option_key = '';
	public static $file_format_option_key = '';
	public static $file_name_option_key = '';
	public static $csv_delimiter_option_key = ',';

	protected $template;

	public function __construct() {
	}

	/**
	 * Get the channel name
	 *
	 * @return string
	 * @since 1.0.0
	 */
	public static function get_name() {
		return '';
	}

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

	/**
	 * Get the account page description for this channel
	 *
	 * @return string
	 * @since 1.0.0
	 */
	public function get_account_page_description() {
		return '';
	}

	/**
	 * Checks if the channel is connected
	 *
	 * @return bool
	 * @since 1.0.0
	 */
	public function is_connected() {
		return false;
	}

	/**
	 * Render form fields for account page editing
	 *
	 * @return void
	 * @since 1.0.0
	 */
	public function render_account_form_fields() {
		echo '<p>' . esc_html__( 'No configuration options available for this channel.', 'orderbridge-for-woocommerce' ) . '</p>';
	}

	/**
	 * Process form submission from account page
	 *
	 * @param array $post_data The POST data from the form
	 * @return array Array with 'success' boolean and 'message' string
	 * @since 1.0.0
	 */
	public function process_account_form( $post_data ) {
		return [
			'success' => true,
			'message' => __( 'Settings saved successfully.', 'orderbridge-for-woocommerce' )
		];
	}

	/**
	 * Handle OAuth callback from external service
	 *
	 * Default implementation for channels that don't use OAuth.
	 * Channels that need OAuth should override this method.
	 *
	 * @return array Array with 'success' boolean and 'message' string
	 * @since 1.0.0
	 */
	public function handle_oauth_callback() {
		return [
			'success' => false,
			'message' => __( 'OAuth is not supported by this channel.', 'orderbridge-for-woocommerce' )
		];
	}

	/**
	 * Gets the template option key from static property
	 *
	 * @return string
	 * @since 1.0.0
	 */
	public function get_template_option_key() {
		return static::$template_option_key;
	}

	/**
	 * Gets the file format option key from static property
	 *
	 * @return string
	 * @since 1.0.0
	 */
	public function get_file_format_option_key() {
		return static::$file_format_option_key;
	}

	/**
	 * Gets the file name option key from static property
	 *
	 * @return string
	 * @since 1.0.0
	 */
	public function get_file_name_option_key() {
		return static::$file_name_option_key;
	}

	/**
	 * Gets the CSV delimiter option key from static property
	 *
	 * @return string
	 * @since 1.0.0
	 */
	public function get_csv_delimiter_option_key() {
		return static::$csv_delimiter_option_key;
	}

	/**
	 * Gets the template configuration
	 *
	 * @return Template|null The template object or null if not set
	 * @since 1.0.0
	 */
	public function get_template() {
		$template_option_key = $this->get_template_option_key();
		if ( empty( $template_option_key ) ) {
			return null;
		}

		if ( $this->template ) {
			return $this->template;
		}

		$template_id = absint( get_option( $template_option_key, 0 ) );
		if ( $template_id > 0 ) {
			$this->template = new Template( $template_id );

			return $this->template;
		}

		return null;
	}

	/**
	 * Creates a file generator instance based on configured format
	 *
	 * @return FileProcessor
	 * @since 1.0.0
	 */
	public function get_generator() {
		$file_format_option_key = $this->get_file_format_option_key();
		if ( empty( $file_format_option_key ) ) {
			$file_format = 'csv';
		} else {
			$file_format = get_option( $file_format_option_key, 'csv' );
		}

		return FileGeneratorFactory::create( $file_format );
	}

	/**
	 * Generates the output filename with replaced variables
	 *
	 * @param int|null $order_id Optional order ID for variable replacement
	 *
	 * @return string The generated filename with placeholders replaced
	 * @since 1.0.0
	 */
	public function get_file_name( $order_id = null ) {
		$file_name_option_key = $this->get_file_name_option_key();
		$template             = get_option( $file_name_option_key, FileProcessor::get_default_file_name() );
		$variables            = Variables::get_variables( $order_id );

		foreach ( $variables as $key => $variable ) {
			$placeholder = '{{' . $key . '}}';
			$value       = ( $variable['value'] !== null ) ? $variable['value'] : '';
			$template    = str_replace( $placeholder, $value, $template );
		}

		return $template;
	}

	/**
	 * Gets the configured CSV delimiter
	 *
	 * @return string The delimiter character
	 * @since 1.0.0
	 */
	public function get_delimiter() {
		$csv_delimiter_option_key = $this->get_csv_delimiter_option_key();
		$default                  = ',';
		if ( empty( $csv_delimiter_option_key ) ) {
			$delimiter = $default;
		} else {
			$delimiter = get_option( $csv_delimiter_option_key, $default );
		}

		$delimiters = FileProcessor::get_csv_delimiters();
		if ( ! array_key_exists( $delimiter, $delimiters ) ) {
			$delimiter = $default;
		}

		return $delimiter;
	}

	/**
	 * Checks if file generation is possible
	 *
	 * @return bool True if template exists and has columns configured
	 * @since 1.0.0
	 */
	public function can_generate() {
		$template = $this->get_template();
		if ( $template ) {
			$columns = $template->get_columns();
			if ( ! empty( $columns ) ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Generates the export file
	 *
	 * @param int|null $order_id Optional order ID to export
	 *
	 * @return string|null The generated file path or null if generation fails
	 * @since 1.0.0
	 */
	public function generate( $order_id = null ) {
		$template = $this->get_template();
		if ( ! $template ) {
			return null;
		}

		$generator = $this->get_generator();

		return $generator->generate(
			$template,
			$this->get_file_name( $order_id ),
			$order_id,
			$this->get_delimiter()
		);
	}

	/**
	 * Returns the description for the file format selection field.
	 *
	 * @return string Description with optional upsell link.
	 */
	protected function get_file_name_description(){
		$description = esc_html__( 'Choose a file format to export your data.', 'orderbridge-for-woocommerce' );

		if ( ! wdevs_coe_fs()->is_premium() ) {
			$upgrade_url = esc_url( wdevs_coe_fs()->get_upgrade_url() );
			$upsell_text = esc_html__( 'Unlock more formats with Pro', 'orderbridge-for-woocommerce' );

			/* translators: %s: Link to the plugin upgrade (Pro) page */
			$description .= sprintf(
				' <a href="%s" target="_blank" rel="noopener noreferrer">%s</a>',
				$upgrade_url,
				$upsell_text
			);
		}

		return $description;
	}

	public function create_folder( $user_id, $parent_id, $folder_name ){

	}

	public function rename_folder( $user_id, $folder_id, $new_name ){

	}

	public function delete_folder( $user_id, $folder_id ){

	}
}