<?php
/**
 * EMC Updates
 *
 * Functions for updating data, used by the background updater.
 *
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

function emc_update_116_carrier_display_option() {
	add_option('EMC_CARRIER_DISPLAY', 'no');
}

function emc_update_116_db_version() {
	envoimoinscher_model::update_db_version( '1.1.6' );
}

function emc_update_126_pickup_option() {
	// delivery date changes
    $emc_pickup_j1 = get_option('EMC_PICKUP_J1');
    $emc_pickup_j2 = get_option('EMC_PICKUP_J2');
	update_option('EMC_PICKUP', array($emc_pickup_j1[0], $emc_pickup_j2[0], $emc_pickup_j1[2]));
	delete_option('EMC_PICKUP_J1');
	delete_option('EMC_PICKUP_J2');
}

function emc_update_126_label_delivery_date_options() {
    // delivery label changes
    $label = get_option('EMC_LABEL_DELIVERY_DATE');
    // get installed languages
    $languages = get_available_languages();
    array_push($languages, 'en_US'); // 'en' is always added by default and not returned by get_available_languages
    $translations = array();
    foreach ($languages as $language) {
        $translations[$language] = $label;
    }
	update_option('EMC_LABEL_DELIVERY_DATE', $translations);
}

function emc_update_126_tracking_urls() {
        // get activated services
    $emc_services = envoimoinscher_model::get_emc_active_shipping_methods();
    
    // get default tracking urls
    $tracking_urls = envoimoinscher_model::$tracking_urls;
    
    // set default tracking url values for activated services if empty
    foreach( $emc_services as $value ){
        if ( get_option( 'woocommerce_' . $value . '_settings' ) ){
            $option = get_option( 'woocommerce_' . $value . '_settings' );

            if ($option['carrier_tracking_url'] == '') {
                $option['carrier_tracking_url'] = isset($tracking_urls[$value]) ? $tracking_urls[$value] : '';
            }
            update_option( 'woocommerce_' . $value . '_settings',  $option );
        }
	}
}

function emc_update_126_db_version() {
	envoimoinscher_model::update_db_version( '1.2.6' );
}

function emc_update_129_db_drop_columns() {
	global $wpdb;

    $wpdb->query( 
        "ALTER TABLE {$wpdb->prefix}emc_services DROP srv_zone, DROP srv_id_wc_carrier, DROP srv_description_bo;"
    );
}

function emc_update_129_carriers_update() {
	envoimoinscher_model::load_carrier_list_api(false, false);
    
    // update existing carriers fields
    $services = envoimoinscher_model::get_services();
    $languages = get_available_languages();
    array_push($languages, 'en_US'); // 'en' is always added by default and not returned by get_available_languages
    foreach ($services as $service) {
        $current_settings = get_option('woocommerce_'.$service->ope_code.'_'.$service->srv_code.'_settings');
        if($current_settings !== false) {
            $new_settings = array();
            if (false === @unserialize($current_settings['srv_name'])) {
                $translations = array();
                foreach ($languages as $language) {
                    $translations[$language] = $current_settings['srv_name'];
                }
                $new_settings['srv_name'] = serialize($translations);
            } else {
                $new_settings['srv_name'] = $current_settings['srv_name'];
            }
            if (false === @unserialize($current_settings['srv_description'])) {
                $translations = array();
                foreach ($languages as $language) {
                    $translations[$language] = $current_settings['srv_description'];
                }
                $new_settings['srv_description'] = serialize($translations);
            } else {
                $new_settings['srv_description'] = $current_settings['srv_description'];
            }
            $new_settings['enabled'] = $current_settings['enabled'];
            if (isset($current_settings['pricing'])) {
                $new_settings['pricing'] = $current_settings['pricing'];
            }
            if (isset($current_settings['default_dropoff_point'])) {
                $new_settings['default_dropoff_point'] = $current_settings['default_dropoff_point'];
            }
            $new_settings['carrier_tracking_url'] = $current_settings['carrier_tracking_url'];
            update_option('woocommerce_'.$service->ope_code.'_'.$service->srv_code.'_settings', $new_settings);
        }
    }
}

function emc_update_129_options() {
	// rectify option naming
    $display_carrier = get_option('EMC_carrier_display', 'yes');
    update_option('EMC_CARRIER_DISPLAY', $display_carrier);
    
    // rectify option translation
    $label = get_option('EMC_LABEL_DELIVERY_DATE');
    if (isset($label['en'])) {
        $label['en_US'] = $label['en'];
        unset($label['en']);
    }
    update_option('EMC_LABEL_DELIVERY_DATE', serialize($label));
}

function emc_update_129_db_version() {
	envoimoinscher_model::update_db_version( '1.2.9' );
}

function emc_update_130_unserializing_multilingual_fields_services() {
    // unserializing existing multilingual carriers fields
    $services = envoimoinscher_model::get_services();
    foreach ($services as $service) {
        $current_settings = get_option('woocommerce_'.$service->ope_code.'_'.$service->srv_code.'_settings');
        if($current_settings != null) {
            $new_settings = array();
            if (false !== @unserialize($current_settings['srv_name'])) {
                $new_settings['srv_name'] = @unserialize($current_settings['srv_name']);
            } else {
                $new_settings['srv_name'] = $current_settings['srv_name'];
            }
            if (false !== @unserialize($current_settings['srv_description'])) {
                $new_settings['srv_description'] = @unserialize($current_settings['srv_description']);
            } else {
                $new_settings['srv_description'] = $current_settings['srv_description'];
            }
            $new_settings['enabled'] = $current_settings['enabled'];
            if (isset($current_settings['pricing'])) {
                $new_settings['pricing'] = $current_settings['pricing'];
            }
            if (isset($current_settings['default_dropoff_point'])) {
                $new_settings['default_dropoff_point'] = $current_settings['default_dropoff_point'];
            }
            $new_settings['carrier_tracking_url'] = $current_settings['carrier_tracking_url'];
            update_option('woocommerce_'.$service->ope_code.'_'.$service->srv_code.'_settings', $new_settings);
        }
    }
}

function emc_update_130_unserializing_multilingual_fields_option() {
	$label = get_option('EMC_LABEL_DELIVERY_DATE');
    if (false !== @unserialize($label)) {
        update_option('EMC_LABEL_DELIVERY_DATE', @unserialize($label));
    }
}

function emc_update_130_convert_insurance_to_ids() {
	global $wpdb;

	$metas = $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE meta_key IN (\"_assurance_emballage\", \"_assurance_materiau\", \"_assurance_protection\", \"_assurance_fermeture\")");
    $insurance = array(
        1 => "Boîte",
        10 => "Caisse",
        11 => "Bac",
        12 => "Emballage isotherme",
        14 => "Etui",
        15 => "Malle",
        16 => "Sac",
        17 => "Tube",
        101 => "Carton",
        102 => "Bois",
        103 => "Carton blindé",
        104 => "Film opaque",
        105 => "Film transparent",
        106 => "Métal",
        107 => "Papier",
        108 => "Papier armé",
        109 => "Plastique et carton",
        110 => "Plastique",
        111 => "Plastique opaque",
        112 => "Plastique transparent",
        113 => "Polystyrène",
        201 => "Sans protection particulière",
        202 => "Calage papier",
        203 => "Bulles plastiques",
        204 => "Carton antichoc",
        205 => "Coussin air",
        206 => "Coussin mousse",
        207 => "Manchon carton (bouteille)",
        208 => "Manchon mousse (bouteille)",
        209 => "Matelassage",
        210 => "Plaque mousse",
        212 => "Coussin de calage",
        213 => "Sachet bulles",
        301 => "Fermeture autocollante",
        302 => "Ruban adhésif",
        303 => "Agrafes",
        304 => "Clous",
        305 => "Collage",
        306 => "Ruban de cerclage",
        307 => "Sangle ou feuillard",
        308 => "Agraphes et cerclage",
        309 => "Clous et cerclage",
        310 => "Ficelles",
    );

    foreach ($metas as $meta) {
        $new_value = array_search($meta->meta_value, $insurance);
        
        if ($new_value == 113 && $meta->meta_key != "_assurance_materiau") {
            $new_value = 211;
        }
        
        if (false === $new_value) {
            $new_value = $meta->meta_value;
        }
        update_post_meta( $meta->post_id, $meta->meta_key, $new_value );
    }
}

function emc_update_130_db_version() {
	envoimoinscher_model::update_db_version( '1.3.0' );
}

function emc_update_140_convert_scales_to_new_format() {
	global $wpdb;
    
    $services = envoimoinscher_model::get_services();
    
    $countries = EMC()->get_all_countries();
    $all_countries = array();
    foreach ($countries as $iso => $label) {
        array_push($all_countries, $iso);
    }
    
    $shipping_classes = EMC()->get_shipping_classes();
    $all_shipping_classes = array();
    foreach ($shipping_classes as $class) {
        array_push($all_shipping_classes, $class->slug);
    }
    array_push($all_shipping_classes,"none");
    
    foreach ($services as $service) {
        $pricing = array();
        $current_settings = get_option('woocommerce_'.$service->ope_code.'_'.$service->srv_code.'_settings');
        if($current_settings != null) {
            if (isset ($current_settings['pricing']) && $current_settings['pricing'] == 1) {
                /* case : live quotes */
                $pricing_item = new stdClass();
                $pricing_item->price_from = '';
                $pricing_item->price_to = '';
                $pricing_item->weight_from = '';
                $pricing_item->weight_to = '';
                $pricing_item->shipping_class = $all_shipping_classes;
                $pricing_item->zones = $all_countries;
                $pricing_item->handling_fees = '';
                $pricing_item->pricing = 'live';
                $pricing_item->flat_rate = '';
                $pricing = array(0 => $pricing_item);
            } elseif (isset ($current_settings['pricing']) && $current_settings['pricing'] == 2 && (isset($current_settings['rate_type']) && $current_settings['rate_type'] == "weight")) {
                /* case : rates based on weight */
                $scales = $wpdb->get_results(
                    'SELECT * FROM '.$wpdb->prefix.'emc_scales WHERE shipping_method = "'.$service->ope_code."_".$service->srv_code.'" AND type = "weight" ',
                    ARRAY_A
                );
                
                if (!empty($scales)) {
                    foreach ($scales as $scale) {
                        $pricing_item = new stdClass();
                        $pricing_item->price_from = '';
                        $pricing_item->price_to = '';
                        $pricing_item->weight_from = $scale['rate_from'];
                        $pricing_item->weight_to = $scale['rate_to'];
                        $pricing_item->shipping_class = $all_shipping_classes;
                        $pricing_item->zones = $all_countries;
                        $pricing_item->handling_fees = isset($current_settings['handling_fees']) ? $current_settings['handling_fees'] : '';
                        $pricing_item->pricing = 'rate';
                        $pricing_item->flat_rate = $scale['rate_price'];
                        array_push($pricing, $pricing_item);
                    }
                }
                
                /* add live quote fallback to keep behaviour as is */
                $pricing_item = new stdClass();
                $pricing_item->price_from = '';
                $pricing_item->price_to = '';
                $pricing_item->weight_from = '';
                $pricing_item->weight_to = '';
                $pricing_item->shipping_class = $all_shipping_classes;
                $pricing_item->zones = $all_countries;
                $pricing_item->handling_fees = '';
                $pricing_item->pricing = 'live';
                $pricing_item->flat_rate = '';
                array_push($pricing, $pricing_item);
            } else if(isset ($current_settings['pricing']))  {
                /* case : rates based on price */
                $scales = $wpdb->get_results(
                    'SELECT * FROM '.$wpdb->prefix.'emc_scales WHERE shipping_method = "'.$service->ope_code."_".$service->srv_code.'" AND type = "price" ',
                    ARRAY_A
                );
                
                if (!empty($scales)) {
                    foreach ($scales as $scale) {
                        $pricing_item = new stdClass();
                        $pricing_item->price_from = $scale['rate_from'];
                        $pricing_item->price_to = $scale['rate_to'];
                        $pricing_item->weight_from = '';
                        $pricing_item->weight_to = '';
                        $pricing_item->shipping_class = $all_shipping_classes;
                        $pricing_item->zones = $all_countries;
                        $pricing_item->handling_fees = isset($current_settings['handling_fees']) ? $current_settings['handling_fees'] : '';
                        $pricing_item->pricing = 'rate';
                        $pricing_item->flat_rate = $scale['rate_price'];
                        array_push($pricing, $pricing_item);
                    }
                }
                
                /* add live quote fallback to keep behaviour as is */
                $pricing_item = new stdClass();
                $pricing_item->price_from = '';
                $pricing_item->price_to = '';
                $pricing_item->weight_from = '';
                $pricing_item->weight_to = '';
                $pricing_item->shipping_class = $all_shipping_classes;
                $pricing_item->zones = $all_countries;
                $pricing_item->handling_fees = '';
                $pricing_item->pricing = 'live';
                $pricing_item->flat_rate = '';
                array_push($pricing, $pricing_item);
            }

            // add pricing items to emc_pricing table
            envoimoinscher_model::add_pricing($service->ope_code."_".$service->srv_code, $pricing);
            
            unset($current_settings['pricing']);
            unset($current_settings['rate_type']);

            // update MONR tracking
            if ($service->ope_code == "MONR") {
                if ($current_settings['carrier_tracking_url'] == "http://www.mondialrelay.fr/suivi-de-colis/") {
                    $current_settings['carrier_tracking_url'] = "http://www.mondialrelay.fr/ww2/public/mr_suivi.aspx?cab=@";
                }
                if ($current_settings['carrier_tracking_url'] == "https://www.ups.com/WebTracking/track?loc=fr_FR&WT.svl=PNRO_L&trackNums=@") {
                    $current_settings['carrier_tracking_url'] = "https://wwwapps.ups.com/WebTracking/track?HTMLVersion=5.0&loc=fr_FR&Requester=UPSHome&WBPM_lid=homepage%252Fct1.html_pnl_trk&track.x=Suivi&trackNums=@";
                }
            }

            update_option('woocommerce_'.$service->ope_code.'_'.$service->srv_code.'_settings', $current_settings);

        }
    }
}

