<?php

use WC_Vendors\Classes\Front\WCV_Order_Controller;

/**
 * The WCVendors Pro order Controller class
 *
 * This is the order controller class for all front end order management
 *
 * @package    WCVendors_Pro
 * @subpackage WCVendors_Pro/public
 * @author     Jamie Madden <support@wcvendors.com>
 */
class WCVendors_Pro_Order_Controller extends WCV_Order_Controller { //phpcs:ignore

    /**
     * Instance of this class
     *
     * @var WCVendors_Pro_Order_Controller
     * @version 1.8.7
     * @since   1.8.7
     */
    public static $instance = null;

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

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

    /**
     * Is the plugin in debug mode
     *
     * @since    1.0.0
     * @access   private
     * @var      bool $debug plugin is in debug mode
     */
    private $debug;

    /**
     * Is the plugin base directory
     *
     * @since    1.0.0
     * @access   private
     * @var      string $base_dir string path for the plugin directory
     */
    private $base_dir;

    /**
     * The tables header rows
     *
     * @since    1.0.0
     * @access   private
     * @var      array $columns The table columns
     */
    private $columns;

    /**
     * The table rows
     *
     * @since    1.0.0
     * @access   private
     * @var      array $rows The table rows
     */
    private $rows;

    /**
     * The ID of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string $wcvendors_pro The ID of this plugin.
     */
    private $controller_type;

    /**
     * Billing fields.
     *
     * @var array
     * @version 1.0.0
     */
    private static $billing_fields;

    /**
     * Shipping fields.
     *
     * @var array
     * @version 1.0.0
     */
    private static $shipping_fields;

    /**
     * Default start date.
     *
     * @var string
     * @version 1.0.0
     */
    private $default_start;

    /**
     * Max number of pages for pagination
     *
     * @since    1.8.7
     * @access   public
     * @var      int $max_num_pages integer for max number of pages for the query
     */
    public $max_num_pages;

    /**
     * Total number of orders for the query
     *
     * @since    1.8.8
     * @access   public
     * @var      int $total_order_count integer for total number of orders for the query
     */
    public $total_order_count;

    /**
     * Whether the shipping management is disabled
     *
     * @since 1.9.8
     * @var bool
     */
    private $disabled_shipping_management;

    /**
     * Initialize the class and set its properties.
     *
     * @since    1.0.0
     *
     * @param      string $wcvendors_pro The name of the plugin.
     * @param      string $version       The version of this plugin.
     * @param   bool   $debug         Whether debug is enabled or not.
     */
    public static function get_instance( $wcvendors_pro, $version, $debug ) {

        if ( is_null( self::$instance ) ) {
            self::$instance = new self( $wcvendors_pro, $version, $debug );
        }

        return self::$instance;
    }

    /**
     * Initialize the class and set its properties.
     *
     * @since    1.0.0
     *
     * @param      string $wcvendors_pro The name of the plugin.
     * @param      string $version       The version of this plugin.
     * @param   bool   $debug         Whether debug is enabled or not.
     */
    public function __construct( $wcvendors_pro, $version, $debug ) {

        $this->wcvendors_pro   = $wcvendors_pro;
        $this->version         = $version;
        $this->debug           = $debug;
        $this->base_dir        = plugin_dir_path( __DIR__ );
        $this->controller_type = 'order';

        $orders_sales_range  = get_option( 'wcvendors_orders_sales_range', 'monthly' );
        $this->default_start = '';
        add_action( 'wcvendors_shipping_label', array( $this, 'shipping_label' ), 10, 2 );
        add_filter( 'wcv_order_statuses', array( $this, 'filter_order_statuses' ) );
        add_filter( 'wcv_orders_count_by_statuses', array( $this, 'filter_orders_count_by_statuses' ) );
        add_filter( 'option_wcvendors_vendor_dashboard_order_status', array( $this, 'filter_vendor_dashboard_order_status_option' ) );

        $this->disabled_shipping_management = wc_string_to_bool( get_option( 'wcvendors_shipping_management_cap', 'no' ) );

        if ( $this->disabled_shipping_management ) {
            add_filter( 'wcv_dashboard_quick_links', array( $this, 'disable_awaiting_shipping_status_quick_link' ) );
            add_filter( 'wcvendors_is_vendor_shipping_disabled', '__return_true' );
        }
    }


    /**
     * Disable the awaiting shipping status quick link if the shipping management is disabled
     *
     * @since 1.9.8
     *
     * @param array $links The quick links.
     * @return array The filtered quick links.
     */
    public function disable_awaiting_shipping_status_quick_link( $links ) {

        if ( isset( $links['order'] ) ) {
            unset( $links['order'] );
        }

        return $links;
    }

