<?php
use WC_Vendors\Classes\Front\WCV_Product_Controller;
/**
 * The main WCVendors Pro Product Controller class
 *
 * This is the main controller class for products, all actions are defined in this class.
 *
 * @package    WCVendors_Pro
 * @subpackage WCVendors_Pro/public
 * @author     Jamie Madden <support@wcvendors.com>
 *
 * @phpcs:disable WordPress.Security.NonceVerification.Missing
 */
class WCVendors_Pro_Product_Controller extends WCV_Product_Controller { //phpcs:ignore

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

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

    /**
     * Allow HTML markup in forms
     *
     * @since    1.3.3
     * @access   private
     * @var      string $allow_markup boolean option to allow mark up in forms
     */
    private $allow_markup;

    /**
     * Is the ratings table name
     *
     * @since    1.0.0
     * @access   public
     * @var      string $table_name name of the ratings table
     */
    public $table_name;

    /**
     * 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         If the plugin is currently in debug mode.
     */
    public function __construct( $wcvendors_pro, $version, $debug ) {
        global $wpdb;
        $this->wcvendors_pro = $wcvendors_pro;
        $this->version       = $version;
        $this->debug         = $debug;
        $this->base_dir      = plugin_dir_path( __DIR__ );
        $this->table_name    = $wpdb->prefix . 'wcv_feedback';

        add_filter( 'wcvendors_variation_actions', array( $this, 'show_hide_variation_bulk_action' ) );
        add_action( 'wcv_form_input_after__sku', array( $this, 'add_product_identifier_field' ) );
        add_action( 'wcv_save_product', array( $this, 'save_product_identifier' ) );
        add_action( 'template_redirect', array( $this, 'maybe_hide_sold_by_on_vendor_page' ) );
        add_filter( 'wcv_product_table_rows', array( $this, 'make_thumbnails_clickable' ) );
        add_action( 'wcvendors_table_after_product', array( $this, 'print_product_thumbnail_modal' ) );
    }


    /**
     * Maybe hide sold by label on vendor product page
     *
     * @since 2.0.0
     * @version 2.0.0
     *
     * @return void
     */
    public function maybe_hide_sold_by_on_vendor_page(): void {

        if ( ! WCV_Vendors::is_vendor_page() ) {
            return;
        }

        $hide_sold_by_on_vendor_page = wc_string_to_bool(
            get_option( 'wcvendors_hide_sold_by_on_vendor_page', 'no' )
        );

        if ( $hide_sold_by_on_vendor_page ) {
            /**
             * Filter to allow modification of the sold by action removal.
             *
             * @since 2.0.0
             * @param bool $remove_action Whether to remove the sold by action.
             */
            $should_remove_action = apply_filters( 'wcvendors_should_hide_sold_by_on_vendor_page', true );

            if ( $should_remove_action ) {
                remove_action(
                    'woocommerce_after_shop_loop_item',
                    array( 'WCV_Vendor_Shop', 'template_loop_sold_by' ),
                    9
                );
            }
        }
    }

    /**
     * Add the product identifier field to the product edit form
     *
     * @param array $field The field to add the product identifier to.
     *
     * @since 1.9.6
     */
    public function add_product_identifier_field( $field ) {

        if ( ! isset( $field['post_id'] ) ) {
            return;
        }

        WCVendors_Pro_Product_Form::product_identifier( $field['post_id'] );
    }

    /**
     * Save the product identifier field
     *
     * @param int $post_id The post ID.
     *
     * @since 1.9.6
     */
    public function save_product_identifier( $post_id ) {

        if ( ! isset( $_POST['_global_unique_id'] ) ) {
            return;
        }

        $global_unique_id = sanitize_text_field( $_POST['_global_unique_id'] );

        if ( empty( $global_unique_id ) ) {
            delete_post_meta( $post_id, '_global_unique_id' );
            return;
        }

        $global_unique_id_found = wc_get_product_id_by_global_unique_id( $global_unique_id );

        if ( $global_unique_id_found ) {
            wc_add_notice( __( 'Invalid or duplicated GTIN, UPC, EAN or ISBN.', 'wcvendors-pro' ), 'error' );
            return;
        }

        update_post_meta( $post_id, '_global_unique_id', $global_unique_id );
    }