function emc_update_140_delete_table_emc_scales() {
	global $wpdb;

	$wpdb->query('DROP TABLE IF EXISTS `'.$wpdb->prefix.'emc_scales`');
}

function emc_update_140_log_option() {
	// add log option
    add_option('EMC_ENABLED_LOGS', 'no');
}

function emc_update_140_db_version() {
	envoimoinscher_model::update_db_version( '1.4.0' );
}

function emc_update_200_add_default_address() {
	global $wpdb;
	// get one defined parcel point by operator
    $services = envoimoinscher_model::get_services();
    $dropoff_points = array();
    $already_added = array();
    foreach ($services as $service) {
        if ($service->srv_dropoff_point == 1 && !in_array($service->ope_code, $already_added)) {
            $current_settings = get_option("woocommerce_".$service->ope_code."_".$service->srv_code."_settings");
            if($current_settings != '') {
                if (isset ($current_settings['default_dropoff_point']) && $current_settings['default_dropoff_point'] != '') {
                    $dropoff_points[$service->ope_code] = $current_settings['default_dropoff_point'];
                    array_push($already_added, $service->ope_code);
                } else {
                    $dropoff_points[$service->ope_code] = '';
                }
            } else {
                $dropoff_points[$service->ope_code] = '';
            }
        }
    }

    // add default address
    $emc_pickup = get_option('EMC_PICKUP');
    $wpdb->insert(
        $wpdb->prefix.'emc_addresses',
        array(
            'type' => 'default',
            'active' => 1,
            'label' => 'default address',
            'gender' => get_option("EMC_CIV"),
            'first_name' => get_option("EMC_FNAME"),
            'last_name' => get_option("EMC_LNAME"),
            'company' => get_option("EMC_COMPANY"),
            'address' => get_option("EMC_ADDRESS"),
            'zipcode' => get_option("EMC_POSTALCODE"),
            'city' => get_option("EMC_CITY"),
            'phone' => get_option("EMC_TEL"),
            'email' => get_option("EMC_MAIL"),
            'add_info' => get_option("EMC_COMPL"),
            'dispo_hde' => get_option("EMC_DISPO_HDE"),
            'dispo_hle' => get_option("EMC_DISPO_HLE"),
            'pickup_day_1' => isset($emc_pickup[0]) ? $emc_pickup[0] : 2,
            'pickup_day_2' => isset($emc_pickup[1]) ? $emc_pickup[1] : 3,
            'pickup_split' => isset($emc_pickup[2]) ? $emc_pickup[2] : 17,
            'shipping_classes' => "",
            'dropoff_points' => serialize($dropoff_points),
        ),
        array(
            '%s',
            '%d',
            '%s',
            '%s',
            '%s',
            '%s',
            '%s',
            '%s',
            '%s',
            '%s',
            '%s',
            '%s',
            '%s',
            '%s',
            '%s',
            '%d',
            '%d',
            '%d',
            '%s',
            '%s',
        )
    );
}

