<?php

namespace IGD_PRO;

use IGD\Account;
use IGD\App;
use IGD\Uploader;

defined( 'ABSPATH' ) || exit;

class WooCommerceUploads {

    /**
     * @var null
     */
    protected static $instance = null;

    public function __construct() {

        // Add Product Type
        add_filter( 'product_type_options', [ $this, 'add_uploadable_product_option' ] );

        // Add Product Data Tab
        add_filter( 'woocommerce_product_data_tabs', [ $this, 'add_product_data_tab' ] );
        add_action( 'woocommerce_product_data_panels', [ $this, 'add_product_data_tab_content' ] );

        // Save product meta
        add_action( 'woocommerce_process_product_meta', [ $this, 'save_product_meta' ] );
        add_action( 'woocommerce_process_product_meta_variable', [ $this, 'save_product_meta' ] );
        add_action( 'woocommerce_ajax_save_product_variations', [ $this, 'save_product_meta' ] );
        add_action( 'woocommerce_process_product_meta_composite', [ $this, 'save_product_meta' ] );

        // Admin order page details
        add_action( 'woocommerce_admin_order_item_headers', [ $this, 'admin_order_item_headers' ] );
        add_action( 'woocommerce_admin_order_item_values', [ $this, 'admin_order_item_values' ], 10, 3 );

        // Render product page uploader
        add_action( 'woocommerce_before_add_to_cart_button', [ $this, 'render_product_page_uploader' ] );

        // Render Order Received, My Account Page Upload Box
        add_action( 'woocommerce_order_item_meta_end', [ $this, 'render_order_received_uploader' ], 10, 3 );

        // Change Thank You Text
        add_filter( 'woocommerce_thankyou_order_received_text', [ $this, 'change_order_received_text' ], 10, 2 );

        // Render Upload button to my Order Table
        add_filter( 'woocommerce_my_account_my_orders_actions', [ $this, 'add_orders_column_actions' ], 10, 2 );

        // Render cart page uploader
        add_action( 'woocommerce_after_cart_item_name', [ $this, 'render_cart_page_uploader' ] );

        // Handle Order Metadata Tags
        add_action( 'woocommerce_checkout_order_created', [ $this, 'save_checkout_uploads' ] );
        add_action( 'woocommerce_store_api_checkout_order_processed', [ $this, 'save_checkout_uploads' ] );

        // add .igd-wc-upload-wrap{display: none;} to the wooCommerce order email
        add_filter( 'woocommerce_email_styles', [ $this, 'add_email_styles' ] );

        // Check min files validation in cart and checkout page
        add_action( 'woocommerce_check_cart_items', [ $this, 'check_min_files' ] );

        add_filter( 'woocommerce_add_to_cart_validation', [ $this, 'validate_required_upload_field' ], 10, 3 );

        // Add uploader data to cart items in cart/checkout blocks
        add_filter( 'woocommerce_get_item_data', [ $this, 'add_blocks_cart_items_data' ], 99, 2 );

        // Get upload folder id for WooCommerce product settings
        add_filter( 'igd_woocommerce_upload_folder_id', [ $this, 'add_woocommerce_upload_folder_id' ], 10, 4 );
    }

    /**
     * Get upload folder id for WooCommerce product settings
     *
     * @param $folder_id
     * @param $data
     * @param $product
     * @param $order
     *
     * @return mixed
     */
    public function add_woocommerce_upload_folder_id( $folder_id, $data, $product, $order ) {

        $folder = $this->get_upload_folder( $data, $product, $order );

        return ! empty( $folder['id'] ) ? $folder['id'] : $data['folderId'];
    }

    public function add_blocks_cart_items_data( $data, $cart_item ) {


        $product_id = $cart_item['product_id'];

        $product = wc_get_product( $product_id );

        if ( ! $this->requires_product_uploads( $product ) ) {
            return $data;
        }

        $upload_locations = $this->get_woocommerce_upload_locations();

        // Check if dokan
        if ( $this->is_dokan_active() ) {
            $upload_locations = $this->get_dokan_upload_locations( $product_id );
        }

        if ( ! in_array( 'cart', $upload_locations ) && ! in_array( 'checkout', $upload_locations ) ) {
            return $data;
        }

        ob_start();
        $this->render_uploader( $product, null, $this->get_session_files( $product_id ) );
        $uploader_html = ob_get_clean();

        $data[] = [
                'key'   => 'igd_wc_uploader',
                'value' => base64_encode( $uploader_html ),
        ];

        return $data;

    }

