<?php
/**
 * EMC Shipping Data
 *
 * Functions for displaying the EMC shipping data meta box.
 *
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

/**
 * EMC_Meta_Box_Order_Shipping Class
 */
class EMC_Meta_Box_Order_Shipping {

    /**
     * Actual order
     *
     * @var mixed
     */
    protected static $order = false;

    /**
     * Actual order's items
     *
     * @var mixed
     */
    protected static $items = false;

    /**
     * Actual emc offer for this order
     *
     * @var mixed
     */
    protected static $emc_offer = false;

    /**
     * Actual emc carrier for this order
     *
     * @var mixed
     */
    protected static $emc_carrier = false;

    /**
     * Pickup point field
     *
     * @var array
     */
    protected static $parcel_pickup_point = array();

    /**
     * Pickup point field
     *
     * @var array
     */
    protected static $parcel_dropoff_point = array();

    /**
     * Insurance field
     *
     * @var array
     */
    protected static $insurance = array();

    /**
     * Pickup date field
     *
     * @var array
     */
    protected static $pickup_date = array();

    /**
     * Dimension fields
     *
     * @var array
     */
    protected static $dimensions = array();

    /**
     * Content description fields
     *
     * @var array
     */
    protected static $content_description = array();

  /**
     * Content description fields
     *
     * @var array
     */
    protected static $shipping_international = array();

    /**
     * Init shipping info fields we display + save
     */
    public static function init_shipping_info($order, $multiparcels) {

        $items = $order->get_items( apply_filters( 'woocommerce_admin_order_item_types', 'line_item' ) ); // items in order
        $fields = array();

        foreach ($multiparcels as $multiparcel_info) {

            $suborder_key = $multiparcel_info['suborder_key'];

            $international_filter = array();

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

                $international_filter['proforma_post_title_en'] = array(
                    'label' => __( 'Describe your goods (English):', 'envoimoinscher' ),
                    'show'  => true,
                );

                $international_filter['proforma_post_title_fr'] = array(
                    'label' => __( 'Describe your goods (language of the country of origin):', 'envoimoinscher' ),
                    'show'  => true,
                );

                $international_filter['proforma_qty'] = array(
                    'label' => __( 'Quantity:', 'envoimoinscher' ),
                    'show'  => true,
                );

                $international_filter['proforma_price'] = array(
                    'label' => __( 'Unit price:', 'envoimoinscher' ),
                    'unit'  => '€',
                    'show'  => true,
                );

                $international_filter['proforma_origin'] = array(
                    'label' => __( 'Country:', 'envoimoinscher' ),
                    'show'  => true,
                );

                $international_filter['proforma_weight'] = array(
                    'label' => __( 'Unit weight:', 'envoimoinscher' ),
                    'unit'  => 'kg',
                    'show'  => true,
                );
            }


            $dims = array();
            // check if there is a new parcel number posted
            $nb_parcels = isset($_POST['nb_parcels_'.$suborder_key])?(int)$_POST['nb_parcels_'.$suborder_key]:count($multiparcel_info['parcels']);
            for($i = 1 ; $i <= $nb_parcels ; $i++)
            {
                $dims[$i] = array(
                   '_dims_'.$i.'_weight' => array(
                       'label' => __( 'Total shipping weight:', 'envoimoinscher' ),
                       'label_simple'  => __( 'weight', 'envoimoinscher' ),
                       'unit'  => 'kg',
                       'class'  => '_dims_weight',
                       'show'  => true,
                   ),
                   '_dims_'.$i.'_width' => array(
                       'label' => __( 'Total shipping width:', 'envoimoinscher' ),
                       'label_simple'  => __( 'width', 'envoimoinscher' ),
                       'unit'  => 'cm',
                       'class'  => '_dims_width',
                       'show'  => true,
                   ),
                   '_dims_'.$i.'_length' => array(
                       'label' => __( 'Total shipping length:', 'envoimoinscher' ),
                       'label_simple'  => __( 'length', 'envoimoinscher' ),
                       'unit'  => 'cm',
                       'class'  => '_dims_length',
                       'show'  => true,
                   ),
                   '_dims_'.$i.'_height' => array(
                       'label' => __( 'Total shipping height:', 'envoimoinscher' ),
                       'label_simple'  => __( 'height', 'envoimoinscher' ),
                       'unit'  => 'cm',
                       'class'  => '_dims_height',
                       'show'  => true,
                   ),
               );
            }

            $fields[$suborder_key] = array(
                'dimensions' => $dims,
                'content_description' => array(
                    '_desc_content' => array(
                        'label' => __( 'Content description:', 'envoimoinscher' ),
                        'show'  => true,
                    ),
                    '_desc_value' => array(
                        'label' => __( 'Declared content value:', 'envoimoinscher' ),
                        'show'  => true,
                    ),
                    '_wrapping' => array(
                        'label' => __( 'Packaging:', 'envoimoinscher' ),
                        'options' => array( '1-Boîte' => __( 'Box', 'envoimoinscher' ), '17-Tube' => __( 'Tube', 'envoimoinscher' )),
                        'show'  => true,
                    ),
                ),
                'parcel_pickup_point' => array(
                    '_pickup_point' => array(
                            'label' => __( 'Customer pickup point:', 'envoimoinscher' ),
                            'show'  => true,
                    ),
                ),
                'parcel_dropoff_point' => array(
                    '_dropoff_point' => array(
                        'label' => __( 'Dropoff point:', 'envoimoinscher' ),
                        'show'  => true,
                    ),
                ),
                'insurance' => array(
                    '_insurance' => array(
                        'label' => __( 'Insure this shipment with AXA', 'envoimoinscher' ),
                        'show'  => true,
                    ),
                ),
                'pickup_date' => array(
                    '_pickup_date' => array(
                        'label' => __( 'Departure date:', 'envoimoinscher' ),
                        'show'  => true,
                    ),
                ),
                'shipping_international' => array(
                    '_proforma_reason' => array(
                        'label'    => __( 'Reason for your shipment *', 'envoimoinscher' ),
                        'class'       => 'proforma_reason',
                        'name'       => 'proforma_reason',
                        'type'     => 'select',
                        'options'  => array(
                            'sale'      => __( 'Sale', 'envoimoinscher' ),
                            'repair'    => __( 'Repair', 'envoimoinscher' ),
                            'return'    => __( 'Return', 'envoimoinscher' ),
                            'present'   => __( 'Present, gift', 'envoimoinscher' ),
                            'sample'    => __( 'Sample, model', 'envoimoinscher' ),
                            'personal'  => __( 'Personal use', 'envoimoinscher' ),
                            'company'   => __( 'Inter-company documents', 'envoimoinscher' ),
                            'other'     => __( 'Other', 'envoimoinscher' )
                        ),
                        'show'  => true,
                        'required' => true
                    ),
                    '_proforma_items' => array(
                        'proforma_post_title_en' => array(
                            'label' => __( 'Description of your goods (English):', 'envoimoinscher' ),
                            'show'  => true,
                        ),
                        'proforma_post_title_fr' => array(
                            'label' => __( 'Description of your goods (language of the country of origin):', 'envoimoinscher' ),
                            'show'  => true,
                        ),
                        'proforma_qty' => array(
                            'label' => __( 'Quantity:', 'envoimoinscher' ),
                            'show'  => true,
                        ),
                        'proforma_price' => array(
                            'label' => __( 'Unit price:', 'envoimoinscher' ),
                            'unit'  => '€',
                            'show'  => true,
                        ),
                        'proforma_origin' => array(
                            'label' => __( 'Country:', 'envoimoinscher' ),
                            'show'  => true,
                        ),
                        'proforma_weight' => array(
                            'label' => __( 'Unit weight:', 'envoimoinscher' ),
                            'unit'  => 'kg',
                            'show'  => true,
                        )
                    )
                )
            );
        }