function emc_update_200_post_metas() {
    // get default address id
    $default_address = envoimoinscher_model::get_addresses("default", true);
    $default_address = current($default_address);
    $default_address_id = $default_address['id'];
    
	// change all existing post metas
    if (function_exists('wc_get_order_statuses')) {
        $orders = get_posts( array(
                'post_type'   => 'shop_order',
                'post_status' => array_keys( wc_get_order_statuses() ),
                'numberposts' => -1
        ) );
    } else {
        $orders = get_posts( array(
            'post_type'   => 'shop_order',
            'post_status' => 'publish',
            'tax_query'   => array( array(
                'taxonomy' => 'shop_order_status',
                'field' => 'slug',
                'terms' => array( 'processing', 'completed', 'pending', 'completed', 'failed', 'on-hold', 'refunded' ),
            ) ),
            'numberposts' => -1
        ) );
    }
    $simple_metas = array(
        '_assurance_fermeture',
        '_assurance_protection',
        '_assurance_materiau',
        '_assurance_emballage',
        '_b13a',
        '_carrier_ref',
        '_connote',
        '_desc_content',
        '_desc_value',
        '_dropoff_point',
        '_dropoff_point_SOGP_RelaisColis',
        '_dropoff_point_MONR_CpourToi',
        '_dropoff_point_IMXE_PackSuiviEurope',
        '_dropoff_point_MONR_CpourToiEurope',
        '_dropoff_point_MONR_DomicileEurope',
        '_emc_carrier',
        '_emc_ref',
        '_emc_tracking',
        '_insurance',
        '_label_url',
        '_manifest',
        '_pickup_date',
        '_pickup_point',
        '_pickup_point_CHRP_ChronoRelais',
        '_pickup_point_CHRP_ChronoRelaisEurope',
        '_pickup_point_MONR_CpourToi',
        '_pickup_point_MONR_CpourToiEurope',
        '_pickup_point_SOGP_RelaisColis',
        '_pickup_point_UPSE_StandardAP',
        '_proforma',
        '_proforma_reason',
        '_remise',
        '_url_push',
        '_wrapping',
    );

    foreach($orders as $post) {
        $order = new WC_Order($post->ID);

        $suborder_key = uniqid($default_address_id.'_');

        // set multiparcels info
        $multiparcels = array();
        $multiparcels[0] = array(
            "suborder_key" => $suborder_key,
            "address_id" => $default_address_id,
            "parcels" => array(
                1 => array(
                    'weight' => get_post_meta( $order->id, '_dims_weight', true ),
                    'length' => get_post_meta( $order->id, '_dims_length', true ),
                    'width' => get_post_meta( $order->id, '_dims_width', true ),
                    'height' => get_post_meta( $order->id, '_dims_height', true ),
                )
            ),
            "products" => array()
        );

        $proforma = array();
        foreach ($order->get_items() as $item) {
            $check_id = $item['variation_id'] != 0 ? $item['variation_id'] : $item['product_id'];
            array_push($multiparcels[0]["products"], array(
                'id' => $check_id ,
                'qty' => $item['qty']
            ));

            // set proforma items to default value as we can't match data
            $_product  = $order->get_product_from_item( $item );

            $weight = envoimoinscher_model::get_product_weight($check_id);
            if( $weight == 0) {
                $weight = 0.02;
            }

            $proforma[$suborder_key][$check_id] = array(
                'post_title_en' => esc_html( $item[ 'name' ] ),
                'post_title_fr' => esc_html( $item[ 'name' ] ),
                'price' => esc_html( $item['line_subtotal'] ) / esc_html( $item['qty'] ),
                'origin' => __( 'France', 'envoimoinscher' ),
                'weight' => wc_get_weight ( $weight, 'kg' ),
            );
        }
        if (!empty($proforma)) update_post_meta( $order->id, '_proforma_items', $proforma);
        update_post_meta( $order->id, '_multiparcels', $multiparcels );

        // update simple metas (no change, just indexing by suborder_key)
        foreach($simple_metas as $meta_key) {
            if (get_post_meta( $order->id, $meta_key, true ) != '') {
                $value = get_post_meta( $order->id, $meta_key, true );
                $new_value = array(
                    $suborder_key => $value
                );
                update_post_meta($order->id, $meta_key, $new_value);
            }
        }
    }
}