    public function validate_required_upload_field( $passed, $product_id, $qty ) {
        $product         = wc_get_product( $product_id );
        $requires_upload = $this->requires_product_uploads( $product );

        if ( ! $requires_upload ) {
            return $passed;
        }

        $module_data      = get_post_meta( $product_id, '_igd_module_data', true );
        $module_data      = ! empty( $module_data ) ? json_decode( base64_decode( $module_data ), true ) : [];
        $upload_min_files = ! empty( $module_data['minFiles'] ) ? $module_data['minFiles'] : 0;

        if ( empty( $upload_min_files ) ) {
            return $passed;
        }

        $uploaded_files = $this->get_session_files( $product_id );

        if ( count( $uploaded_files ) < $upload_min_files ) {
            wc_add_notice( __( 'Please upload at least ' . $upload_min_files . ' file(s) for ' . $product->get_name(), 'integrate-google-drive-premium' ), 'error' );

            return false;
        }


        return $passed;
    }

    public function add_email_styles( $styles ) {
        $styles .= '.igd-wc-upload-wrap{display: none;}';

        return $styles;
    }

    public function check_min_files( $posted = null ) {
        $cart_contents = WC()->cart->get_cart();

        foreach ( $cart_contents as $cart_item ) {
            // Get the product object
            $product    = $cart_item['data'];
            $product_id = $product->get_id();

            $requires_upload = $this->requires_product_uploads( $product );

            if ( ! $requires_upload ) {
                continue;
            }

            $module_data      = get_post_meta( $product_id, '_igd_module_data', true );
            $module_data      = ! empty( $module_data ) ? json_decode( base64_decode( $module_data ), true ) : [];
            $upload_min_files = ! empty( $module_data['minFiles'] ) ? $module_data['minFiles'] : 0;

            if ( empty( $upload_min_files ) ) {
                continue;
            }

            $uploaded_files = $this->get_session_files( $product_id );

            if ( count( $uploaded_files ) < $upload_min_files ) {
                wc_add_notice( __( 'Please upload at least ' . $upload_min_files . ' file(s) for ' . $product->get_name(), 'integrate-google-drive-premium' ), 'error' );

                return;
            }
        }
    }

    public function add_product_data_tab( $product_data_tabs ) {

        $product_data_tabs['upload_options'] = [
                'label'  => __( 'Upload to Google Drive', 'integrate-google-drive-premium' ),
                'target' => 'upload_options',
                'class'  => [ 'show_if_uploadable' ],
        ];

        return $product_data_tabs;
    }

    public function add_orders_column_actions( $actions, \WC_Order $order ) {
        $upload_btn_text           = __( 'Upload Documents', 'integrate-google-drive-premium' );
        $should_show_upload_button = false;


        if ( $this->requires_order_uploads( $order ) ) {

            foreach ( $order->get_items() as $order_item ) {
                $product    = $this->get_product( $order_item );
                $product_id = $product->get_id();

                $requires_upload = $this->requires_product_uploads( $product, $order );

                if ( ! $requires_upload ) {
                    $should_show_upload_button = false;
                    continue;
                }

                if ( $this->is_dokan_active() ) {
                    $upload_locations = $this->get_dokan_upload_locations( $product_id );

                    if ( in_array( 'my-account', $upload_locations ) ) {
                        $should_show_upload_button = true;
                    }

                } elseif ( in_array( 'my-account', $this->get_woocommerce_upload_locations() ) ) {
                    $should_show_upload_button = true;
                }


                if ( 'variation' === $product->get_type() ) {
                    $product = wc_get_product( $product->get_parent_id() );
                }


                $module_data     = get_post_meta( $product_id, '_igd_module_data', true );
                $module_data     = ! empty( $module_data ) ? json_decode( base64_decode( $module_data ), true ) : [];
                $upload_btn_text = ! empty( $module_data['uploadBtnText'] ) ? $module_data['uploadBtnText'] : __( 'Upload Files', 'integrate-google-drive-premium' );

                break;
            }

            if ( $should_show_upload_button ) {
                $actions['upload'] = [
                        'url'  => $order->get_view_order_url() . '#igd-uploads',
                        'name' => $upload_btn_text,
                ];
            }
        }

        return $actions;
    }

