<?php

namespace WDevs\CustomerOrderExport;

use Automattic\WooCommerce\Utilities\FeaturesUtil;
use WDevs\CustomerOrderExport\Generators\FileProcessor;
use WDevs\CustomerOrderExport\Channels\CustomerAccountChannel;
use WDevs\CustomerOrderExport\Channels\EmailChannel;
use WDevs\CustomerOrderExport\Channels\GoogleDriveChannel;
use WDevs\CustomerOrderExport\Channels\OrderChannel;
/**
 * The WooCommerce functionality of the plugin.
 *
 * @link       https://wijnberg.dev
 * @since      1.0.0
 *
 * @package    Wdevs_Customer_Order_Export
 * @subpackage Wdevs_Customer_Order_Export/includes
 */
/**
 * The WooCommerce functionality of the plugin.
 *
 * Defines the plugin name, version, and hooks for WooCommerce functionality.
 * This class is responsible for registering and rendering the WooCommerce settings.
 *
 * @package    Wdevs_Customer_Order_Export
 * @subpackage Wdevs_Customer_Order_Export/includes
 * @author     Wijnberg Developments <contact@wijnberg.dev>
 */
class Woocommerce {
    use Helper;
    /**
     * The ID of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string $plugin_name The ID of this plugin.
     */
    private $plugin_name;

    /**
     * The version of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string $version The current version of this plugin.
     */
    private $version;

    /**
     * The current settings section.
     *
     * @since    1.0.0
     * @access   private
     * @var      string $current_section The current settings section.
     */
    private $current_section;

    /**
     * Initialize the class and set its properties.
     *
     * @param string $plugin_name The name of this plugin.
     * @param string $version The version of this plugin.
     *
     * @since    1.0.0
     */
    public function __construct( $plugin_name, $version ) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;
        $this->current_section = ( isset( $_GET['section'] ) ? sanitize_text_field( wp_unslash( $_GET['section'] ) ) : '' );
        if ( is_admin() ) {
            $page = ( isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '' );
            $tab = ( isset( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : '' );
            if ( $page === 'wc-settings' && $tab === 'wdevs_coe' ) {
                $this->handle_sections();
            }
        }
    }

    /**
     * Declare WooCommerce compatibility
     *
     * @since 1.0.0
     */
    public function declare_compatibility() {
        if ( class_exists( FeaturesUtil::class ) ) {
            FeaturesUtil::declare_compatibility( 'custom_order_tables', 'orderbridge-for-woocommerce/wdevs-customer-order-export.php', true );
        }
    }

    /**
     * Add settings tab to WooCommerce settings.
     *
     * @param array $settings_tabs Array of WooCommerce setting tabs.
     *
     * @return   array    $settings_tabs    Array of WooCommerce setting tabs.
     * @since    1.0.0
     */
    public function add_settings_tab( $settings_tabs ) {
        $settings_tabs['wdevs_coe'] = __( 'Order export channels', 'orderbridge-for-woocommerce' );
        return $settings_tabs;
    }

    /**
     * Get settings for the current section.
     *
     * @return   array    Array of settings.
     * @since    1.0.0
     */
    public function get_settings( $templates = [] ) {
        switch ( $this->current_section ) {
            case 'templates':
                return $this->get_templates_settings();
            case 'preview':
                return $this->get_preview_settings( $templates );
            default:
                return $this->get_main_settings( $templates );
        }
    }

    /**
     * Output the settings.
     *
     * @since    1.0.0
     */
    public function settings_tab() {
        if ( in_array( $this->current_section, array('templates', 'preview') ) ) {
            $GLOBALS['hide_save_button'] = true;
        }
        $templates = [];
        //main settings or preview
        if ( empty( $this->current_section ) || $this->current_section === 'preview' ) {
            $templates = $this->get_templates();
        }
        woocommerce_admin_fields( $this->get_settings( $templates ) );
        // Include partial files if needed for specific sections
        if ( $this->current_section === 'templates' ) {
            $template_id = Template::get_requested_template_id();
            // Editing a template.
            if ( isset( $template_id ) ) {
                $view_data = [
                    'template' => new Template($template_id),
                ];
                include_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/partials/section-wdevs-customer-order-export-template-columns.php';
            } else {
                //templates overview
                $view_data = [
                    'templates' => $this->get_templates(),
                ];
                include_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/partials/section-wdevs-customer-order-export-templates.php';
            }
        } elseif ( $this->current_section === 'preview' ) {
            $view_data = [
                'templates' => $templates,
            ];
            include_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/partials/section-wdevs-customer-order-export-preview.php';
        }
    }