    /**
     *  Process the form submission from the front end.
     *
     * @param int $post_id  The post ID.
     *
     * @since   1.0.0
     * @since   1.8.2 - Added extra permission checks
     */
    public function save_shipping_rate( $post_id ) {

        $shipping_details = wcv_format_product_flat_rate_shipping();

        if ( ! empty( $shipping_details ) ) {
            update_post_meta( $post_id, '_wcv_shipping_details', $shipping_details );
        } else {
            delete_post_meta( $post_id, '_wcv_shipping_details' );
        }

        do_action( 'wcvendors_before_product_save_shipping_rates', $post_id );
        // shipping rates.
        $shipping_rates = array();

        if ( isset( $_POST['_wcv_shipping_fees'] ) ) {

            $shipping_regions_countries = isset( $_POST['_wcv_shipping_countries'] ) ? $_POST['_wcv_shipping_countries'] : array();
            $shipping_method_names      = isset( $_POST['_wcv_shipping_method_names'] ) ? $_POST['_wcv_shipping_method_names'] : array();
            $shipping_states            = isset( $_POST['_wcv_shipping_states'] ) ? $_POST['_wcv_shipping_states'] : array();
            $shipping_postcodes         = isset( $_POST['_wcv_shipping_postcodes'] ) ? $_POST['_wcv_shipping_postcodes'] : array();
            $shipping_fees              = isset( $_POST['_wcv_shipping_fees'] ) ? $_POST['_wcv_shipping_fees'] : array();
            $shipping_fee_count         = count( $shipping_fees );
            $shipping_countries         = array();
            $shipping_regions           = array();

            foreach ( $shipping_regions_countries as $src ) {
                $shipping_countries[] = strstr( $src, 'country:' ) ? str_replace( 'country:', '', $src ) : '';
                $shipping_regions[]   = strstr( $src, 'continent:' ) ? str_replace( 'continent:', '', $src ) : '';
            }
            for ( $i = 0; $i < $shipping_fee_count; $i++ ) {

				if ( $shipping_fees[ $i ] != '' ) { //phpcs:ignore
                    $region       = wc_clean( $shipping_regions[ $i ] );
                    $country      = wc_clean( $shipping_countries[ $i ] );
                    $method_name  = isset( $shipping_method_names[ $i ] ) ? wc_clean( $shipping_method_names[ $i ] ) : '';
                    $state        = wc_clean( $shipping_states[ $i ] );
                    $postcode     = wc_clean( $shipping_postcodes[ $i ] );
                    $qty_override = isset( $_POST[ '_wcv_shipping_overrides_' . $i ] ) ? 'yes' : 'no';

                    $fee                  = wc_format_decimal( $shipping_fees[ $i ] );
                    $shipping_rates[ $i ] = array(
                        'region'       => $region,
                        'country'      => $country,
                        'method_name'  => $method_name,
                        'state'        => $state,
                        'postcode'     => $postcode,
                        'fee'          => $fee,
                        'qty_override' => $qty_override,
                    );
                }
            }
            update_post_meta( $post_id, '_wcv_shipping_rates', $shipping_rates );
        } else {

            delete_post_meta( $post_id, '_wcv_shipping_rates' );
        }
        // Invalidate the shipping cache.
        WC_Cache_Helper::get_transient_version( 'shipping', true );
    }