    public function change_order_received_text( $thank_you_text, $order ) {

        if ( ! $this->requires_order_uploads( $order ) ) {
            return $thank_you_text;
        }

        $should_show_upload_button = false;

        foreach ( $order->get_items() as $order_item ) {
            $product    = $this->get_product( $order_item );
            $product_id = $product->get_id();

            $requires_upload = $this->requires_product_uploads( $product, $order );

            if ( ! $requires_upload ) {
                $should_show_upload_button = false;
                continue;
            }

            if ( $this->is_dokan_active() ) {
                $upload_locations = $this->get_dokan_upload_locations( $product_id );

                if ( in_array( 'my-account', $upload_locations ) && in_array( 'order-received', $upload_locations ) ) {
                    $should_show_upload_button = true;
                }

            } elseif ( in_array( 'my-account', $this->get_woocommerce_upload_locations() ) && in_array( 'order-received', $this->get_woocommerce_upload_locations() ) ) {
                $should_show_upload_button = true;
            }

            break;

        }

        if ( ! $should_show_upload_button ) {
            return $thank_you_text;
        }

        /* translators: %1$s: order url, %2$s: order url */
        $custom_text    = __( ' You can now start uploading your documents', 'integrate-google-drive-premium' );
        $thank_you_text .= apply_filters( 'igd_wc_thank_you_text', $custom_text, $order, $this );

        return $thank_you_text;
    }

    public function admin_order_item_headers( $order ) {
        if ( ! $this->requires_order_uploads( $order ) ) {
            return;
        }

        ?>
        <th style="white-space: nowrap;"><?php esc_html_e( 'Uploaded Files', 'integrate-google-drive-premium' ); ?></th>
        <?php

    }

    public function admin_order_item_values( $_product, $item, $item_id ) {

        if ( ! $_product || ! $this->requires_order_uploads( $item->get_order() ) ) {
            return;
        }

        if ( ! $this->requires_product_uploads( $_product, $item->get_order() ) ) {
            echo '<td> — </td>';

            return;
        }

        $files = array_filter( wc_get_order_item_meta( $item_id, '_igd_files', false ) );

        if ( empty( $files ) ) {
            echo '<td style="text-align: center;"> — </td>';

            return;
        }

        ?>
        <td class="igd-wc-uploaded-files-wrap">
            <ul class="igd-wc-uploaded-files">
                <?php foreach ( $files as $file ) : ?>
                    <li>
                        <a href="<?php echo esc_url( $file['webViewLink'] ); ?>" target="_blank">
                            <img src="<?php echo esc_url( $file['iconLink'] ); ?>"
                                 alt="<?php echo esc_attr( $file['name'] ); ?>"/>
                            <span><?php echo esc_html( $file['name'] ); ?></span>
                        </a>
                    </li>
                <?php endforeach; ?>
            </ul>
        </td>
        <?php
    }

    public function is_dokan_active() {
        $integrations    = igd_get_settings( 'integrations' );
        $is_dokan_upload = igd_get_settings( 'dokanUpload', false );

        return in_array( 'dokan', $integrations ) && $is_dokan_upload && class_exists( 'WeDevs_Dokan' );
    }

    public function get_dokan_upload_locations( $product_id ) {
        $upload_locations = get_user_meta( get_post_field( 'post_author', $product_id ), '_igd_dokan_upload_locations', true );

        return is_array( $upload_locations ) ? $upload_locations : array( 'checkout', 'order-received', 'my-account' );
    }

    public function render_product_page_uploader() {
        global $product;

        $product_id = $product->get_id();

        // Check if dokan
        if ( $this->is_dokan_active() ) {

            $product_id       = get_the_ID();
            $upload_locations = $this->get_dokan_upload_locations( $product_id );

            if ( ! in_array( 'product', $upload_locations ) ) {
                return;
            }
        } elseif ( ! in_array( 'product', $this->get_woocommerce_upload_locations() ) ) {
            return;
        }

        $this->render_uploader( $product, null, $this->get_session_files( $product_id ) );
    }

    public function render_cart_page_uploader( $cart_item ) {

        $product_id = $cart_item['product_id'];
        $product    = wc_get_product( $product_id );

        $upload_locations = $this->get_woocommerce_upload_locations();

        // Check if dokan
        if ( $this->is_dokan_active() ) {
            $upload_locations = $this->get_dokan_upload_locations( $product_id );
        }

        if ( ! in_array( 'cart', $upload_locations ) ) {
            return;
        }

        $this->render_uploader( $product, null, $this->get_session_files( $product_id ) );

    }