    /**
     * Save the settings.
     *
     * @since    1.0.0
     */
    public function update_settings() {
        $templates = $this->get_templates();
        woocommerce_update_options( $this->get_settings( $templates ) );
        // Only register translations if we're on the main settings section
        if ( empty( $this->current_section ) ) {
            $this->register_translations();
        }
    }

    /**
     * Handle sections for the settings tab.
     *
     * @since    1.0.0
     * @access   private
     */
    private function handle_sections() {
        add_action( 'woocommerce_sections_wdevs_coe', array($this, 'output_sections') );
        add_action( 'woocommerce_update_options_wdevs_coe', array($this, 'update_settings') );
    }

    /**
     * Get available sections for the settings tab.
     *
     * @return array Array of sections.
     * @since    1.0.0
     */
    public function get_sections() {
        return array(
            ''          => __( 'Channels', 'orderbridge-for-woocommerce' ),
            'templates' => __( 'Templates', 'orderbridge-for-woocommerce' ),
            'preview'   => __( 'Preview', 'orderbridge-for-woocommerce' ),
        );
    }

    /**
     * Output sections navigation.
     *
     * @since    1.0.0
     */
    public function output_sections() {
        $sections = $this->get_sections();
        $documentationURL = 'https://products.wijnberg.dev/product/wordpress/plugins/orderbridge-for-woocommerce/';
        echo '<ul class="subsubsub">';
        foreach ( $sections as $id => $label ) {
            $url = admin_url( 'admin.php?page=wc-settings&tab=wdevs_coe&section=' . sanitize_title( $id ) );
            $class = ( $this->current_section === $id ? 'current' : '' );
            $separator = '|';
            echo '<li><a href="' . esc_url( $url ) . '" class="' . esc_attr( $class ) . '">' . esc_html( $label ) . '</a> ' . esc_html( $separator ) . '</li>';
        }
        ?>

		<?php 
        // Use FreemiusMenu class for clean Freemius menu rendering
        $freemius_menu_config = [
            'account'     => true,
            'pricing'     => true,
            'contact'     => false,
            'support'     => false,
            'affiliation' => false,
            'addons'      => false,
        ];
        $freemius_menu = new FreemiusMenu(wdevs_coe_fs(), $freemius_menu_config);
        $freemius_items = $freemius_menu->get_enabled_menu_items();
        foreach ( $freemius_items as $item_type => $item_data ) {
            ?>
			<li>
				<a href="<?php 
            echo esc_url( $item_data['url'] );
            ?>" 
				   class="fs-submenu-item <?php 
            echo esc_attr( $item_type . ' ' . $item_data['class'] );
            ?>"
				   style="<?php 
            echo ( $item_type === 'pricing' ? 'color: #27ae60;' : '' );
            ?>">
					<?php 
            echo wp_kses_post( $item_data['label'] );
            ?>
				</a> |
			</li>
		<?php 
        }
        ?>
        <li>
            <a href="<?php 
        echo esc_attr( $documentationURL );
        ?>" target="_blank">
				<?php 
        esc_html_e( 'Documentation', 'orderbridge-for-woocommerce' );
        ?>
                <svg style="width: 0.8rem; height: 0.8rem; stroke: currentColor; fill: none;"
                     xmlns="http://www.w3.org/2000/svg"
                     stroke-width="10" stroke-dashoffset="0"
                     stroke-dasharray="0" stroke-linecap="round"
                     stroke-linejoin="round" viewBox="0 0 100 100">
                    <polyline fill="none" points="40 20 20 20 20 90 80 90 80 60"/>
                    <polyline fill="none" points="60 10 90 10 90 40"/>
                    <line fill="none" x1="89" y1="11" x2="50" y2="50"/>
                </svg>
            </a>
        </li>

		<?php 
        echo '</ul><br class="clear" />';
    }

    /**
     * Output footer info
     *
     * @since    1.0.0
     */
    public function render_footer_info() {
        $text = sprintf( 
            /* translators: %s: Link to author site. */
            __( 'OrderBridge – Multi-Channel Export for WooCommerce is developed by %s. Your trusted WordPress & WooCommerce plugin partner from the Netherlands.', 'orderbridge-for-woocommerce' ),
            '<a href="https://products.wijnberg.dev/product/wordpress/plugins/orderbridge-for-woocommerce/" target="_blank" rel="noopener">Wijnberg Developments</a>'
         );
        echo '<span style="padding: 0 30px; background: #f0f0f1; display: block;">' . wp_kses_post( $text ) . '</span>';
    }

    /**
     * @param $value
     * @param $old_value
     * @param $option
     *
     * @return string
     * @since  1.0.0
     */
    public function sanitize_file_name( $value, $old_value, $option ) {
        $string = trim( $value );
        $string = preg_replace( '/[^a-zA-Z0-9_{}-]+/', '-', $string );
        $string = preg_replace( '/-+/', '-', $string );
        $string = trim( $string, '-' );
        if ( empty( $string ) ) {
            return FileProcessor::get_default_file_name();
        }
        return $string;
    }