function emc_update_200_alter_table() {
	global $wpdb;
    
    // if countries column exists, we need to copy the information it contains to zones
    // and then delete useless countries column
    $sql = "SELECT * FROM `".$wpdb->prefix."emc_pricing`";
    $results = $wpdb->get_results($sql, ARRAY_A);

    // check if column exists (the test is done this way and not complex SQL request for compatibility issues)
    if (isset($results[0]['countries'])) {
        $sql = "UPDATE `".$wpdb->prefix."emc_pricing` SET `zones`=`countries`;";
        $wpdb->query($sql);
        $sql = "ALTER TABLE `".$wpdb->prefix."emc_pricing` DROP COLUMN `countries`;";
        $wpdb->query($sql);
    }
}

function emc_update_200_options() {
	// add maximum weight option
    update_option('EMC_PARCEL_SPLIT', '0');
    update_option('EMC_PARCEL_MAX_DIM', '11');
}

function emc_update_200_db_version() {
	envoimoinscher_model::update_db_version('2.0.0');
}


function emc_update_210_update_options() {
	$emc_key = get_option('EMC_KEY');
    $env = get_option('EMC_ENV');
    if (strtoupper($env) == 'TEST') {
        add_option('EMC_KEY_TEST', $emc_key);
        add_option('EMC_KEY_PROD', '');
    } else {
        add_option('EMC_KEY_TEST', '');
        add_option('EMC_KEY_PROD', $emc_key);
    }
    delete_option('EMC_KEY');
}

function emc_update_210_update_authorized_categories() {
	envoimoinscher_model::load_carrier_list_api(false, false);
    envoimoinscher_model::update_categories();
    envoimoinscher_model::remove_carriers_forbidden_categories();
}

function emc_update_210_db_version() {
	envoimoinscher_model::update_db_version('2.1.0');
}