    public function render_order_received_uploader( $item_id, $item, $order ) {

        $product = $item->get_product();

        //check if dokan
        if ( $this->is_dokan_active() ) {
            $product_id       = $product->get_id();
            $upload_locations = $this->get_dokan_upload_locations( $product_id );

            if ( is_wc_endpoint_url( 'order-received' ) && ! in_array( 'order-received', $upload_locations ) ) {
                return;
            } elseif ( is_wc_endpoint_url( 'view-order' ) && ! in_array( 'my-account', $upload_locations ) ) {
                return;
            }

        } elseif ( is_wc_endpoint_url( 'order-received' ) && ! in_array( 'order-received', $this->get_woocommerce_upload_locations() ) ) {
            return;
        } elseif ( is_wc_endpoint_url( 'view-order' ) && ! in_array( 'my-account', $this->get_woocommerce_upload_locations() ) ) {
            return;
        }


        if ( $this->requires_product_uploads( $product, $order ) ) {
            // Add upload button in the email
            $is_sending_mail = doing_action( 'woocommerce_email_order_details' );

            if ( $is_sending_mail || ! ( is_wc_endpoint_url() || is_admin() ) ) {
                $order_url = $order->get_view_order_url() . "#igd-uploads-{$item_id}";

                /* translators: %s: order url */
                echo '<br/><small  class="igd-upload-text">' . sprintf( __( 'You can start uploading your documents on the %1$s order page%2$s', 'integrate-google-drive-premium' ), '<a href="' . $order_url . '">', '</a>' ) . '.</small>';

                return;
            }

            $item_files = array_filter( wc_get_order_item_meta( $item_id, '_igd_files', false ) );

            $this->render_uploader( $product, $order, $item_files );
        }

    }

    public function render_uploader( $product, $order = null, $files = [] ) {
        if ( doing_action( 'woocommerce_email_order_details' ) || ! $this->requires_product_uploads( $product ) ) {
            return;
        }

        $product_id = $product->get_id();

        // Prepare module data
        $module_data = get_post_meta( $product_id, '_igd_module_data', true );
        $module_data = ! empty( $module_data ) ? json_decode( base64_decode( $module_data ), true ) : [];

        $wc_page = false;
        if ( is_account_page() ) {
            $wc_page = 'my-account';
        } elseif ( is_wc_endpoint_url( 'order-received' ) ) {
            $wc_page = 'order-received';
        } elseif ( is_product() ) {
            $wc_page = 'product';
        } elseif ( is_checkout() ) {
            $wc_page = 'checkout';
        } elseif ( is_cart() ) {
            $wc_page = 'cart';
        }

        $item_id = $order ? $this->get_order_item_id_by_product_id( $order, $product_id ) : null;

        $module_data['isWooCommerceUploader'] = $wc_page;
        $module_data['wcItemId']              = $item_id;
        $module_data['wcOrderId']             = $order ? $order->get_id() : null;
        $module_data['wcProductId']           = $product_id;
        $module_data['uploadedFiles']         = $files;

        if ( $this->is_dokan_active() ) {
            $vendor_id              = get_post_field( 'post_author', $product_id );
            $module_data['account'] = Account::instance( $vendor_id )->get_active_account();
        }

        $button_text = ! empty( $module_data['uploadBtnText'] ) ? $module_data['uploadBtnText'] : __( 'Upload Documents', 'integrate-google-drive-premium' );


        ?>

        <div class="igd-wc-upload-wrap">

            <button type="button" class="button upload-button">
                <i class="dashicons dashicons-upload"></i>
                <span><?php echo esc_html( $button_text ); ?></span>
            </button>

            <?php

            // Render Upload Box
            echo \IGD\Shortcode::instance()->render_shortcode( [], $module_data );

            // Render Description
            if ( ! empty( $module_data['uploadBoxDescription'] ) ) {
                echo '<p class="igd-wc-upload-description">' . esc_html( $module_data['uploadBoxDescription'] ) . '</p>';
            }

            ?>
        </div>

        <?php
    }