    /**
     * Get main settings fields.
     *
     * @return array Array of settings.
     * @since    1.0.0
     */
    private function get_main_settings( $templates ) {
        $email_channel = new EmailChannel();
        $settings = $email_channel->get_settings( $templates );
        $order_channel = new OrderChannel();
        $order_settings = $order_channel->get_settings( $templates );
        $settings = array_merge( $settings, $order_settings );
        return apply_filters( 'wdevs_coe_settings', $settings );
    }

    /**
     * Get templates settings fields.
     *
     * @return array Array of settings.
     * @since    1.0.0
     */
    private function get_templates_settings() {
        $settings = array();
        return apply_filters( 'wdevs_coe_settings_templates', $settings );
    }

    /**
     * Get preview settings fields.
     *
     * @return array Array of settings.
     * @since    1.0.0
     */
    private function get_preview_settings( $templates = [] ) {
        $disabled = false;
        if ( empty( $templates ) ) {
            $disabled = true;
        }
        $settings = array(
            array(
                'name' => __( 'Preview Settings', 'orderbridge-for-woocommerce' ),
                'type' => 'title',
                'desc' => __( 'Download a preview export file. First, select the channel you want to preview and optionally select an order.', 'orderbridge-for-woocommerce' ),
                'id'   => 'wdevs_coe_preview_section_title',
            ),
            ( $disabled ? array(
                'type' => 'info',
                'text' => __( 'Please create at least one template to enable the preview functionality.', 'orderbridge-for-woocommerce' ),
            ) : array() ),
            array(
                'title'             => __( 'Channel', 'orderbridge-for-woocommerce' ),
                'desc'              => __( 'Select a channel to preview.', 'orderbridge-for-woocommerce' ),
                'id'                => 'wdevs_coe_preview_section_id',
                'type'              => 'select',
                'class'             => 'wc-enhanced-select',
                'options'           => array(
                    'email'            => __( 'Email', 'orderbridge-for-woocommerce' ),
                    'order'            => __( 'Order edit page', 'orderbridge-for-woocommerce' ),
                    'customer_account' => __( 'Customer dashboard', 'orderbridge-for-woocommerce' ),
                    'google_drive'     => __( 'Google Drive', 'orderbridge-for-woocommerce' ),
                ),
                'desc_tip'          => true,
                'custom_attributes' => ( $disabled ? array(
                    'disabled' => 'disabled',
                ) : array() ),
            ),
            array(
                'title'             => __( 'Preview order', 'orderbridge-for-woocommerce' ),
                'desc'              => __( 'Select an order to generate a preview.', 'orderbridge-for-woocommerce' ),
                'id'                => 'wdevs_coe_preview_order_id',
                'type'              => 'select',
                'class'             => 'wc-enhanced-select',
                'options'           => $this->get_recent_orders_for_preview(),
                'desc_tip'          => true,
                'custom_attributes' => ( $disabled ? array(
                    'disabled' => 'disabled',
                ) : array() ),
            ),
            array(
                'type' => 'sectionend',
                'id'   => 'wdevs_coe_preview_section_end',
            )
        );
        return apply_filters( 'wdevs_coe_settings_preview', $settings );
    }

    /**
     * Register string translations
     *
     * @since 1.0.0
     */
    private function register_translations() {
        // Check if WPML is active
        if ( !defined( 'ICL_SITEPRESS_VERSION' ) ) {
            return;
        }
        $allowed_types = get_option( 'wdevs_coe_allowed_types' );
        do_action(
            'wpml_register_single_string',
            'orderbridge-for-woocommerce',
            'wdevs_coe_allowed_types',
            $allowed_types
        );
    }

    /**
     * Retrieves recent orders for preview dropdown
     *
     * @return array Options for order selection dropdown
     * @since 1.0.0
     */
    private function get_recent_orders_for_preview() {
        $orders = wc_get_orders( array(
            'limit'   => 10,
            'orderby' => 'date',
            'order'   => 'DESC',
            'return'  => 'ids',
        ) );
        $options = array(
            '' => __( 'Select an option', 'orderbridge-for-woocommerce' ),
        );
        foreach ( $orders as $order_id ) {
            $order = wc_get_order( $order_id );
            if ( $order && !is_a( $order, 'WC_Order_Refund' ) ) {
                // translators: %1$s: order ID, %2$s: billing email
                $options[$order_id] = sprintf( __( 'Order #%1$s - %2$s', 'orderbridge-for-woocommerce' ), $order_id, $order->get_billing_email() );
            }
        }
        return $options;
    }

}
