<?php
/**
 * EMC Carriers Settings
 */

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

if ( ! class_exists( 'emc_settings_carriers' ) ) :

/**
 * emc_settings_carriers
 */
class emc_settings_carriers extends emc_admin_settings {

   /**
    * Constructor.
    */
    public function __construct() {
        $this->id = 'carriers';
		$this->label = __( 'Carriers', 'envoimoinscher' );
        add_filter( 'emc_settings_tabs_array', array( &$this, 'add_tab' ), 20 );
	}

	/**
	 * Get sections
	 *
	 * @return array
	 */
	public function get_subtabs() {

		$subtabs = array(
			'' => __( 'Weight based carriers', 'envoimoinscher' ),
			'advanced_carriers' => __( 'Weight/Dimensions based carriers', 'envoimoinscher' ),
			'weight_options' => __( 'Multi-parcel and weight options', 'envoimoinscher' ),
			'display' => __( 'Front office display', 'envoimoinscher' ),
		);

		return $subtabs;
	}

    /**
	 * Get settings array
	 * @param $memory_limit limit ressources usage (for activation only)
	 * @return array
	 */
	public function get_settings($memory_limit = false) {
        $current_subtab = isset($_GET['subtab']) ? sanitize_title( $_GET['subtab'] ) : '';

        if ($current_subtab == 'display') {
            $settings = array(
                0 => array(
                    'section_id' => 'display_options',
                    'section_title' => __( 'Display', 'envoimoinscher' ),
                    'fields' => array(
                        0 => array(
                            'title' => __( 'Carrier logos', 'envoimoinscher' ),
                            'desc' => __( 'Uncheck this box to hide carrier logos in front office.', 'envoimoinscher' ),
                            'id' => 'EMC_CARRIER_DISPLAY',
                            'type' => 'checkbox',
                            'default' => 'yes',
                            'desc_tip' => true,
                        ),
                        1 => array(
                            'title' => __( 'Label for delivery date', 'envoimoinscher' ),
                            'desc' => __( 'You can customize delivery date front-office message. Example: "Delivery planned on: {DATE}". Leaving the field empty hides the delivery date.', 'envoimoinscher' ),
                            'id' => 'EMC_LABEL_DELIVERY_DATE',
                            'type' => 'multilingual_text',
                            'default' => array(
                                'fr_FR' => 'Livraison prévue le : {DATE}',
                                'en_US' => 'Delivery on: {DATE}',
                            ),
                            'desc_tip' => false,
                        ),
                    ),
                )
            );
        } else {
            $settings = array();
        }

        return $settings;
    }

	/**
	 * Output the settings
	 */
	public function output() {
		$current_subtab = isset($_GET['subtab']) ? sanitize_title( $_GET['subtab'] ) : '';

		if ($current_subtab == 'weight_options'){
			$this->output_weight_options();
		} elseif ($current_subtab == 'display') {
            parent::output();
		} else {
			$this->output_carrier_list( );
		}
	}

	/**
	 * Save settings
	 */
	public function save() {
		$current_subtab = isset($_GET['subtab']) ? sanitize_title( $_GET['subtab'] ) : '';

		if ($current_subtab == 'weight_options'){
			$this->save_weight_options();
		} elseif ($current_subtab == 'display') {
            parent::save();
		} else {
			$this->save_carrier_list();
		}
	}

	/**
	 * Output weight options
	 */
	public function output_weight_options() {

        $current_subtab = isset($_GET['subtab']) ? sanitize_title( $_GET['subtab'] ) : '';

		$dims = envoimoinscher_model::get_dimensions();
        $services = envoimoinscher_model::get_emc_active_shipping_methods();

        // we look for the highest dimension at which a carrier is available
        $carrier_upper_limit = array();
        foreach (array_reverse($dims) as $dim) {
            $carrier_upper_limit[$dim->dim_id] = array();
            if (count($services) == 0) {
                continue;
            }
            foreach ($services as $key => $carrier_code) {
                if (!isset(envoimoinscher_model::$max_dimensions[$carrier_code])) {
                    continue;
                }
                $max_dims = envoimoinscher_model::$max_dimensions[$carrier_code];

                // check max weight
                if ((float)$max_dims['max_weight'] < (float)$dim->dim_weight) {
                    continue;
                }

                // sort dimensions
                $s = array(
                    'length' => $dim->dim_length,
                    'width' => $dim->dim_width,
                    'height' => $dim->dim_height,
                );
                arsort($s);

                // check longest side
                if ((float)$max_dims['longest_side'] < (float)current($s)) {
                    continue;
                }

                // check formula
                $formula = str_replace('{length}', $s['length'], $max_dims['formula']);
                $formula = str_replace('{width}', $s['width'], $formula);
                $formula = str_replace('{height}', $s['height'], $formula);
                if ((float)$max_dims['formula_max_value'] < eval('return (float)'.$formula.';')) {
                    continue;
                }

                // if carrier is valid, include in carrier_upper_limit
                array_push($carrier_upper_limit[$dim->dim_id], $carrier_code);
                unset($services[$key]);
            }
        }

        $language = get_locale();
		include( dirname ( dirname( __FILE__ ) ) . '/views/html-admin-carriers-weight-options.php');
	}