    public function save_checkout_uploads( $order ) {

        if ( ! $order ) {
            return;
        }

        $items = $order->get_items();

        foreach ( $items as $item_id => $item ) {

            $product_id = $item->get_product_id();

            if ( ! $product_id ) {
                return;
            }

            $product = wc_get_product( $product_id );

            if ( ! $this->requires_product_uploads( $product ) ) {
                return;
            }

            // Save files to order
            $files = WC()->session->get( 'igd_product_files_' . $product_id, [] );
            WC()->session->__unset( 'igd_product_files_' . $product_id );

            foreach ( $files as $file ) {
                wc_add_order_item_meta( $item_id, '_igd_files', $file );
            }

            // Uploader data
            $data = WC()->session->get( 'igd_wc_upload_data_' . $product_id, [] );
            WC()->session->__unset( 'igd_wc_upload_data_' . $product_id );

            // Rename uploaded folder once order is placed
            $folder = WC()->session->get( 'igd_upload_folder_' . $product_id, [] );
            WC()->session->__unset( 'igd_upload_folder_' . $product_id );

            $upload_folder_name = ! empty( $data['folderNameTemplate'] ) ? $data['folderNameTemplate'] : 'Order - %wc_order_id% - %wc_product_name% (%user_email%)';

            $args = [
                    'name'       => $upload_folder_name,
                    'wc_product' => $product,
            ];

            $user = $order->get_user();

            // Guest User
            if ( ! $user ) {
                $user_id = $order->get_order_key();

                $user               = new \stdClass();
                $user->user_login   = $order->get_billing_first_name() . ' ' . $order->get_billing_last_name();
                $user->display_name = $order->get_billing_first_name() . ' ' . $order->get_billing_last_name();
                $user->first_name   = $order->get_billing_first_name();
                $user->last_name    = $order->get_billing_last_name();
                $user->user_email   = $order->get_billing_email();
                $user->ID           = $user_id;
                $user->user_role    = esc_html__( 'Anonymous user', 'integrate-google-drive-premium' );
            }

            $args['user']     = $user;
            $args['wc_order'] = $order;

            $name = igd_replace_template_tags( $args );

            $folder['name'] = $name;

            // Rename new folder
            App::instance( $folder['accountId'] )->rename( $name, $folder['id'] );

            // Create folder for each item
            if ( count( $items ) > 1 ) {
                $item_folder_name = __( 'Files of ', 'integrate-google-drive-premium' ) . $product->get_title();

                $new_folder = Uploader::instance( $folder['accountId'] )->create_entry_folder_and_move( $files, $item_folder_name, $folder, true );

                wc_update_order_item_meta( $item_id, '_igd_upload_folder', $new_folder );
            } else {
                wc_update_order_item_meta( $item_id, '_igd_upload_folder', $folder );
            }

        }
    }

    public function get_session_files( $product_id ) {

        if ( empty( WC()->session ) ) {
            return [];
        }

        $files = WC()->session->get( 'igd_product_files_' . $product_id, [] );

        return array_values( array_filter( $files ) );
    }

    // Used in Uploader get_resume_url
    public function get_upload_folder( $data, $product, $order = null ) {
        $product_id = $product->get_id();

        if ( $order ) {
            $order_item_id = $this->get_order_item_id_by_product_id( $order, $product_id );

            if ( ! $order_item_id ) {
                return;
            }

            $folder = wc_get_order_item_meta( $order_item_id, '_igd_upload_folder' );
        } else {
            $folder = WC()->session->get( 'igd_upload_folder_' . $product_id, [] );
        }

        if ( ! empty( $folder ) ) {
            //check if folder is existing in Google Drive
            try {
                $folder = App::instance( $folder['accountId'] )->get_file_by_id( $folder['id'], true );
            } catch ( \Exception $e ) {
                $folder = $this->create_upload_folder( $data, $product, $order );
            }

        }

        if ( empty( $folder ) ) {
            $folder = $this->create_upload_folder( $data, $product, $order );
        }

        return $folder;
    }

