<?php



// If this file is called directly, abort.

if ( ! defined('ABSPATH')) {

    die;

}



/**

 * Class MP_Mass_Shipping

 */
use Automattic\WooCommerce\Utilities\OrderUtil;


class MP_Mass_Shipping

{

    /** @var WC_Order[] */

    private $orders;



    public function __construct()

    {

	    if ( MultiParcels()->permissions->isFull() ) {

		    add_action( 'admin_menu', [ $this, 'admin_menu' ], 99 );

		    // Add bulk action
            if (class_exists( \Automattic\WooCommerce\Utilities\OrderUtil::class )) {
                if ( OrderUtil::custom_orders_table_usage_is_enabled() ) {
                    // HPOS usage is enabled.
                    add_action( 'bulk_actions-woocommerce_page_wc-orders', [ $this, 'add_action' ] );
                }else {
                    // Traditional CPT-based orders are in use.
                    add_action( 'bulk_actions-edit-shop_order', [ $this, 'add_action' ] );
                }
            } else {
                // Traditional CPT-based orders are in use.
                add_action( 'bulk_actions-edit-shop_order', [ $this, 'add_action' ] );
            }




		    // Catch the action
            if (class_exists( \Automattic\WooCommerce\Utilities\OrderUtil::class )) {
                if ( OrderUtil::custom_orders_table_usage_is_enabled() ) {
                    // HPOS usage is enabled.
                    add_filter( 'handle_bulk_actions-woocommerce_page_wc-orders', [ $this, 'do_action' ], 10, 3 );
                }else {
                    // Traditional CPT-based orders are in use.
                    add_filter( 'handle_bulk_actions-edit-shop_order', [ $this, 'do_action' ], 10, 3 );
                }
            }else {
                // Traditional CPT-based orders are in use.
                add_filter( 'handle_bulk_actions-edit-shop_order', [ $this, 'do_action' ], 10, 3 );
            }
	    }

    }



    public function admin_menu()

    {
        // Add page without menu link

        add_submenu_page(null, 'MultiParcels', 'MultiParcels', 'manage_woocommerce',

            'multiparcels-shipping-for-woocommerce-mass-shipping', [$this, 'page']);

    }



    function page()

    {
        $set_nonce = wp_create_nonce('_wpnonce2');

        if ( ! wp_verify_nonce( $set_nonce, '_wpnonce2' ) ) {
            return;
        }



	    $shipping_id = MultiParcels()->shippings->create( [], $_GET['ids'] );

	    if (MultiParcels()->options->get_other( 'skip_extra_step_when_mass_shipping' )) {

            wp_redirect( MP_Amazing_shipping::link() . '&start=' . $shipping_id );

            exit;

        }

        wp_redirect( MP_Amazing_shipping::link() );

        exit;

    }



    /**

     * @param array $order_meta

     *

     * @return bool

     */

    public function is_confirmed($order_meta)

    {
        if (class_exists( \Automattic\WooCommerce\Utilities\OrderUtil::class )) {
            if( OrderUtil::custom_orders_table_usage_is_enabled() ) {
                if (array_key_exists(MP_Woocommerce_Order_Shipping::CONFIRMED_KEY, $order_meta)) {
                    $confirmed = $order_meta[MP_Woocommerce_Order_Shipping::CONFIRMED_KEY];

                    if ($confirmed) {
                        return true;
                    }
                }
            }else {
                if (array_key_exists(MP_Woocommerce_Order_Shipping::CONFIRMED_KEY, $order_meta)) {
                    $confirmed = $order_meta[MP_Woocommerce_Order_Shipping::CONFIRMED_KEY][0];

                    if ($confirmed) {
                        return true;
                    }
                }
            }
        } else {
            if (array_key_exists(MP_Woocommerce_Order_Shipping::CONFIRMED_KEY, $order_meta)) {
                $confirmed = $order_meta[MP_Woocommerce_Order_Shipping::CONFIRMED_KEY][0];

                if ($confirmed) {
                    return true;
                }
            }
        }


        return false;

    }



    /**

     * @param array $order_meta

     *

     * @return array

     */

    public function get_errors($order_meta)

    {
        if (class_exists( \Automattic\WooCommerce\Utilities\OrderUtil::class )) {
            if ( OrderUtil::custom_orders_table_usage_is_enabled() ) {
                // HPOS usage is enabled.
                if (array_key_exists(MP_Woocommerce_Order_Shipping::ERRORS_KEY, $order_meta)) {
                    $errors = $order_meta[MP_Woocommerce_Order_Shipping::ERRORS_KEY];
                    if ($errors) {
                        return json_decode($errors, true);
                    }
                }
            }else {
                // Traditional CPT-based orders are in use.
                if (array_key_exists(MP_Woocommerce_Order_Shipping::ERRORS_KEY, $order_meta)) {
                    $errors = $order_meta[MP_Woocommerce_Order_Shipping::ERRORS_KEY][0];
                    if ($errors) {
                        return json_decode($errors, true);
                    }
                }
            }
        } else {
            // Traditional CPT-based orders are in use.
            if (array_key_exists(MP_Woocommerce_Order_Shipping::ERRORS_KEY, $order_meta)) {
                $errors = $order_meta[MP_Woocommerce_Order_Shipping::ERRORS_KEY][0];
                if ($errors) {
                    return json_decode($errors, true);
                }
            }
        }




        return [];

    }