	/**
	 * Save weight options
	 */
	public function save_weight_options() {

		if ( empty( $_POST ) ) {
			return false;
		}

        if (isset($_POST['EMC_PARCEL_SPLIT'])) {
            update_option('EMC_PARCEL_SPLIT', $_POST['EMC_PARCEL_SPLIT']);
        }

        if (isset($_POST['EMC_PARCEL_MAX_DIM'])) {
            update_option('EMC_PARCEL_MAX_DIM', $_POST['EMC_PARCEL_MAX_DIM']);
        }

        // save weight option table
        global $wpdb;
        $from_weight = 0; // Initialize
        //update dimensions
        $i = 1;
        $weight_options = array();
        while (isset($_POST['id'.$i])) {
            if (isset($_POST['length'.$i]) && isset($_POST['width'.$i])
                && isset($_POST['height'.$i])&& isset($_POST['weight'.$i])
                && !(isset($_POST['ignore'.$i]) && $_POST['ignore'.$i] == "ignore")) {
                // we index by weight in order to sort values
                $weight_options[''.((float)$_POST['weight'.$i])] = array(
                    'dim_length' => $_POST['length'.$i],
                    'dim_width' => $_POST['width'.$i],
                    'dim_height' => $_POST['height'.$i],
                    'dim_weight' => $_POST['weight'.$i],
                );
            }
            $i++;
        }

        ksort($weight_options);

        // reset weight options table
        $wpdb->query('DELETE FROM '.$wpdb->prefix.'emc_dimensions');

        // add weight_from with 0 for first iteration and insert rows
        $j = 1;
        foreach ($weight_options as $row) {
            if ($j == 1) {
                $row['dim_weight_from'] = 0;
            } else {
                $row['dim_weight_from'] = $from_weight;
            }
            $from_weight = $row['dim_weight'];

            // insert row
            $wpdb->insert(
                $wpdb->prefix.'emc_dimensions',
                array(
                    'dim_id' => $j,
                    'dim_length' => $row['dim_length'],
                    'dim_width' => $row['dim_width'],
                    'dim_height' => $row['dim_height'],
                    'dim_weight_from' => $row['dim_weight_from'],
                    'dim_weight' => $row['dim_weight'],
                ),
                array(
                    '%d',
                    '%d',
                    '%d',
                    '%d',
                    '%f',
                    '%f',
                )
            );
            $j++;
        }
        envoimoinscher_model::handle_sql_error();
	}

	/**
	 * Output carrier list
	 */
	public function output_carrier_list( ) {

        $current_subtab = isset($_GET['subtab']) ? sanitize_title( $_GET['subtab'] ) : '';

		$carrier_list = envoimoinscher_model::get_services();

		$active_carriers = envoimoinscher_model::get_emc_active_shipping_methods();

        if(empty($carrier_list)) {
            $initial = true;
        } else {
            $initial = false;
        }

        $current_content = envoimoinscher_model::get_current_content();
        if (isset($current_content['id'])) {
            $authorized_operators = envoimoinscher_model::get_operators_by_content($current_content['id']);
        } else {
            $authorized_operators = false;
        }

		include( dirname ( dirname( __FILE__ ) ) . '/views/html-admin-carriers-carrier-list.php');
	}