    public function create_upload_folder( $data, $product, $order = null ) {
        $product_id = $product->get_id();

        $upload_folder_name = ! empty( $data['folderNameTemplate'] ) ? $data['folderNameTemplate'] : 'Order - %wc_order_id% - %wc_product_name% (%user_email%)';
        $account_id         = ! empty( $data['accountId'] ) ? $data['accountId'] : '';
        $parent_folder_id   = ! empty( $data['folderId'] ) ? $data['folderId'] : '';
        $parent_folder      = [
                'id'        => $parent_folder_id,
                'accountId' => $account_id,
        ];

        $args = [
                'parent'     => $parent_folder,
                'name'       => $upload_folder_name,
                'wc_product' => $product,
        ];

        if ( ! empty( $order ) ) {
            $user = $order->get_user();

            // Guest User
            if ( ! $user ) {
                $user_id = $order->get_order_key();

                $user               = new \stdClass();
                $user->user_login   = $order->get_billing_first_name() . ' ' . $order->get_billing_last_name();
                $user->display_name = $order->get_billing_first_name() . ' ' . $order->get_billing_last_name();
                $user->first_name   = $order->get_billing_first_name();
                $user->last_name    = $order->get_billing_last_name();
                $user->user_email   = $order->get_billing_email();
                $user->ID           = $user_id;
                $user->user_role    = esc_html__( 'Anonymous user', 'integrate-google-drive-premium' );
            }

            $args['user']     = $user;
            $args['wc_order'] = $order;
        }

        $folder = PrivateFolders::instance()->create_folder( $args );

        if ( ! empty( $order ) ) {
            //get order item id by product id
            $order_item_id = $this->get_order_item_id_by_product_id( $order, $product_id );

            if ( $order_item_id ) {
                wc_update_order_item_meta( $order_item_id, '_igd_upload_folder', $folder );
            }

        } else {
            WC()->session->set( 'igd_upload_folder_' . $product_id, $folder );
        }

        return $folder;
    }

    /**
     * Check if product requires uploads
     *
     * @param \WC_Product $product
     * @param \WC_Order $order
     *
     * @return bool
     */
    public function requires_product_uploads( $product = null, $order = null ) {

        if ( empty( $product ) || ! ( $product instanceof \WC_Product ) ) {
            return false;
        }

        if ( 'variation' === $product->get_type() && ! empty( wc_get_product( $product->get_parent_id() ) ) ) {
            $product = wc_get_product( $product->get_parent_id() );
        }

        $product_id = $product->get_id();

        $uploadable = get_post_meta( $product_id, '_uploadable', true ) == 'yes';
        $igd_upload = get_post_meta( $product_id, '_igd_upload', true ) == 'yes';

        // Check if checkout page
        if ( ! $order ) {
            return $uploadable && $igd_upload;
        }

        // Order Status
        $order_status = igd_get_settings( 'wooCommerceUploadOrderStatuses', array(
                'wc-pending',
                'wc-processing',
                'wc-on-hold',
        ) );

        if ( $this->is_dokan_active() ) {
            $order_status = get_user_meta( get_post_field( 'post_author', $product_id ), '_igd_dokan_upload_order_statuses', true );
        }

        if ( ! is_array( $order_status ) ) {
            $order_status = [];
        }

        $upload_active = in_array( 'wc-' . $order->get_status(), $order_status );

        if ( is_admin() ) {
            $current_screen = get_current_screen();

            if ( ! empty( $current_screen ) && in_array( $current_screen->post_type, [ 'shop_order' ] ) ) {
                $upload_active = true;
            } elseif ( isset( $_REQUEST['type'] ) || 'wc-item-details' !== $_REQUEST['type'] ) {
                $upload_active = true;
            }
        }

        $show_upload_box = apply_filters( 'igd_wc_show_upload_field', $upload_active, $order, $product, $this );

        if ( $uploadable && $igd_upload && $show_upload_box ) {
            return true;
        }

        return false;
    }

    /**
     * Check if order requires uploads
     *
     * @param $order
     *
     * @return bool
     */
    public function requires_order_uploads( $order ) {
        if ( ! ( $order instanceof \WC_Order ) ) {
            return false;
        }

        foreach ( $order->get_items() as $order_item ) {
            $product         = $this->get_product( $order_item );
            $requires_upload = $this->requires_product_uploads( $product, $order );

            if ( $requires_upload ) {
                return true;
            }
        }

        return false;
    }

    /**
     * Get Product from Order Item
     *
     * @param $order_item
     *
     * @return false|\WC_Product
     */
    public function get_product( $order_item ) {
        $product = $order_item->get_product();

        if ( empty( $product ) || ! ( $product instanceof \WC_Product ) ) {
            return false;
        }

        return $product;
    }

    public function get_order_item_id_by_product_id( $order, $product_id ) {

        foreach ( $order->get_items() as $order_item_id => $order_item ) {
            $product = $order_item->get_product();
            if ( $product && $product->get_id() == $product_id ) {
                return $order_item_id;
            }
        }

        return 0;
    }