    /**

     * @param array $actions

     *

     * @return mixed

     */

    public function add_action($actions)

    {

        $actions['multiparcels_mass_confirm'] = __('Dispatch selected orders', 'multiparcels-shipping-for-woocommerce');



        return $actions;

    }



    /**

     * @param $redirect_to

     * @param $action

     * @param $ids

     *

     * @return string

     */

    public function do_action($redirect_to, $action, $ids)

    {

        if ($action != 'multiparcels_mass_confirm') {

            return $redirect_to;

        }



        $base = admin_url('admin.php?page=multiparcels-shipping-for-woocommerce-mass-shipping');



        wp_redirect(add_query_arg([

	        'ids' => $ids,

        ], $base));

        exit;

    }



    private function load_orders($ids)

    {

        foreach ($ids as $order_id) {

            $order          = [];

            $order['order'] = wc_get_order($order_id);

            if (class_exists( \Automattic\WooCommerce\Utilities\OrderUtil::class )) {
                if (OrderUtil::custom_orders_table_usage_is_enabled()) {
                    $order['meta']  = $order['order']->get_meta_data();
                }else {
                    $order['meta']  = get_post_meta($order_id);
                }
            } else {
                $order['meta']  = get_post_meta($order_id);
            }
            $order['id']    = $order['order']->get_id();

            $this->orders[] = $order;

        }

    }



    private function confirm_order($order)

    {
        $shipping = new MP_Woocommerce_Order_Shipping();

        $shipping->load_order($order['id']);



        if ( ! $shipping->is_confirmed()) {

            $shipping->ship_order($order['id'], [], false);

        }

    }



    private function print_orders()

    {

        $external_ids = [];



        foreach ($this->orders as $order) {

            if (array_key_exists('multiparcels_external_id', $order['meta'])) {

                if (class_exists( \Automattic\WooCommerce\Utilities\OrderUtil::class )) {
                    if( OrderUtil::custom_orders_table_usage_is_enabled() ) {
                        // HPOS is enabled.
                        $external_ids[] = $order['meta']['multiparcels_external_id'];
                    }else {
                        // CPT-based orders are in use.
                        $external_ids[] = $order['meta']['multiparcels_external_id'][0];
                    }
                } else {
                    // CPT-based orders are in use.
                    $external_ids[] = $order['meta']['multiparcels_external_id'][0];
                }


            }

        }



        if (count($external_ids)) {

//            $response = MultiParcels()->api_client->request('batch_labels', 'POST', [
//
//                'shipments' => $external_ids,
//
//            ]);


            $response = MultiParcels()->api_client->request('api/translate/mp/batch_labels', 'POST', [

                'shipments' => $external_ids,

            ]);



            if ($response->was_successful()) {

                $file_name = sprintf("labels_%d.pdf", mt_rand(10000, 99999));

//                $upload    = wp_upload_bits($file_name, null, base64_decode($response->get_data()['content']));

                $labels_content = base64_decode($response->get_data()['content']);

                // Create a unique filename
                $labels_directory = WP_CONTENT_DIR . '/plugins/multiparcels-shipping-for-woocommerce/shipments_labels/';

                // Create the directory if it doesn't exist
                if (!file_exists($labels_directory)) {
                    mkdir($labels_directory, 0755, true);
                }

//                if (file_exists($labels_directory . $file_name)) {
//                    $file_path = $labels_directory . $file_name;
//                    unlink($file_path);
//                }

                // Save the labels to the directory
//                            $upload = wp_upload_bits($file_name, null, base64_decode($label_data['content']));
                $result = file_put_contents($labels_directory . $file_name, $labels_content);

//                $upload_url = content_url() . '/plugins/multiparcels-shipping-for-woocommerce/shipments_labels/' . $file_name;
                //$upload_url = content_url() . '/plugins/multiparcels-shipping-for-woocommerce/serve_label.php?file=' . $file_name;
                $upload_url = admin_url() . 'admin-post.php?action=serve_label&file=' . $file_name;

//                header('Location: ' . $upload['url']);

                header('Location: ' . $upload_url);

                exit;

            }

        }

    }

}



return new MP_Mass_Shipping();