	/**
	 * Save carriers
	 */
	public function save_carrier_list() {
		if ( empty( $_POST ) ) {
			return false;
		} elseif ( isset( $_POST['refresh'] ) || isset( $_POST['refresh_w_override'] ) ) {
			$return = envoimoinscher_model::load_carrier_list_api(false, isset($_POST['refresh_w_override']) ? true : false);
			if($return === true) {
                $notice = array(
                    'type' => "simple-notice",
                    'status' => 'success',
                    'message' => 'Your carrier list has been successfully updated.',
                    'placeholders' => array(),
                    'autodestruct' => 1
                );
                emc_admin_notices::add_custom_notice('carrier_list_refresh', $notice);
            } else {
                $notice = array(
                    'type' => "simple-notice",
                    'status' => 'failure',
                    'message' => $return,
                    'placeholders' => array(),
                    'autodestruct' => 1
                );
                emc_admin_notices::add_custom_notice('carrier_list_refresh', $notice);
            }
            $return = envoimoinscher_model::update_categories();
            if($return === true) {
                $notice = array(
                    'type' => "simple-notice",
                    'status' => 'success',
                    'message' => 'Your shipment content list has been successfully updated.',
                    'placeholders' => array(),
                    'autodestruct' => 1
                );
                emc_admin_notices::add_custom_notice('categories_update', $notice);
            } else {
                $notice = array(
                    'type' => "simple-notice",
                    'status' => 'failure',
                    'message' => $return,
                    'placeholders' => array(),
                    'autodestruct' => 1
                );
                emc_admin_notices::add_custom_notice('categories_update', $notice);
            }
            envoimoinscher_model::remove_carriers_forbidden_categories();
		} elseif ( isset( $_POST['flush'] ) ) {
			$return = envoimoinscher_model::flush_rates_cache();

			if($return !== false) {
                $notice = array(
                    'type' => "simple-notice",
                    'status' => 'success',
                    'message' => 'Your cache has been successfully flushed.',
                    'placeholders' => array(),
                    'autodestruct' => 1
                );
                emc_admin_notices::add_custom_notice('flush_cache', $notice);
            } else {
                $notice = array(
                    'type' => "simple-notice",
                    'status' => 'failure',
                    'message' => 'An error occurred while flushing your cache.',
                    'placeholders' => array(),
                    'autodestruct' => 1
                );
                emc_admin_notices::add_custom_notice('flush_cache', $notice);
            }
		} else {
			// save carriers
			$current_subtab = isset($_GET['subtab']) ? $_GET['subtab'] : '';
			$emc_services = get_option( 'EMC_SERVICES' , array ( 1 => array(), 2 => array() ) );
			$posted_services = array();
			if ( isset ( $_POST['offers'] ) && !empty ( $_POST['offers'] ) ) {
				foreach ( $_POST['offers'] as $key => $value ) {
					array_push ( $posted_services, $value );
				}
			}

			if ( $current_subtab == 'advanced_carriers' ) {
				$emc_services[2] = $posted_services;
			}
			else {
				$emc_services[1] = $posted_services;
			}

			update_option( 'EMC_SERVICES', $emc_services );

			// set default values for automatically activating service
            if (!envoimoinscher_model::is_zones_enabled()) {
                $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( $posted_services as $value ){
				if ( get_option( 'woocommerce_' . $value . '_settings' ) ){
					$option = get_option( 'woocommerce_' . $value . '_settings' );
					$option['enabled'] = 'yes';
					update_option( 'woocommerce_' . $value . '_settings',  $option );
				} else {
					$service = envoimoinscher_model::get_service_by_carrier_code($value);

                    // get default tracking urls
                    $tracking_urls = envoimoinscher_model::$tracking_urls;

					$option = array(
						'enabled' => 'yes',
						'srv_name' => @unserialize($service->srv_name),
						'srv_description' => @unserialize($service->srv_description),
						'carrier_tracking_url' => isset($tracking_urls[$value]) ? $tracking_urls[$value] : '',
					);
					update_option( 'woocommerce_' . $value . '_settings', $option );

                    // add pricing item
                    $pricing = new stdClass();
                    $pricing->price_from = '';
                    $pricing->price_to = '';
                    $pricing->weight_from = '';
                    $pricing->weight_to = '';
                    $pricing->shipping_class = $all_shipping_classes;
                    $pricing->zones = isset($all_countries) ? $all_countries:'';
                    $pricing->handling_fees = '';
                    $pricing->pricing = 'live';
                    $pricing->flat_rate = '';
                    envoimoinscher_model::add_pricing($value, array(0 => $pricing));
				}
			}
		}
	}

}

endif;