    /**
     * Show or hide the variation bulk action
     *
     * @since 1.9.4
     * @version 1.9.4
     *
     * @param array $actions The actions to show or hide.
     * @return array The actions to show or hide.
     */
    public function show_hide_variation_bulk_action( $actions ) {
        $hide_enabled         = wc_string_to_bool( get_option( 'wcvendors_hide_product_variations_enabled', 'no' ) );
        $hide_downloadable    = wc_string_to_bool( get_option( 'wcvendors_hide_product_variations_downloadable', 'no' ) );
        $hide_virtual         = wc_string_to_bool( get_option( 'wcvendors_hide_product_variations_virtual', 'no' ) );
        $hide_manage_stock    = wc_string_to_bool( get_option( 'wcvendors_hide_product_variations_manage_stock', 'no' ) );
        $hide_price           = wc_string_to_bool( get_option( 'wcvendors_hide_product_variations_price', 'no' ) );
        $hide_sale_price      = wc_string_to_bool( get_option( 'wcvendors_hide_product_variations_sale_price', 'no' ) );
        $hide_stock_qty       = wc_string_to_bool( get_option( 'wcvendors_hide_product_variations_stock_qty', 'no' ) );
        $hide_weight          = wc_string_to_bool( get_option( 'wcvendors_hide_product_variations_weight', 'no' ) );
        $hide_dimensions      = wc_string_to_bool( get_option( 'wcvendors_hide_product_variations_dimensions', 'no' ) );
        $hide_shipping_class  = wc_string_to_bool( get_option( 'wcvendors_hide_product_variations_shipping_class', 'no' ) );
        $hide_download_limit  = wc_string_to_bool( get_option( 'wcvendors_hide_product_variations_download_limit', 'no' ) );
        $hide_download_expiry = wc_string_to_bool( get_option( 'wcvendors_hide_product_variations_download_expiry', 'no' ) );

        if ( $hide_enabled ) {
            unset( $actions['groups']['status']['toggle_variation_enabled'] );
        }

        if ( $hide_downloadable ) {
            unset( $actions['groups']['status']['options']['toggle_variable_is_downloadable'] );
            unset( $actions['groups']['downloadable'] );
        }

        if ( $hide_virtual ) {
            unset( $actions['groups']['status']['options']['toggle_variable_is_virtual'] );
        }

        if ( $hide_manage_stock ) {
            unset( $actions['groups']['inventory']['toggle_variable_manage_stock'] );
        }

        if ( $hide_sale_price ) {
            unset( $actions['groups']['pricing']['variable_sale_price'] );
            unset( $actions['groups']['pricing']['variable_sale_price_increase'] );
            unset( $actions['groups']['pricing']['variable_sale_price_decrease'] );
            unset( $actions['groups']['pricing']['variable_sale_schedule'] );
        }

        if ( $hide_price ) {
            unset( $actions['groups']['pricing'] );
        }

        if ( $hide_stock_qty ) {
            unset( $actions['groups']['invetory']['variable_stock'] );
        }

        if ( $hide_dimensions ) {
            unset( $actions['groups']['shipping']['variable_width'] );
            unset( $actions['groups']['shipping']['variable_height'] );
            unset( $actions['groups']['shipping']['variable_length'] );
        }

        if ( $hide_weight ) {
            unset( $actions['groups']['shipping']['variable_weight'] );
        }

        if ( $hide_download_limit ) {
            unset( $actions['groups']['downloadable']['download_limit'] );
        }

        if ( $hide_download_expiry ) {
            unset( $actions['groups']['downloadable']['download_expiry'] );
        }

        if ( $hide_manage_stock ) {
            unset( $actions['groups']['inventory']['options']['toggle_variable_manage_stock'] );
        }

        return $actions;
    }

    /**
     * Make product thumbnails clickable in the product table.
     *
     * @since  2.0.1
     * @param  array $rows Array of table row objects.
     * @return array Modified array of table row objects.
     */
    public function make_thumbnails_clickable( $rows ) {

        if ( ! is_array( $rows ) ) {
            return $rows;
        }

        foreach ( $rows as $row ) {
            if ( isset( $row->tn ) && isset( $row->ID ) && is_numeric( $row->ID ) ) {
                $thumbnail_full_url = has_post_thumbnail( $row->ID ) ? wp_get_attachment_url( get_post_thumbnail_id( $row->ID ) ) : wc_placeholder_img_src();
                $row->tn            = '<a href="' . esc_url( $thumbnail_full_url ) . '" class="open-product-thumb-modal" data-href="' . esc_url( $thumbnail_full_url ) . '">' . $row->tn . '</a>';
            }
        }
        return $rows;
    }


    /**
     * Print the product thumbnail modal
     *
     * @since  2.0.1
     * @return void
     */
    public function print_product_thumbnail_modal() {
        wc_get_template( 'product-thumbnail-modal.php', array(), 'wc-vendors/dashboard/product/', WCV_PRO_ABSPATH_TEMPLATES . 'dashboard/product/' );
    }
}