        return $fields;
    }

    private static function output_header() {
        ?>
            <style type="text/css">
                #post-body-content, #titlediv, #major-publishing-actions, #minor-publishing-actions, #visibility, #submitdiv { display:none }
            </style>
            <div class="panel-wrap woocommerce">
                <div class="panel">
                    <button class="button-primary"><?php _e( 'Save orders and update rates', 'envoimoinscher' ); ?></button>
                    <a id="add-shipment" class="button"><?php _e( 'Add a shipment', 'envoimoinscher' ); ?></a>
                    <a id="reset-shipping"><?php _e( 'Reinitialize shipping options', 'envoimoinscher' ); ?></a>
        <?php
    }

    private static function output_footer() {
        ?>
                </div>
            </div>
        <?php
    }

    /**
     * Output the metabox
     */
    public static function output( $post ) {

        /* Process order */
        // get the actual order
        global $the_order, $wpdb;
        if ( ! is_object( $the_order ) ) {
            $order = envoimoinscher_model::envoimoinscher_get_order( $post->ID );
        }
        else {
            $order = $the_order;
        }
        $order_id = envoimoinscher_model::envoimoinscher_get_order_id($order);

        // get offers for all addresses (function also initializes order values)
        $offers = envoimoinscher_model::check_rates_from_order($order);
        
        // get values
        $items = $order->get_items( apply_filters( 'woocommerce_admin_order_item_types', 'line_item' ) ); // items in order
        $activated_services = envoimoinscher_model::get_enabled_shipping_methods(); // activated emc services
        $methods = WC()->shipping()->get_shipping_methods(); // all WC complete methods
        $chosen_carrier_array = get_post_meta( $order_id, '_emc_carrier', true );
        $emc_ref_array = get_post_meta( $order_id, '_emc_ref', true );
        $carrier_ref_array = get_post_meta( $order_id, '_carrier_ref', true );
        $label_url_array = get_post_meta( $order_id, '_label_url', true );
        $remise_array = get_post_meta( $order_id, '_remise', true );
        $manifest_array = get_post_meta( $order_id, '_manifest', true );
        $connote_array = get_post_meta( $order_id, '_connote', true );
        $proforma_array = get_post_meta( $order_id, '_proforma', true );
        $b13a_array = get_post_meta( $order_id, '_b13a', true );
        $desc_value_array = get_post_meta( $order_id, '_desc_value', true);
        $desc_content_array = get_post_meta( $order_id, '_desc_content', true);
        $wrapping_array = get_post_meta( $order_id, '_wrapping', true);
        $pickup_point_array = get_post_meta( $order_id, '_pickup_point', true);
        $dropoff_point_array = get_post_meta( $order_id, '_dropoff_point', true);
        $pickup_date_array = get_post_meta( $order_id, '_pickup_date', true);
        $insurance_array = get_post_meta( $order_id, '_insurance', true);
        $addressbook = envoimoinscher_model::get_addresses("all", true);
        $default_insurance_options = array(
            '_assurance_emballage' => get_post_meta( $order_id, '_assurance_emballage', true),
            '_assurance_materiau' => get_post_meta( $order_id, '_assurance_materiau', true),
            '_assurance_protection' => get_post_meta( $order_id, '_assurance_protection', true),
            '_assurance_fermeture' => get_post_meta( $order_id, '_assurance_fermeture', true)
        );
        $proforma_reason_array = get_post_meta( $order_id, '_proforma_reason', true);
        $proforma_items_array = get_post_meta( $order_id, '_proforma_items', true);

        // get multiparcel value (already set in check_rates_from_order if needed)
        $multiparcels = get_post_meta($order_id, '_multiparcels', true);

        // init fields
        $fields = self::init_shipping_info($order, $multiparcels); // fields for forms

        /* Start output */
        // output header
        self::output_header();

        $shipment_nb = 1;

        foreach ($multiparcels as $multiparcel_info) {

            $suborder_key = $multiparcel_info['suborder_key'];
            $address_id = $multiparcel_info['address_id'];

            // display title
            ?>
                <div class="suborder" data-suborder="<?php echo $suborder_key; ?>">
                    <div>
                        <h2><?php echo sprintf(__( 'Shipment n°%s', 'envoimoinscher' ), $shipment_nb ); ?> <span style="font-size:0.6em"><?php echo sprintf(__( '[suborder %s]', 'envoimoinscher' ), $suborder_key ); ?></span></h2>
                    </div>
                    <input type="hidden" name="emc_submit"/>
            <?php
            $shipment_nb++;

            // initialize values
            $chosen_carrier = isset($chosen_carrier_array[$suborder_key]) ? $chosen_carrier_array[$suborder_key] : ""; // selected carrier
            $emc_ref = isset($emc_ref_array[$suborder_key]) ? $emc_ref_array[$suborder_key] : ""; // emc shipment reference
            $carrier_ref = isset($carrier_ref_array[$suborder_key]) ? $carrier_ref_array[$suborder_key] : ""; // carrier shipment reference
            $label_url = isset($label_url_array[$suborder_key]) ? $label_url_array[$suborder_key] : ""; // document
            $remise = isset($remise_array[$suborder_key]) ? $remise_array[$suborder_key] : ""; // document
            $manifest = isset($manifest_array[$suborder_key]) ? $manifest_array[$suborder_key] : ""; // document
            $connote = isset($connote_array[$suborder_key]) ? $connote_array[$suborder_key] : ""; // document
            $proforma = isset($proforma_array[$suborder_key]) ? $proforma_array[$suborder_key] : ""; // document
            $b13a = isset($b13a_array[$suborder_key]) ? $b13a_array[$suborder_key] : ""; // document
            $desc_value = isset($desc_value_array[$suborder_key]) ? $desc_value_array[$suborder_key] : ""; // document
            $desc_content = isset($desc_content_array[$suborder_key]) ? $desc_content_array[$suborder_key] : ""; // document
            $wrapping = isset($wrapping_array[$suborder_key]) ? $wrapping_array[$suborder_key] : ""; // document
            $pickup_point = isset($pickup_point_array[$suborder_key]) ? $pickup_point_array[$suborder_key] : ""; // document
            $dropoff_point = isset($dropoff_point_array[$suborder_key]) ? $dropoff_point_array[$suborder_key] : ""; // document
            $pickup_date = isset($pickup_date_array[$suborder_key]) ? $pickup_date_array[$suborder_key] : ""; // document
            $insurance = isset($insurance_array[$suborder_key]) ? $insurance_array[$suborder_key] : ""; // document
            $proforma_reason = isset($proforma_reason_array[$suborder_key]) ? $proforma_reason_array[$suborder_key] : ""; // document
            $proforma_items = isset($proforma_items_array[$suborder_key]) ? $proforma_items_array[$suborder_key] : ""; // document
            $warning_rate = false;

            // sender information
            foreach($addressbook as $item) {
                if ($item['id'] == $address_id) {
                    $shipper_address = $item;
                }
                if ($item['type'] == 'default' && $item['active']) {
                    $default_address = $item;
                }
            }
            // check if address is inactive
            $is_active = envoimoinscher_model::is_address_active($address_id);
            if (!$is_active) {
                $shipper_address = $default_address; // used only for relay map display
                $warning_rate = true; // display rate warning
            }

            // Get the selected service
            if ( $chosen_carrier == "" ) {
                foreach($order->get_shipping_methods() as $value){
                    $carrier_code = $value['method_id'];
                }
                echo '<h4 class="red">'.__( 'You must first select a Boxtal carrier in order to send this order with us.', 'envoimoinscher' ).'</h4>';
            } else {
                $carrier_code = $chosen_carrier;
                $carrier_settings = get_option('woocommerce_'.$carrier_code.'_settings');

                // Get the associated carrier object
                $emc_carrier = isset($methods[$carrier_code]) ? $methods[$carrier_code] : false;
                
                // Load the EMC service
                $service = envoimoinscher_model::get_service_by_carrier_code($carrier_code);
            }
            
            // get tracking url according to branding
            $tracking_url = "http://www.envoimoinscher.com/suivi-colis.html?reference=";
            if (get_option('EMC_COUNTRY') == "ES") {
                $tracking_url = "http://www.boxtal.es/seguimiento-paquete.html?reference=";
            } else {
                $tracking_url = "http://www.envoimoinscher.com/suivi-colis.html?reference=";
            }

            if(!isset($offers[$suborder_key])) {
                // case curl error
                echo '<div class="red">' . $offers . '</div>';
            } elseif( is_array( $offers[$suborder_key] ) ) {
                if ( isset ( $offers[$suborder_key][$carrier_code] ) ) {
                    // case offer is found
                    $emc_offer = $offers[$suborder_key][$carrier_code];
                    $rate = $emc_offer['price']['tax-exclusive'] ;
                    if ( isset ($emc_offer['options']['assurance']['parameters']) ) {
                        $insurance_options = $emc_offer['options']['assurance']['parameters'];
                        $insurance_price = (float)$emc_offer['insurance']['tax-exclusive'];
                    }
                }
            } else {
                // case resp error
                echo '<div class="red">' . $offers[$suborder_key] . '</div>';
            }

            ?>
                <!-- case : parcel already sent -->
                <?php if( $emc_ref != "" ) : ?>
                    <div class="already_sent">
                        <div class="reference">
                            <span class="green"><?php _e( 'Your order has already been sent.', 'envoimoinscher' ); ?></span>
                            <?php echo '<div class="emc_ref">' . sprintf(__( 'Boxtal reference: %s.', 'envoimoinscher' ), '<a href="' . $tracking_url . $emc_ref . '" target="_blank">' . $emc_ref . '</a>' ) . '</div>'; ?>
                            <?php
                                if ( $carrier_ref != "" ) {
                                    echo '<div class="carrier_ref">';
                                    echo sprintf(__( 'Customer tracking number (available in the front-office > order view page): %s.', 'envoimoinscher' ), $carrier_ref ) . '</div>';
                                }
                            ?>
                        </div>
                        <!-- document links -->
                        <div class="emc_documents <?php if ( $label_url_array ) echo 'labels_available'; ?>">
                            <div class="label_url" <?php if ($label_url == "") echo 'style="display:none"'; ?>><?php echo sprintf(__('Your waybill is available. Download it %s.', 'envoimoinscher' ), '<a href="#">' . __('here', 'envoimoinscher') . '</a>' ); ?></div>
                            <div class="remise" <?php if ($remise == "") echo 'style="display:none"'; ?>><?php echo sprintf(__('Your delivery waybill is available. Download it %s.', 'envoimoinscher' ), '<a href="#">' . __('here', 'envoimoinscher') . '</a>' ); ?></div>
                            <div class="manifest" <?php if ($manifest == "") echo 'style="display:none"'; ?>><?php echo sprintf(__('Your manifest is available. Download it %s.', 'envoimoinscher' ), '<a href="'.$manifest.'" target="_blank">' . __('here', 'envoimoinscher') . '</a>' ); ?></div>
                            <div class="connote" <?php if ($connote == "") echo 'style="display:none"'; ?>><?php echo sprintf(__('Your connote is available. Download it %s.', 'envoimoinscher' ), '<a href="'.$connote.'" target="_blank">' . __('here', 'envoimoinscher') . '</a>' ); ?></div>
                            <div class="proforma" <?php if ($proforma == "") echo 'style="display:none"'; ?>><?php echo sprintf(__('Your pro-forma invoice is available. Download it %s.', 'envoimoinscher' ), '<a href="'.$proforma.'" target="_blank">' . __('here', 'envoimoinscher') . '</a>' ); ?></div>
                            <div class="b13a" <?php if ($b13a == "") echo 'style="display:none"'; ?>><?php echo sprintf(__('Your B13A export declaration is available. Download it %s.', 'envoimoinscher' ), '<a href="'.$b13a.'" target="_blank">' . __('here', 'envoimoinscher') . '</a>' ); ?></div>
                        </div>
                    </div>
                <?php endif; ?>

                <div class="rates">
                    <?php if (!isset($emc_offer)) { ?>
                        <div class="type red"><?php _e( 'The carrier selection is no longer valid for this order, please select another and click on "Update rate"', 'envoimoinscher' ); ?> </div>
                    <?php } else { ?>
                        <div class="type">
                            <?php _e( 'Your current rate is:', 'envoimoinscher' ); ?> <span class="display_rate"><?php echo wc_price( $rate, array('ex_tax_label'=>true) ); ?></span>
                            <span style="color:red;<?php if ($warning_rate !== true) echo "display:none"; ?>;font-size:0.8em;" class="warning_rate"><?php _e( 'Please save your order to update your rate', 'envoimoinscher' ); ?></span>
                        </div>
                    <?php } ?>
                    <span class="current_rate"><?php echo $rate; ?></span>
                </div>

                <!-- carrier selection -->
                <div class="carrier_select">
                    <h4><?php _e( 'Chosen carrier', 'envoimoinscher' ); ?></h4>
                    <select name="_emc_carrier_<?php echo $suborder_key; ?>" class="_emc_carrier">
                        <?php
                            if (is_array($offers[$suborder_key]) && count($offers[$suborder_key]) > 0) {
                                if ( $chosen_carrier == "" ) echo '<option>' . __( 'Please select a carrier', 'envoimoinscher' ) . '</option>';
                                foreach( $offers[$suborder_key] as $key => $value ) {
                                    echo '<option value="'.$key.'" ';
                                    if ( $key == $chosen_carrier ) echo 'selected';
                                    echo '>'.$value['operator']['label'].' ('.$value['service']['label'].') - '.wc_price( $value['price']['tax-exclusive'], array('ex_tax_label'=>true) ).'</option>';
                                }
                            } else {
                                echo '<option>' . __( 'No offer found', 'envoimoinscher' ) . '</option>';
                            }
                        ?>
                    </select>
                </div><!-- eod carrier_select -->

                <!-- address selection -->
                <div class="address_select">
                    <h4><?php _e( 'Pick-up address', 'envoimoinscher' ); ?></h4>
                    <select name="_address_select_<?php echo $suborder_key; ?>" class="_address_select <?php if (!$is_active) echo "border-red"; ?>">
                        <?php
                            if (!$is_active) {
                                echo '<option value="" selected>'.__('Please choose a new address', 'envoimoinscher').'</option>';
                            }
                            foreach( $addressbook as $address ) {
                                echo '<option value="'.$address['id'].'" ';
                                if ( $address['id'] == $address_id ) echo 'selected';
                                echo '>'.$address['label'].'</option>';
                            }
                        ?>
                    </select>
                </div><!-- eod address_select -->

                <!-- address selection -->
                <div class="order_actions">
                    <span class="sending" style="display:none"><img src="<?php echo plugins_url( '/assets/img/loading.gif', EMC_PLUGIN_FILE ); ?>" /></span>
                    <button class="button-primary send-shipment" <?php if ($warning_rate === true || $chosen_carrier == '' || $emc_ref != "" || (is_array($offers[$suborder_key]) && count($offers[$suborder_key]) == 0))  echo "disabled" ?>><?php _e( 'Send this shipment', 'envoimoinscher' ); ?></button>
                    <button class="button delete-shipment"><?php _e( 'Delete this shipment', 'envoimoinscher' ); ?></button>
                </div><!-- eod address_select -->

                <div class="order_shipping_column_container">

                    <div class="order_shipping_column">


                        <h4><?php _e( 'Shipment information', 'envoimoinscher' ); ?> <a class="edit_shipment_info" href="#"><img src="<?php echo WC()->plugin_url(); ?>/assets/images/icons/edit.png" alt="<?php _e( 'Edit', 'envoimoinscher' ); ?>" width="14" /></a></h4>

                        <!-- display values -->
                        <div class="shipment_info">

                            <?php
                                foreach ( $fields[$suborder_key]['content_description'] as $key => $field ) {
                                    if ( isset( $field['show'] ) && false === $field['show'] ) {
                                        continue;
                                    }
                                    if( $key == '_desc_value' ) {
                                        $value = wc_price( $desc_value, array('ex_tax_label'=>true) );
                                        echo '<p class="form-field form-field-wide"><span>'. $field['label'] . ' <span class="desc_value_replace">'. $value .'</span></span></p>';
                                    } elseif ( $key == '_desc_content' ) {
                                        echo '<p class="form-field form-field-wide"><span>'. $field['label'] . ' '. $desc_content .'</span></p>';
                                    } elseif ( $key == '_wrapping' && ( isset($service) && $service->ope_code == 'POFR' )) {
                                        $value = isset($field['options'][$wrapping]) ? $field['options'][$wrapping] : '';
                                        echo '<p class="form-field form-field-wide"><span>'. $field['label'] . ' '. $value .'</span></p>';
                                    }
                                }

                                foreach ( $fields[$suborder_key]['parcel_pickup_point'] as $key => $field ) {
                                    if ( isset( $field['show'] ) && false === $field['show'] ) {
                                        continue;
                                    }

                                    echo '<p class="form-field form-field-wide parcel_pickup_point" ';
                                    if( isset($service) && $service->srv_pickup_point != 1) {
                                        echo 'style="display:none"';
                                    }
                                    echo '><span>'. $field['label'] . ' ';

                                    echo '<span class="field_replace">'. $pickup_point . '</span></span></p>';
                                }

                                foreach ( $fields[$suborder_key]['parcel_dropoff_point'] as $key => $field ) {
                                    if ( isset( $field['show'] ) && false === $field['show'] ) {
                                        continue;
                                    }

                                    echo '<p class="form-field form-field-wide parcel_dropoff_point" ';
                                    if( isset($service) && $service->srv_dropoff_point != 1) {
                                        echo 'style="display:none"';
                                    }
                                        
                                    echo '><span>'. $field['label'] . ' ';

                                    echo '<span class="field_replace">'. $dropoff_point . '</span></span></p>';
                                }

                            ?>
                        </div><!-- eod shipment_info -->

                        <!-- display form -->
                        <div class="edit_shipment_info">

                            <?php
                            foreach ( $fields[$suborder_key]['content_description'] as $key => $field ) {
                                echo '<div class="form-field ';
                                if ( $key != '_wrapping') {
                                    echo 'form-field-wide';
                                }
                                echo '"><span>';
                                if( $key == '_desc_content' ) {
                                    echo '<span>'.$field['label'].'</span> ';
                                    echo '<textarea name="'.$key.'_'.$suborder_key.'" class="'.$key.'">'.$desc_content.'</textarea>';
                                } elseif( $key == '_desc_value' ) {
                                    echo '<span>'.$field['label'].'</span> ';
                                    echo '<input type="text" name="'.$key.'_'.$suborder_key.'" class="'.$key.'" value="'.$desc_value.'" size=3 /> €';
                                } elseif ( $key == '_wrapping' && ( isset($service) && $service->ope_code == 'POFR' )) {
                                    echo '<span>'.$field['label'].'</span> ';
                                    echo '<select name="'.$key.'_'.$suborder_key.'" class="'.$key.'">';
                                    foreach ($field['options'] as $o => $option) {
                                        echo '<option value="'.$o.'" ';
                                        if ($o == $wrapping) {
                                            echo 'selected="selected"';
                                        }
                                        echo '>'.$option.'</option>';
                                    }
                                    echo '</select>';
                                }
                                echo '</span></div>';
                            }

                            $admin_url = admin_url();
                            $base_url = $admin_url."/admin-ajax.php?action=get_choix_relais&";
                            foreach ( $fields[$suborder_key]['parcel_pickup_point'] as $key => $field ) {
                                echo '<div class="form-field form-field-wide parcel_pickup_point" ';
                                if( isset($service) && $service->srv_pickup_point != 1) {
                                    echo 'style="display:none"';
                                }
                                echo'><span><span>'.$field['label'].'</span> ';
                                echo '<input type="text" class="input_replace" name="'.$key.'_'.$suborder_key.'" id="'.$key.'_'.$suborder_key.'" value="'.$pickup_point.'" size=8 /> </span><br/>';
                                echo '<a rel="'.$key.'" class="iframe" href="'.$base_url.'collecte=dest&cp='.envoimoinscher_model::envoimoinscher_get_order_property($order, 'shipping_postcode').'&ville='.envoimoinscher_model::envoimoinscher_get_order_property($order, 'shipping_city').'&country='.envoimoinscher_model::envoimoinscher_get_order_property($order, 'shipping_country').'&srv='.$service->srv_code.'&ope='.$service->ope_code.'&inputCallBack='.$key.'_'.$suborder_key.'">'.__( 'Get code', 'envoimoinscher' ).'</a></div>';
                            }

                            foreach ( $fields[$suborder_key]['parcel_dropoff_point'] as $key => $field ) {
                                echo '<div class="form-field form-field-wide parcel_dropoff_point" ';
                                if( isset($service) && $service->srv_dropoff_point != 1) {
                                    echo 'style="display:none"';
                                }
                                echo '><span><span>'.$field['label'].'</span> ';
                                echo '<input type="text" class="input_replace" name="'.$key.'_'.$suborder_key.'" id="'.$key.'_'.$suborder_key.'" value="'.$dropoff_point.'" size=8 /> </span><br/>';
                                echo '<a rel="'.$key.'" class="iframe" href="'.$base_url.'collecte=exp&cp='.$shipper_address['zipcode'].'&ville='.stripslashes($shipper_address['city']).'&country='.get_option('EMC_COUNTRY', 'FR').'&srv='.$service->srv_code.'&ope='.$service->ope_code.'&inputCallBack='.$key.'_'.$suborder_key.'">'.__( 'Get code', 'envoimoinscher' ).'</a></div>';
                            }
                            ?>

                        </div><!-- eod edit_shipment_info -->

                        <div>
                            <?php
                                foreach ( $fields[$suborder_key]['pickup_date'] as $key => $field ) {
                                    if ( isset( $field['show'] ) && false === $field['show'] ) {
                                        continue;
                                    }
                                    ?>
                                        <p class="form-field form-field-wide"><span><?php echo $field['label']; ?></span>
                                            <input type="text" class="date-picker <?php echo $key; ?>" name="<?php echo $key.'_'.$suborder_key;?>" id="<?php echo $key.'_'.$suborder_key;?>" maxlength="10" value="<?php echo date_i18n( 'Y-m-d', $pickup_date ); ?>" pattern="[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|1[0-9]|2[0-9]|3[01])" />
                                        </p>
                                    <?php
                                }
                            ?>
                        </div><!-- eod pickup_date -->

                    </div><!-- eod order_shipping_column -->

                    <div class="order_shipping_column">
                        <h4><?php _e( 'Dimensions', 'envoimoinscher' ); ?> <a class="edit_dimensions" href="#"><img src="<?php echo WC()->plugin_url(); ?>/assets/images/icons/edit.png" alt="<?php _e( 'Edit', 'envoimoinscher' ); ?>" width="14" /></a></h4>

                        <!-- display values -->
                        <div class="dimensions">
                            <?php
                                foreach($fields[$suborder_key]['dimensions'] as $i => $dimensions)
                                {
                                    echo '<p class="form-field form-field-wide">'.__('Parcel','envoimoinscher').' '.$i.' :</p>';
                                    foreach ( $dimensions as $key => $field ) {
                                        if ( isset( $field['show'] ) && false === $field['show'] ) {
                                            continue;
                                        }

                                        echo '<p class="form-field form-field-wide"><span>'. $field['label'] . ' ';

                                        if( isset($multiparcel_info["parcels"][$i][str_replace('_dims_'.$i.'_', '', $key)]) && $multiparcel_info["parcels"][$i][str_replace('_dims_'.$i.'_', '', $key)]) {
                                            echo '<span><span class="'.str_replace('_dims_'.$i.'_', '', $key).' '.$key.'">'. $multiparcel_info["parcels"][$i][str_replace('_dims_'.$i.'_', '', $key)] .'</span> '. $field['unit'] . '</span></span></p>';
                                        }
                                        else{
                                            if (strpos($key, 'weight') !== false) {
                                                // for french translation
                                                echo '<span style="color:red">'. __( 'No weight defined yet.', 'envoimoinscher' ) .'</span></span></p>';
                                            } else {
                                                echo '<span style="color:red">'. sprintf( __( 'No %s defined yet.', 'envoimoinscher' ), $field['label_simple'] ) .'</span></span></p>';
                                            }
                                        }
                                    }
                                }
                            ?>
                        </div><!-- eod dimensions -->

                        <!-- display form -->
                        <div class="edit_dimensions">
                            <input type="hidden" name="nb_parcels_<?php echo $suborder_key; ?>" class="emc-nb-parcels_<?php echo $suborder_key; ?>" value="<?php echo count($fields[$suborder_key]['dimensions']); ?>"/>
                            <?php
                            foreach($fields[$suborder_key]['dimensions'] as $i => $dimensions)
                            {
                                echo '<div class="emc-parcel"><p class="form-field form-field-wide">'.__('Parcel','envoimoinscher').' <span class="parcel-id">'.$i.'</span> <a '.((count($fields[$suborder_key]['dimensions'])<=1)?'style="display:none;"':'').' class="remove-parcel">('.__('remove','envoimoinscher').')</a> :</p>';
                                foreach ( $dimensions as $key => $field ) {
                                    echo '<div class="form-field form-field-wide"><span><span>'.$field['label'].'</span> ';
                                    echo '<input type="text" class="'.$key.' '.$field['class'].'" data-name-template="'.str_replace('_dims_'.$i,'_dims_{id}',$key.'_'.$suborder_key).'" name="'.$key.'_'.$suborder_key.'" value="'.$multiparcel_info["parcels"][$i][str_replace('_dims_'.$i.'_', '', $key)].'" size=3 /> '.$field['unit'].'</span></div>';
                                }
                                echo '</div>';
                            }
                            ?>
                        <p><a data-key="<?php echo $suborder_key; ?>" class="add-parcel"><?php echo __('add parcel','envoimoinscher'); ?></a></p>
                        </div><!-- eod edit_dimensions -->

                    </div><!-- eod order_shipping_column -->

                    <?php if ( isset ($insurance_options) ) : ?>
                    <div class="order_shipping_column">
                        <h4><?php _e( 'Insurance', 'envoimoinscher' ); ?></h4>

                        <div>
                            <?php
                            foreach ( $fields[$suborder_key]['insurance'] as $key => $field ) {
                                echo '<p>';
                                echo '<input type="checkbox" class="'.$key.'" name="'.$key.'_'.$suborder_key.'"';
                                if ( $insurance != 0 ) echo 'checked';
                                echo '/>'.$field['label'].' (<span id="insurance_rate">'.wc_price( $insurance_price, array('ex_tax_label'=>true) ).'</span>)</p>';
                                echo '<span class="insurance_rate_unformatted">'.$insurance_price.'</span>';
                            }
                            ?>
                        </div><!-- eod insurance -->

                        <div class="edit_insurance">
                            <?php
                                foreach($insurance_options as $option) {
                                    if( empty($option['values']) ) continue;
                                    $default = $default_insurance_options['_'.str_replace('.', '_', $option['code'])][$suborder_key];
                                    echo '<div class="form-field form-field-wide"><label for="_'.$option['code'].'">'.ucfirst($option['label']).'</label>';
                                    echo '<select name="_'.$option['code'].'_'.$suborder_key.'" id="_'.$option['code'].'_'.$suborder_key.'">';
                                    foreach($option['values'] as $key => $value) {
                                        echo '<option value="'.$key.'" ';
                                        if( $key == $default ) echo 'selected';
                                        echo '>'.$value.'</option>';
                                    }
                                    echo '</select></div>';
                                }
                            ?>
                        </div><!-- eod edit_insurance -->
                    </div><!-- eod order_shipping_column -->
                    <?php endif; ?>

                </div><!-- eod order_shipping_column_container -->
                <div class="clear"></div>

                <?php
                    $proforma_mandatory_fields = array();

                    if( is_array( $offers[$suborder_key] ) ) {
                      if( isset( $offers[$suborder_key][ $carrier_code ] ) ){
                        $emc_offer = $offers[$suborder_key][ $carrier_code ];
                        if( isset( $emc_offer[ 'mandatory' ] ) ){
                          foreach( $emc_offer[ 'mandatory' ] as $option => $value ) {
                            if ( strstr( $option,'proforma.' ) && !isset( $proforma_mandatory_fields[ $option ] ) ) {
                              $proforma_mandatory_fields[ $option ] = $value;
                            }
                          }
                        }
                      }
                    }

                    // Display it only if mandatory fields
                    if (count($proforma_mandatory_fields) > 0) {
                        ?>
                        <div class="international_shipping order_shipping_column_container">
                            <h4><?php _e( 'International Shipping', 'envoimoinscher' ); ?></h4>
                            <?php

                                $proforma_fields = $fields[$suborder_key]['shipping_international'];

                                // Select shipping reason
                                $select_reason = '<p class="form-field form-field-wide"><span>' . $proforma_fields[ '_proforma_reason' ][ 'label' ] . '</span>';
                                $select_reason .= '<select name="' . $proforma_fields[ '_proforma_reason' ][ 'name' ] .'_'.$suborder_key. '" class="' . $proforma_fields[ '_proforma_reason' ][ 'class' ] . '">';

                                foreach ( $proforma_fields[ '_proforma_reason' ][ 'options' ] as $option => $value ) {
                                    if( $option == $proforma_reason ) {
                                        $select_reason .= '<option value="' . $option . '" selected>' . $value . '</option>';
                                    } else {
                                        $select_reason .= '<option value="' . $option . '">' . $value . '</option>';
                                    }
                                }

                                $select_reason .= '</select></p>';
                                echo $select_reason;

                                // proforma items
                                echo '<h4>'. __( 'Shipment content', 'envoimoinscher' ) .'</h4>';

                                foreach ( $items as $item_id => $item ) {
                                    $_product  = $order->get_product_from_item( $item );
                                    $check_id = $item["variation_id"] == 0 ? $item["product_id"]:$item["variation_id"];
                                    $item_weight = (float) envoimoinscher_model::get_product_weight($check_id);
                                    $item_price = (float) (esc_html( $item['line_subtotal'] ) / esc_html( $item['qty'] ));
                                    ?>
                                        <div class="item" data-item="'.$suborder_key.'_'.$check_id.'">

                                            <!-- product title and thumbnail -->
                                            <div class="thumb">
                                                <?php if ( $_product ) : ?>
                                                    <a href="<?php echo esc_url( admin_url( 'post.php?post=' . absint( $_product->id ) . '&action=edit' ) ); ?>" class="tips" data-tip="<?php

                                                        echo '<strong>' . __( 'Product ID:', 'envoimoinscher' ) . '</strong> ' . absint( $item['product_id'] );

                                                        if ( ! empty( $item['variation_id'] ) && 'product_variation' === get_post_type( $item['variation_id'] ) ) {
                                                            echo '<br/><strong>' . __( 'Variation ID:', 'envoimoinscher' ) . '</strong> ' . absint( $item['variation_id'] );
                                                        } elseif ( ! empty( $item['variation_id'] ) ) {
                                                            echo '<br/><strong>' . __( 'Variation ID:', 'envoimoinscher' ) . '</strong> ' . absint( $item['variation_id'] ) . ' (' . __( 'No longer exists', 'envoimoinscher' ) . ')';
                                                        }

                                                        if ( $_product && $_product->get_sku() ) {
                                                            echo '<br/><strong>' . __( 'Product SKU:', 'envoimoinscher' ).'</strong> ' . esc_html( $_product->get_sku() );
                                                        }

                                                        if ( $_product && isset( $_product->variation_data ) ) {
                                                            echo '<br/>' . wc_get_formatted_variation( $_product->variation_data, true );
                                                        }

                                                    ?>"><?php echo apply_filters( 'woocommerce_admin_order_item_thumbnail', $_product->get_image( 'shop_thumbnail', array( 'title' => '' ) ), $item_id, $item ); ?></a>
                                                <?php else : ?>
                                                    <?php echo wc_placeholder_img( 'shop_thumbnail' ); ?>
                                                <?php endif; ?>
                                                <a href="<?php echo esc_url( admin_url( 'post.php?post=' . absint( $_product->id ) . '&action=edit' ) ); ?>"><?php echo $item['name'] ?></a>
                                            </div>

                                            <!-- not editable properties (except quantity) -->
                                            <div><?php
                                                echo '<span class="mr10">'.$proforma_fields[ '_proforma_items' ]['proforma_weight']['label'] . ' ' . $item_weight . ' kg</span>';
                                                echo '<span class="mr10 item-price">'.$proforma_fields[ '_proforma_items' ]['proforma_price']['label'] . ' ' . wc_price( $item_price, array('ex_tax_label'=>true) ) . '</span>';
                                                echo '<input type="hidden" class="item-weight" value="'.$item_weight.'" />';
                                                echo '<input type="hidden" class="item-price" value="'.$item_price.'" />';

                                                // get quantity
                                                foreach ($multiparcel_info['products'] as $product) {
                                                    if ($product['id'] == $check_id) {
                                                        $qty = $product['qty'];
                                                    }
                                                }
                                                echo $proforma_fields[ '_proforma_items' ]['proforma_qty']['label'].' ';
                                                echo '<input type="number" class="proforma_qty" name="proforma_qty_'.$suborder_key.'_'.$check_id.'" value="'.$qty.'" min="0" max="999999" />';
                                            ?></div>

                                            <!-- editable properties (toggled by quantity) -->
                                            <div class="proforma_editable_fields" <?php if ($qty == 0) echo 'style="display:none"'; ?>>
                                                <div class="proforma">
                                                    <strong><?php _e( 'Edit fields', 'envoimoinscher' ); ?></strong> <a class="edit_item_international" href="#"><img src="<?php echo WC()->plugin_url(); ?>/assets/images/icons/edit.png" alt="<?php _e( 'Edit', 'envoimoinscher' ); ?>" width="14" /></a><br/>

                                                    <?php
                                                        if ( isset( $proforma_mandatory_fields[ 'proforma.description_en' ] ) ) {
                                                            echo $proforma_fields[ '_proforma_items' ][ 'proforma_post_title_en' ][ 'label' ] . ' ' . $proforma_items[$check_id]['post_title_en'].'<br/>';
                                                        }

                                                        if ( isset( $proforma_mandatory_fields[ 'proforma.description_fr' ] ) ) {
                                                            echo $proforma_fields[ '_proforma_items' ][ 'proforma_post_title_fr' ][ 'label' ] . ' ' . $proforma_items[$check_id]['post_title_fr'].'<br/>';
                                                        }

                                                        if ( isset( $proforma_mandatory_fields[ 'proforma.origine' ] ) ) {
                                                            echo $proforma_fields[ '_proforma_items' ]['proforma_origin']['label'] . ' ' . $proforma_items[$check_id]['origin'];
                                                        }
                                                    ?>
                                                </div>


                                                <!-- Display form for the edit item -->
                                                <div class="edit_proforma">
                                                    <strong><?php _e( 'Edit fields', 'envoimoinscher' ); ?></strong>

                                                    <?php
                                                        if ( isset( $proforma_mandatory_fields[ 'proforma.description_en' ] ) ) {
                                                            echo '<p>'.$proforma_fields[ '_proforma_items' ][ 'proforma_post_title_en' ][ 'label' ] . ' <textarea name="proforma_post_title_en_'.$suborder_key.'_'.$check_id.'">'.$proforma_items[$check_id]['post_title_en'] . '</textarea></p>';
                                                        }

                                                        if ( isset( $proforma_mandatory_fields[ 'proforma.description_fr' ] ) ) {
                                                            echo '<p>'.$proforma_fields[ '_proforma_items' ][ 'proforma_post_title_fr' ][ 'label' ] . ' <textarea name="proforma_post_title_fr_'.$suborder_key.'_'.$check_id.'">'. $proforma_items[$check_id]['post_title_fr'] . '</textarea></p>';
                                                        }

                                                        if(method_exists(WC()->countries, 'get_countries')) {
                                                            $display_countries =  WC()->countries->get_countries();
                                                        } else {
                                                            $display_countries =  WC()->countries->countries;
                                                        }

                                                        if ( isset( $proforma_mandatory_fields[ 'proforma.origine' ] ) ) {
                                                            echo '<p><label for="proforma_origin">' . $proforma_fields[ '_proforma_items' ]['proforma_origin']['label'] . '</label> ';
                                                            echo '<select name="proforma_origin_'.$suborder_key.'_'.$check_id.'">';
                                                            foreach ($display_countries as $country_code => $country) {
                                                                if( $country == $proforma_items[$check_id]['origin'] ) {
                                                                    echo '<option value="'. $country_code .'" selected>' . $country . '</option>';
                                                                } else {
                                                                   echo '<option value="'. $country_code .'">' . $country . '</option>';
                                                                }
                                                            }
                                                            echo '</select></p>';
                                                        }
                                                    ?>
                                                </div>
                                            </div>
                                        </div>
                                    <?php
                                }
                            ?>
                        </div><!-- eod proforma order_shipping_column_container -->
                        <?php
                    }  // end of if proforma_mandatory_fields
                echo '</div>'; // end of emc_shipment div
        } // end of multiparcels foreach

        // output footer
        self::output_footer();

        // add "add a shipment" popup
        ?>
            <div style="display:none">
                <div id="add-shipment-popup">
                    <span class="s14">
                        <?php
                            echo '<p>'.__( 'Which address will you be using?', 'envoimoinscher' ).' ';
                            echo '<select name="_address_select">';
                            foreach( $addressbook as $address ) {
                                echo '<option value="'.$address['id'].'">'.$address['label'].'</option>';
                            }
                            echo '</select></p>';
                            echo '<p>'.__( 'Which items will you be adding to this shipment?', 'envoimoinscher' ).'</p>';
                            echo '<table>';
                            foreach ( $items as $item ) {
                                $check_id = $item["variation_id"] == 0 ? $item["product_id"] : $item["variation_id"];
                                if (function_exists('wc_get_product')) {
                                    $product = wc_get_product( $check_id );
                                } else {
                                    // fix for WC < 2.5
                                    $product = WC()->product_factory->get_product( $check_id );
                                }
                                // get title
                                $title = $product->get_title();
                                $product_type = envoimoinscher_model::envoimoinscher_get_product_property($product, 'type');
                                if ( $product_type == 'variation' ) {
                                    $parent_id = $product->parent->id;
                                    if (function_exists('wc_get_product')) {
                                        $parent_product = wc_get_product( $parent_id );
                                    } else {
                                        // fix for WC < 2.5
                                        $parent_product = WC()->product_factory->get_product( $parent_id );
                                    }
                                    foreach($parent_product->get_available_variations() as $variation) {
                                        if ($variation['variation_id'] == $check_id) {
                                            foreach($variation['attributes'] as $attributes){
                                                $title .= ' ' . $attributes;
                                            }
                                        }
                                    }
                                }
                                ?>
                                    <!-- product title and thumbnail -->
                                    <tr class="thumb">
                                        <td>
                                            <?php 
                                                echo '<span class="thumb" style="margin-right:5px">'.$product->get_image( 'shop_thumbnail', array( 'title' => '' ) ).'</span>'.$title;
                                            ?>
                                        </td>
                                        <td><input type="number" class="popup_proforma_qty" name="proforma_qty_<?php echo $check_id; ?>" value="0" min="0" max="999999" /></td>
                                    </tr>
                                <?php
                            }
                            echo '</table>';
                        ?>
                    </span>
                    <div class="center">
                        <div class="add-shipment-error red" style="height:20px;margin:5px 0"></div>
                        <button class="button-primary mr5" name="add-shipment">
                            <?php _e( 'Add shipment', 'envoimoinscher' ); ?>
                        </button>
                        <button class="button mr5" name="cancel"><?php _e( 'Cancel', 'envoimoinscher' ); ?></button>
                    </div>
                </div>
            </div>
        <?php
        
        // add "reset shipping options" popup
        ?>
            <div style="display:none">
                <div id="reset-shipping-popup">
                    <span class="s14 center">
                        <p><?php _e('Are you sure you want to reset shipping options? All changes you made will be lost (customer pickup point choice will be kept).', 'envoimoinscher' ); ?></p>
                    <span>
                    <div class="center">
                        <button class="button-primary mr5" name="reset-shipping" rel="">
                            <?php _e( 'Reset shipping options', 'envoimoinscher' ); ?>
                        </button>
                        <button class="button mr5" name="cancel"><?php _e( 'Cancel', 'envoimoinscher' ); ?></button>
                    </div>
                </div>
            </div>
        <?php

        // add "delete a shipment" popup
        ?>
            <div style="display:none">
                <div id="delete-shipment-popup">
                    <span class="s14">
                        <p><?php _e('Are you sure you want to delete this shipment? All data will be lost.', 'envoimoinscher' ); ?></p>
                    <span>
                    <div class="center">
                        <button class="button-primary mr5" name="delete-shipment" rel="">
                            <?php _e( 'Delete shipment', 'envoimoinscher' ); ?>
                        </button>
                        <button class="button mr5" name="cancel"><?php _e( 'Cancel', 'envoimoinscher' ); ?></button>
                    </div>
                </div>
            </div>
        <?php
    }

    /**
     * Save meta box data
     */
    public static function save( $post_id, $post ) {
        global $the_order, $wpdb;
        if ( ! is_object( $the_order ) ) {
            $order = envoimoinscher_model::envoimoinscher_get_order( $post->ID );
        }
        else {
            $order = $the_order;
        }
        $order_id = envoimoinscher_model::envoimoinscher_get_order_id($order);

        // get multiparcel value
        $multiparcels = get_post_meta($order_id, '_multiparcels', true);
        // get values
        $addressbook = envoimoinscher_model::get_addresses("all", true);
        $items = $order->get_items( apply_filters( 'woocommerce_admin_order_item_types', 'line_item' ) ); // items in order
        $_emc_carrier = get_post_meta( $order_id, '_emc_carrier', true );
        $_emc_ref = get_post_meta( $order_id, '_emc_ref', true );
        $_carrier_ref = get_post_meta( $order_id, '_carrier_ref', true );
        $_label_url = get_post_meta( $order_id, '_label_url', true );
        $_remise = get_post_meta( $order_id, '_remise', true );
        $_manifest = get_post_meta( $order_id, '_manifest', true );
        $_connote = get_post_meta( $order_id, '_connote', true );
        $_proforma = get_post_meta( $order_id, '_proforma', true );
        $_b13a = get_post_meta( $order_id, '_b13a', true );
        $_desc_value = get_post_meta( $order_id, '_desc_value', true);
        $_desc_content = get_post_meta( $order_id, '_desc_content', true);
        $_wrapping = get_post_meta( $order_id, '_wrapping', true);
        $_pickup_point = get_post_meta( $order_id, '_pickup_point', true);
        $_dropoff_point = get_post_meta( $order_id, '_dropoff_point', true);
        $_pickup_date = get_post_meta( $order_id, '_pickup_date', true);
        $_insurance = get_post_meta( $order_id, '_insurance', true);
        $_assurance_emballage = get_post_meta( $order_id, '_assurance_emballage', true);
        $_assurance_materiau = get_post_meta( $order_id, '_assurance_materiau', true);
        $_assurance_protection = get_post_meta( $order_id, '_assurance_protection', true);
        $_assurance_fermeture = get_post_meta( $order_id, '_assurance_fermeture', true);
        $_proforma_reason = get_post_meta( $order_id, '_proforma_reason', true);
        $_proforma_items = get_post_meta( $order_id, '_proforma_items', true);

        // init fields
        $fields = self::init_shipping_info($order, $multiparcels); // fields for forms

        foreach ($multiparcels as $index => $multiparcel_info) {

            $suborder_key = $multiparcel_info['suborder_key'];

            // update address
            if( isset($_POST[ '_address_select_'.$suborder_key ]) && $_POST[ '_address_select_'.$suborder_key ] != '') {
                $multiparcels[$index]['address_id'] = $_POST[ '_address_select_'.$suborder_key ];
            }

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

                $carrier_code = wc_clean($_POST[ '_emc_carrier_'.$suborder_key ]);

                $service = envoimoinscher_model::get_service_by_carrier_code($carrier_code);

                // update content description (colis.valeur & colis.description)
                foreach ( $fields[$suborder_key]['content_description'] as $key => $field ) {
                    if (isset($_POST[ $key.'_'.$suborder_key ])) {
                        ${$key}[$suborder_key] = wc_clean( $_POST[ $key.'_'.$suborder_key ] );
                    }
                }

                if( $service != false ) {

                    if ( !isset($_emc_carrier[$suborder_key]) || $carrier_code != $_emc_carrier[$suborder_key]) {
                        // if carrier has changed, reinitialize parcel points
                        $_emc_carrier[$suborder_key] = $carrier_code;
                        $carrier_settings = get_option('woocommerce_'.$carrier_code.'_settings');

                        if ( $service->srv_dropoff_point == 1 ) {
                            $dropoff_point_carrier = get_post_meta( $post_id, '_dropoff_point_' . $carrier_code , true );

                            if ( $dropoff_point_carrier != '' && isset($dropoff_point_carrier[$suborder_key]) && $dropoff_point_carrier[$suborder_key] != '' ) {
                                $dropoff_point = $dropoff_point_carrier[$suborder_key];
                            } else {
                                foreach($addressbook as $item) {
                                    if ($item['id'] == $_POST[ '_address_select_'.$suborder_key ]) {
                                        $address = $item;
                                    }
                                }
                                $dropoff_points = @unserialize($address['dropoff_points']);
                                list($ope, $srv) = explode('_', $carrier_code);
                                $dropoff_point = isset($dropoff_points[$ope]) ? $dropoff_points[$ope] : '';
                            }
                        } else {
                            $dropoff_point = 'POST';
                        }

                        $_dropoff_point[$suborder_key] = $dropoff_point;

                        $pickup_point_carrier = get_post_meta( $post_id, '_pickup_point_' . $carrier_code , true );
                        if ( $pickup_point_carrier != '' ) {
                            $_pickup_point[$suborder_key] = $pickup_point_carrier[$suborder_key];
                        }
                        else{
                            $_pickup_point[$suborder_key] = '';
                        }
                    } else {
                        // else update parcel points info
                        if( $service->srv_dropoff_point == 1 ) {
                            $_dropoff_point[$suborder_key] = wc_clean( isset($_POST[ '_dropoff_point_'.$suborder_key ]) ? $_POST[ '_dropoff_point_'.$suborder_key ] : '' );
                            $dropoff_point_carrier = get_post_meta( $post_id, '_dropoff_point_' . $carrier_code , true );
                            $dropoff_point_carrier[$suborder_key] = wc_clean( isset($_POST[ '_dropoff_point_'.$suborder_key ]) ? $_POST[ '_dropoff_point_'.$suborder_key ] : '' );
                            update_post_meta( $post_id, '_dropoff_point_' . $carrier_code , $dropoff_point_carrier );
                        }

                        if( $service->srv_pickup_point == 1 ) {
                            $_pickup_point[$suborder_key] = wc_clean( isset($_POST[ '_pickup_point_'.$suborder_key ]) ? $_POST[ '_pickup_point_'.$suborder_key ] : '' );
                            $pickup_point_carrier = get_post_meta( $post_id, '_pickup_point_' . $carrier_code , true );
                            $pickup_point_carrier[$suborder_key] = wc_clean( isset($_POST[ '_pickup_point_'.$suborder_key ]) ? $_POST[ '_pickup_point_'.$suborder_key ] : '' );
                            update_post_meta( $post_id, '_pickup_point_' . $carrier_code , $pickup_point_carrier );
                        }
                    }
                }

                // update pickup date
                $_pickup_date[$suborder_key] = wc_clean( strtotime (  $_POST[ '_pickup_date_'.$suborder_key ] ) );

                // update dimensions
                $multiparcels[$index]["parcels"] = array();
                foreach ( $fields[$suborder_key]['dimensions'] as $i => $dimensions ) {
                    $multiparcels[$index]["parcels"][$i] = array();
                    foreach($dimensions as $key => $field)
                    {
                        $multiparcels[$index]["parcels"][$i][str_replace('_dims_'.$i.'_', '', $key)] = (float)wc_clean( str_replace(',', '.', $_POST[ $key.'_'.$suborder_key ]) );
                    }
                }

                // update insurance
                $_insurance[$suborder_key] = isset ($_POST[ '_insurance_' . $suborder_key ]) ? 1 : 0;
                if (isset ($_POST[ '_assurance_emballage_' . $suborder_key ])) {
                    $_assurance_emballage[$suborder_key] = $_POST[ '_assurance_emballage_' . $suborder_key ];
                }
                if (isset ($_POST[ '_assurance_materiau_' . $suborder_key ])) {
                    $_assurance_materiau[$suborder_key] = $_POST[ '_assurance_materiau_' . $suborder_key ];
                }
                if (isset ($_POST[ '_assurance_protection_' . $suborder_key ])) {
                    $_assurance_protection[$suborder_key] = $_POST[ '_assurance_protection_' . $suborder_key ];
                }
                if (isset ($_POST[ '_assurance_fermeture_' . $suborder_key ])) {
                    $_assurance_fermeture[$suborder_key] = $_POST[ '_assurance_fermeture_' . $suborder_key ];
                }

                // update proforma
                if (isset ($_POST[ 'proforma_reason_' . $suborder_key ])) {
                    $_proforma_reason[$suborder_key] = $_POST[ 'proforma_reason_' . $suborder_key ];
                }

                if(method_exists(WC()->countries, 'get_countries')) {
                    $display_countries =  WC()->countries->get_countries();
                } else {
                    $display_countries =  WC()->countries->countries;
                }

                $proforma_fields = $fields[$suborder_key]['shipping_international'];

                foreach ( $items as $item ) {
                    $check_id = $item["variation_id"] == 0 ? $item["product_id"] : $item["variation_id"];
                    $_proforma_items[$suborder_key][$check_id] = array(
                        'post_title_en' => isset ( $_POST[ 'proforma_post_title_en_'.$suborder_key.'_'.$check_id ] ) ? $_POST[ 'proforma_post_title_en_'.$suborder_key.'_'.$check_id ] : esc_html( $item[ 'name' ] ),
                        'post_title_fr' => isset ( $_POST[ 'proforma_post_title_fr_'.$suborder_key.'_'.$check_id ] ) ? $_POST[ 'proforma_post_title_fr_'.$suborder_key.'_'.$check_id ] : esc_html( $item[ 'name' ] ),
                        'origin' => isset ( $_POST[ 'proforma_origin_'.$suborder_key.'_'.$check_id ] ) ? $display_countries[$_POST[ 'proforma_origin_'.$suborder_key.'_'.$check_id ]] : __( 'France', 'envoimoinscher' ),
                    );
                    $qty = isset ( $_POST[ 'proforma_qty_'.$suborder_key.'_'.$check_id ] ) ? $_POST[ 'proforma_qty_'.$suborder_key.'_'.$check_id ] : 0;
                    foreach ($multiparcels as $multiparcel_info_2_index => $multiparcel_info_2) {
                        if ($multiparcel_info_2['suborder_key'] == $suborder_key) {
                            $updated = false;
                            foreach ($multiparcel_info_2['products'] as $product_index => $product) {
                                if ($product['id'] == $check_id) {
                                    $multiparcels[$multiparcel_info_2_index]['products'][$product_index]['qty'] = $qty;
                                    $updated = true;
                                }
                            }
                            if (!$updated) {
                                array_push($multiparcel_info_2['products'], array('id' => $check_id, 'qty' => $qty));
                            }
                        }
                    }
                }

                wc_delete_shop_order_transients( $post_id );
            }
        }

        // post values
        update_post_meta( $order_id, '_emc_carrier', $_emc_carrier );
        update_post_meta( $order_id, '_emc_ref', $_emc_ref );
        update_post_meta( $order_id, '_carrier_ref', $_carrier_ref );
        update_post_meta( $order_id, '_label_url', $_label_url );
        update_post_meta( $order_id, '_remise', $_remise );
        update_post_meta( $order_id, '_manifest', $_manifest );
        update_post_meta( $order_id, '_connote', $_connote );
        update_post_meta( $order_id, '_proforma', $_proforma );
        update_post_meta( $order_id, '_b13a', $_b13a );
        update_post_meta( $order_id, '_desc_value', $_desc_value );
        update_post_meta( $order_id, '_desc_content', $_desc_content );
        update_post_meta( $order_id, '_wrapping', $_wrapping );
        update_post_meta( $order_id, '_pickup_point', $_pickup_point );
        update_post_meta( $order_id, '_dropoff_point', $_dropoff_point );
        update_post_meta( $order_id, '_pickup_date', $_pickup_date );
        update_post_meta( $order_id, '_insurance', $_insurance );
        update_post_meta( $order_id, '_assurance_emballage', $_assurance_emballage );
        update_post_meta( $order_id, '_assurance_materiau', $_assurance_materiau );
        update_post_meta( $order_id, '_assurance_protection', $_assurance_protection );
        update_post_meta( $order_id, '_assurance_fermeture', $_assurance_fermeture );
        update_post_meta( $order_id, '_proforma_reason', $_proforma_reason );
        update_post_meta( $order_id, '_proforma_items', $_proforma_items );
        update_post_meta( $order_id, '_multiparcels', $multiparcels );
    }
}