    /**
     * Add Uploadable Product Option to Product Data Tab
     *
     * @param $options
     *
     * @return mixed
     */
    public function add_uploadable_product_option( $options ) {
        $options['uploadable'] = [
                'id'            => '_uploadable',
                'wrapper_class' => 'show_if_simple show_if_variable',
                'label'         => __( 'Uploadable', 'integrate-google-drive-premium' ),
                'description'   => __( 'Allow customers to upload files to this product.', 'integrate-google-drive-premium' ),
                'default'       => 'no',
        ];

        return $options;
    }

    public function add_product_data_tab_content() {
        global $post;

        $igd_upload  = get_post_meta( $post->ID, '_igd_upload', true );
        $module_data = get_post_meta( $post->ID, '_igd_module_data', true );

        ?>

        <div id="upload_options" class="panel woocommerce_options_panel hidden" style="display:none">
            <div class="options_group">
                <p class="form-field">
                    <label for="_igd_upload"><?php _e( 'Show Upload Box : ', 'integrate-google-drive-premium' ); ?></label>

                    <?php echo wc_help_tip( __( 'Show upload box to allow customers to upload files for this product.', 'integrate-google-drive-premium' ) ); ?>

                    <input type="checkbox" class="checkbox" name="_igd_upload"
                           id="_igd_upload" <?php checked( $igd_upload, 'yes' ); ?> />
                </p>

                <div class="show_if_igd_upload upload-box-settings">
                    <h4><?php _e( 'Google Drive Upload Box Settings', 'integrate-google-drive-premium' ); ?></h4>

                    <!-- Configure Module -->
                    <p class="form-field upload-box-button-text-field">
                        <label for="igd_module_data"><?php _e( 'Configure Uploader : ', 'integrate-google-drive-premium' ); ?></label>


                        <input type="hidden" name="_igd_module_data" id="igd_module_data"
                               value="<?php echo esc_attr( $module_data ); ?>"/>

                        <?php

                        if ( ! empty( $module_data ) ) {
                            $decoded_data = json_decode( base64_decode( $module_data ), true );

                            if ( ! empty( $decoded_data['folders'] ) ) {

                                $folder_info = reset( $decoded_data['folders'] );

                                ?>
                                <span class="igd-upload-folder-info">
                                    <img src="<?php echo esc_attr($folder_info['iconLink']); ?>" alt="Folder Icon" class="igd-folder-icon" rel="nofollow" />
                                    <span><?php echo esc_html( $folder_info['name'] ); ?></span>
                                </span>
                                <?php
                            }
                        }


                        ?>

                        <button type="button" class="btn-primary igd-btn igd-wc-configure">
                            <i class="dashicons dashicons-admin-generic"></i>
                            <span><?php _e( 'Configure Uploader', 'integrate-google-drive-premium' ); ?></span>
                        </button>

                        <?php echo wc_help_tip( __( 'Configure the uploader to let customers upload files directly to your Google Drive for this product.', 'integrate-google-drive-premium' ) ); ?>

                    </p>

                </div>

            </div>
        </div>

        <?php
    }

    /**
     * Save uploadable product meta
     *
     * @param $post_id
     *
     * @return void
     */
    public
    function save_product_meta(
            $post_id
    ) {
        $uploadable = ! empty( $_POST['_uploadable'] ) ? 'yes' : 'no';
        $igd_upload = ! empty( $_POST['_igd_upload'] ) ? 'yes' : 'no';
        $igd_module = ! empty( $_POST['_igd_module_data'] ) ? sanitize_text_field( $_POST['_igd_module_data'] ) : '';

        update_post_meta( $post_id, '_uploadable', $uploadable );
        update_post_meta( $post_id, '_igd_upload', $igd_upload );
        update_post_meta( $post_id, '_igd_module_data', $igd_module );
    }

    public
    function get_woocommerce_upload_locations() {
        if ( ! igd_get_settings( 'wooCommerceUpload' ) ) {
            return [];
        }

        return igd_get_settings( 'wooCommerceUploadLocations', [
                'checkout',
                'order-received',
                'my-account',
        ] );
    }

    /**
     * @return WooCommerceUploads|null
     */
    public
    static function instance() {
        if ( is_null( self::$instance ) ) {
            self::$instance = new self();
        }

        return self::$instance;
    }

}

WooCommerceUploads::instance();