    /**
     *  Get the store id of the vendor
     *
     * @since    1.0.0
     *
     * @param     int $vendor_id which vendor is being mark shipped.
     * @param     int $order_id  which order is being marked shipped.
     */
    public static function shipping_label( $vendor_id, $order_id ) {

        $order = wc_get_order( $order_id );

        $vendor_ids = (array) $order->get_meta( 'wcv_vendor_ids' );

        if ( ! in_array( $vendor_id, $vendor_ids, true ) ) {
            wc_add_notice( __( 'You are not allowed to generate label for this order.', 'wcvendors-pro' ), 'error' );
            return;
        }

        $vendor_items    = WCV_Queries::get_products_for_order( $order->get_id() );
        $vendor_products = array();

        foreach ( $order->get_items() as $item ) {
            $product_id     = $item->get_variation_id() > 0 ? $item->get_variation_id() : $item->get_product_id();
            $product_vendor = get_post_field( 'post_author', $product_id );

            if ( ! in_array( $product_id, $vendor_items, true ) && (int) $product_vendor === (int) $vendor_id ) {
                $vendor_products[] = $item;
            }
        }

        // Prevent user editing the $_GET variable.
        if ( empty( $vendor_products ) ) {
            wc_add_notice( __( 'No products for this order.', 'wcvendors-pro' ), 'error' );
            return;
        }

        $store_name    = WCV_Vendors::get_vendor_shop_name( $vendor_id );
        $base_dir      = plugin_dir_path( __DIR__ );
        $countries     = WCVendors_Pro_Form_Helper::countries();
        $store_icon_id = get_user_meta( $vendor_id, '_wcv_store_icon_id', true );

        $store_country = get_user_meta( $vendor_id, '_wcv_store_country', true );
        $store_address = array(
            get_user_meta( $vendor_id, '_wcv_store_address1', true ),
            get_user_meta( $vendor_id, '_wcv_store_address2', true ),
            get_user_meta( $vendor_id, '_wcv_store_city', true ),
            trim(
                sprintf(
                    '%s %s',
                    get_user_meta( $vendor_id, '_wcv_store_state', true ),
                    get_user_meta( $vendor_id, '_wcv_store_postcode', true )
                )
            ),
            isset( $countries[ $store_country ] ) ? $countries[ $store_country ] : '',
        );

        $store_address                       = array_filter( $store_address );
        $override_shpipping_address_if_empty = wc_string_to_bool( get_option( 'wcvendors_orders_override_empty_shipping', 'no' ) );
        $ship_from                           = implode( '<br />', $store_address );
        $ship_to                             = ( wc_ship_to_billing_address_only() || $override_shpipping_address_if_empty )
            ? $order->get_formatted_billing_address()
            : $order->get_formatted_shipping_address();

        wc_get_template(
            'shipping-label.php',
            apply_filters(
                'wcvendors_pro_order_shipping_label',
                array(
                    'order'      => $order,
                    'ship_to'    => $ship_to,
                    'ship_from'  => $ship_from,
                    'store_name' => $store_name,
                    'products'   => $vendor_products,
                    'store_icon' => wp_get_attachment_image( $store_icon_id ),
                )
            ),
            'wc-vendors/dashboard/order/',
            $base_dir . 'templates/dashboard/order/'
        );

        die();
    }

    /**
     * Filter the order statuses
     *
     * @param array $statuses The order statuses.
     * @return array The filtered order statuses.
     *
     * @since 1.9.5
     */
    public function filter_order_statuses( $statuses ) {
        $vendor_order_statuses = get_option( 'wcvendors_vendor_dashboard_order_status', array() );
        if ( empty( $vendor_order_statuses ) ) {
            return $statuses;
        }
        foreach ( $statuses as $key => $status ) {
            if ( ! in_array( $key, $vendor_order_statuses, true ) ) {
                unset( $statuses[ $key ] );
            }
        }
        return $statuses;
    }

    /**
     * Filter the vendor dashboard order status option to remove refunded status when show reversed orders is disabled
     *
     * @param array $order_statuses The vendor dashboard order status option value.
     * @return array The filtered order status option value.
     *
     * @since 2.0.0
     */
    public function filter_vendor_dashboard_order_status_option( $order_statuses ) {
        if ( ! wcv_is_show_reversed_order() && is_array( $order_statuses ) ) {
            $key = array_search( 'wc-refunded', $order_statuses, true );
            if ( false !== $key ) {
                unset( $order_statuses[ $key ] );
            }
        }
        return $order_statuses;
    }

    /**
     * Filter the orders count by statuses
     *
     * @since 1.9.5
     *
     * @param array $statuses The order statuses.
     * @return array The filtered order statuses.
     */
    public function filter_orders_count_by_statuses( $statuses ) {
        $vendor_order_statuses = get_option( 'wcvendors_vendor_dashboard_order_status', array() );
        foreach ( $statuses as $key => $count ) {
            if ( 'awating_shipping' === $key || 'awaiting_shipping' === $key ) {
                continue;
            }
            $wc_key = 'wc-' . $key;
            if ( ! in_array( $wc_key, $vendor_order_statuses, true ) ) {
                unset( $statuses[ $key ] );
            }
        }

        if ( ! wcv_is_show_reversed_order() ) {
            unset( $statuses['refunded'] );
        }
        return $statuses;
    }
}
