/**
     * @param Bring_WC_Order_Adapter $order
     */
    static function render_packages($order)
    {
        $shipping_item_tip = __('Shipping item id', 'bring-fraktguiden');
        ?>
    <table class="bring-booking-packages">
      <thead>
      <tr>
        <th title="<?php 
        echo $shipping_item_tip;
        ?>
"><?php 
        _e('#', 'bring-fraktguiden');
        ?>
</th>
        <th><?php 
        _e('Product', 'bring-fraktguiden');
        ?>
</th>
        <th><?php 
        _e('Width', 'bring-fraktguiden');
        ?>
 (cm)</th>
        <th><?php 
        _e('Height', 'bring-fraktguiden');
        ?>
 (cm)</th>
        <th><?php 
        _e('Length', 'bring-fraktguiden');
        ?>
 (cm)</th>
        <th><?php 
        _e('Weight', 'bring-fraktguiden');
        ?>
 (kg)</th>
      </tr>
      </thead>
      <tbody>
      <?php 
        foreach ($order->get_packages_formatted(false, true) as $key => $package) {
            ?>
        <?php 
            $shipping_item_id = $package['shipping_item_info']['item_id'];
            $service_data = Fraktguiden_Helper::get_service_data_for_key($package['shipping_item_info']['shipping_method']['service']);
            ?>
        <tr>
          <td title="<?php 
            echo $shipping_item_tip;
            ?>
">
            <?php 
            echo $shipping_item_id;
            ?>
          </td>
          <td>
            <?php 
            echo $service_data[Fraktguiden_Helper::get_option('service_name')];
            ?>
            <?php 
            $pickup_point = $order->get_pickup_point_for_shipping_item($shipping_item_id);
            if (!empty($pickup_point)) {
                ?>
              <span class="tips"
                    data-tip="<?php 
                echo str_replace('|', '<br/>', $pickup_point['cached']);
                ?>
">
                [<?php 
                _e('Pickup Point', 'bring-fraktguiden');
                ?>
]
              </span>
              <?php 
            }
            ?>
          </td>
          <td>
            <?php 
            echo $package['dimensions']['widthInCm'];
            ?>
          </td>
          <td>
            <?php 
            echo $package['dimensions']['heightInCm'];
            ?>
          </td>
          <td>
            <?php 
            echo $package['dimensions']['lengthInCm'];
            ?>
          </td>
          <td>
            <?php 
            echo $package['weightInKg'];
            ?>
          </td>
        </tr>
      <?php 
        }
        ?>
      </tbody>
    </table>
    <?php 
    }
 /**
  * Prints rate json for a bring service.
  *
  * Only available from admin.
  * @todo: refactor!!
  */
 static function wp_ajax_get_rate()
 {
     header('Content-type: application/json');
     $result = ['success' => false, 'rate' => null, 'packages' => null];
     if (isset($_GET['post_id']) && isset($_GET['service'])) {
         $order = new WC_Order($_GET['post_id']);
         $items = $order->get_items();
         $fake_cart = [];
         foreach ($items as $item) {
             $fake_cart[uniqid()] = ['quantity' => $item['qty'], 'data' => new WC_Product_Simple($item['product_id'])];
         }
         //include( '../../common/class-fraktguiden-packer.php' );
         $packer = new Fraktguiden_Packer();
         $product_boxes = $packer->create_boxes($fake_cart);
         $packer->pack($product_boxes, true);
         $package_params = $packer->create_packages_params();
         //@todo: share / filter
         $standard_params = array('clientUrl' => $_SERVER['HTTP_HOST'], 'from' => Fraktguiden_Helper::get_option('from_zip'), 'fromCountry' => Fraktguiden_Helper::get_option('from_country'), 'to' => $order->shipping_postcode, 'toCountry' => $order->shipping_country, 'postingAtPostOffice' => Fraktguiden_Helper::get_option('post_office') == 'no' ? 'false' : 'true', 'additional' => Fraktguiden_Helper::get_option('evarsling') == 'yes' ? 'evarsling' : '');
         $params = array_merge($standard_params, $package_params);
         $url = add_query_arg($params, WC_Shipping_Method_Bring::SERVICE_URL);
         $url .= '&product=' . $_GET['service'];
         // Make the request.
         $request = new WP_Bring_Request();
         $response = $request->get($url);
         if ($response->status_code == 200) {
             $json = json_decode($response->get_body(), true);
             $service = $json['Product']['Price']['PackagePriceWithoutAdditionalServices'];
             $rate = Fraktguiden_Helper::get_option('vat') == 'exclude' ? $service['AmountWithoutVAT'] : $service['AmountWithVAT'];
             $result['success'] = true;
             $result['rate'] = $rate;
             $result['packages'] = json_encode($package_params);
         }
     }
     echo json_encode($result);
     die;
 }
 /**
  * Returns all packages for the order 'Bring booking formatted'.
  *
  * @param int|boolean $item_id_to_find
  * @param boolean $include_info
  *
  * @return array
  */
 public function get_packages_formatted($item_id_to_find = false, $include_info = false)
 {
     $result = [];
     $order_items_packages = $this->get_packages($item_id_to_find);
     if (!$order_items_packages) {
         $this->order_update_packages();
         $order_items_packages = $this->get_packages($item_id_to_find);
     }
     if (!$order_items_packages) {
         return [];
     }
     $elements = ['width', 'height', 'length', 'weightInGrams'];
     $elements_count = count($elements);
     foreach ($order_items_packages as $item_id => $package) {
         $package_count = count($package) / $elements_count;
         for ($i = 0; $i < $package_count; $i++) {
             $weight_in_kg = (int) $package['weightInGrams' . $i] / 1000;
             $data = ['weightInKg' => $weight_in_kg, 'goodsDescription' => null, 'dimensions' => ['widthInCm' => $package['width' . $i], 'heightInCm' => $package['height' . $i], 'lengthInCm' => $package['length' . $i]], 'containerId' => null, 'packageType' => null, 'numberOfItems' => null, 'correlationId' => null];
             if ($include_info) {
                 $shipping_method = '';
                 $shipping_methods = $this->get_fraktguiden_shipping_items();
                 foreach ($shipping_methods as $id => $shipping_method) {
                     if ($id == $item_id) {
                         $shipping_method = Fraktguiden_Helper::parse_shipping_method_id($shipping_method['method_id']);
                         break;
                     }
                 }
                 $data['shipping_item_info'] = ['item_id' => $item_id, 'shipping_method' => $shipping_method];
             }
             $result[] = $data;
         }
     }
     return $result;
 }
    static function generate()
    {
        global $woocommerce, $wp_version;
        ?>
    <html>
    <head>
      <meta charset="utf-8">
      <title>Fraktguiden - System Info</title>
      <style>
        body {
          font-family: "Open Sans", sans-serif;
          color: #333;
        }

        body, td {
          font-size: 13px;
          line-height: 17px;
        }

        div.main {
          width: 55%;
          margin-left: auto;
          margin-right: auto;
          text-align: center;
        }

        table {
          border-collapse: collapse;
          border: none;
        }

        td, th {
          padding: 3px 6px;
          vertical-align: top;
          border: 1px solid lightgray;
          text-align: left;
        }

        th {
          padding-top: 15px;
          padding-bottom: 15px;
        }

        table.properties td, table.properties th {
          border: 1px solid white;
        }

        table.properties td:first-child {
          background-color: lightgray;
          text-align: right;
          width: 130px;
        }

        ul {
          margin: 0;
          padding: 0 15px;
        }

      </style>
    </head>
    <body>
    <div class="main">
      <h1>System Info</h1>
      <table>
        <?php 
        $bfg_plugin_data = get_plugin_data(dirname(__DIR__) . '/bring-fraktguiden-for-woocommerce/bring-fraktguiden-for-woocommerce.php');
        $bfg_options = get_option('woocommerce_' . WC_Shipping_Method_Bring::ID . '_settings');
        self::create_header('WordPress ' . $wp_version);
        self::create_row('active_plugins', self::create_active_plugins_info());
        self::create_header('WooCommerce ' . $woocommerce->version);
        self::create_row('base_country', $woocommerce->countries->get_base_country());
        self::create_row('woocommerce_dimension_unit', get_option('woocommerce_dimension_unit'));
        self::create_row('woocommerce_weight_unit', get_option('woocommerce_weight_unit'));
        self::create_row('woocommerce_currency', get_option('woocommerce_currency'));
        self::create_row('shipping_countries', self::create_shipping_countries($woocommerce->countries->get_shipping_countries()));
        self::create_header($bfg_plugin_data['Name'] . ' ' . $bfg_plugin_data['Version']);
        self::generate_fraktguiden_options($bfg_options);
        self::create_header('Bring Fraktguiden Services');
        self::generate_fraktguiden_services_info(Fraktguiden_Helper::get_all_services_with_customer_types(), $bfg_options);
        ?>
      </table>
    </div>

    <?php 
        self::generate_script();
        ?>

    </body>
    </html>
    <?php 
        die;
    }
 /**
  * @param string $additional_info
  * @return array
  */
 static function get_sender_address($additional_info = '')
 {
     $form_fields = ['booking_address_store_name', 'booking_address_street1', 'booking_address_street2', 'booking_address_postcode', 'booking_address_city', 'booking_address_country', 'booking_address_contact_person', 'booking_address_phone', 'booking_address_email'];
     $result = [];
     foreach ($form_fields as $field) {
         $result[$field] = Fraktguiden_Helper::get_option($field);
     }
     return ["name" => $result['booking_address_store_name'], "addressLine" => $result['booking_address_street1'], "addressLine2" => $result['booking_address_street2'], "postalCode" => $result['booking_address_postcode'], "city" => $result['booking_address_city'], "countryCode" => $result['booking_address_country'], "reference" => null, "additionalAddressInfo" => $additional_info, "contact" => ["name" => $result['booking_address_contact_person'], "email" => $result['booking_address_email'], "phoneNumber" => $result['booking_address_phone']]];
 }
    public function generate_services_table_html()
    {
        $services = Fraktguiden_Helper::get_services_data();
        $selected = $this->services2;
        $field_key = $this->get_field_key('services2');
        $custom_prices = get_option($field_key . '_custom_prices');
        ob_start();
        ?>

    <tr valign="top">
      <th scope="row" class="titledesc">
        <label
            for="<?php 
        echo $field_key;
        ?>
"><?php 
        _e('Services 2', self::TEXT_DOMAIN);
        ?>
</label>
      </th>
      <td class="forminp">
        <table class="wc_shipping widefat fraktguiden-services-table">
          <thead>
          <tr>
            <th class="fraktguiden-services-table-col-enabled">Enabled</th>
            <th class="fraktguiden-services-table-col-service">Service</th>
            <th class="fraktguiden-services-table-col-custom-price">Egendefinert pris</th>
          </tr>
          </thead>
          <tbody>

          <?php 
        foreach ($services as $key => $service) {
            $id = $field_key . '_' . $key;
            $prices_field_key = $field_key . '_custom_prices[' . $key . ']';
            $custom_price = isset($custom_prices[$key]) ? $custom_prices[$key] : '';
            $checked = in_array($key, $selected);
            ?>
            <tr>
              <td class="fraktguiden-services-table-col-enabled">
                <label for="<?php 
            echo $id;
            ?>
"
                       style="display:inline-block; width: 100%">
                  <input type="checkbox" id="<?php 
            echo $id;
            ?>
"
                         name="<?php 
            echo $field_key;
            ?>
[]"
                         value="<?php 
            echo $key;
            ?>
" <?php 
            echo $checked ? 'checked' : '';
            ?>
 />
                </label>
              </td>
              <td class="fraktguiden-services-table-col-name">
                <span data-tip="<?php 
            echo $service['HelpText'];
            ?>
"
                      class="woocommerce-help-tip"></span>
                <label class="fraktguiden-service" for="<?php 
            echo $id;
            ?>
"
                       data-ProductName="<?php 
            echo $service['ProductName'];
            ?>
"
                       data-DisplayName="<?php 
            echo $service['DisplayName'];
            ?>
">
                  <?php 
            echo $service[$this->service_name];
            ?>
                </label>
              </td>
              <td class="fraktguiden-services-table-col-custom-price">
                <input type="text" name="<?php 
            echo $prices_field_key;
            ?>
"
                       value="<?php 
            echo $custom_price;
            ?>
"/>
              </td>
            </tr>
          <?php 
        }
        ?>
          </tbody>
        </table>
        <script>
          jQuery( document ).ready( function () {
            var $ = jQuery;
            $( '#woocommerce_bring_fraktguiden_service_name' ).change( function () {
              console.log( 'change', this.value );
              var val = this.value;
              $( '.fraktguiden-services-table' ).find( 'label.fraktguiden-service' ).each( function ( i, elem ) {

                var label = $( elem );
                label.text( label.attr( 'data-' + val ) );
              } );
            } );

          } );
        </script>
      </td>
    </tr>

    <?php 
        return ob_get_clean();
    }
 /**
  * Returns an array with nordic country codes
  *
  * @return array
  */
 static function get_nordic_countries()
 {
     global $woocommerce;
     $countries = array('NO', 'SE', 'DK', 'FI', 'IS');
     return Fraktguiden_Helper::array_filter_key($woocommerce->countries->countries, function ($k) use($countries) {
         return in_array($k, $countries);
     });
 }
    public function generate_services_table_html()
    {
        $services = Fraktguiden_Helper::get_services_data();
        $selected = $this->services;
        $field_key = $this->get_field_key('services');
        $custom_prices = get_option($field_key . '_custom_prices');
        $free_shipping_checks = get_option($field_key . '_free_shipping_checks');
        $free_shipping_thresholds = get_option($field_key . '_free_shipping_thresholds');
        ob_start();
        ?>

    <tr valign="top">
      <th scope="row" class="titledesc">
        <label
            for="<?php 
        echo $field_key;
        ?>
"><?php 
        _e('Services 2', 'bring-fraktguiden');
        ?>
</label>
      </th>
      <td class="forminp">
        <table class="wc_shipping widefat fraktguiden-services-table">
          <thead>
          <tr>
            <th class="fraktguiden-services-table-col-enabled">Aktiv</th>
            <th class="fraktguiden-services-table-col-service">Tjeneste</th>
            <th class="fraktguiden-services-table-col-custom-price">Egendefinert pris</th>
            <th class="fraktguiden-services-table-col-free-shipping">Gratis frakt</th>
            <th class="fraktguiden-services-table-col-free-shipping-threshold">Fraktfri grense</th>
          </tr>
          </thead>
          <tbody>

          <?php 
        foreach ($services as $key => $service) {
            $id = $field_key . '_' . $key;
            $vars = ['custom_price' => 'custom_prices', 'free_shipping' => 'free_shipping_checks', 'free_shipping_threshold' => 'free_shipping_thresholds'];
            // Extract variables from the settings data
            foreach ($vars as $var => $data_var) {
                // Eg.: ${custom_price_id} = 'woocommerce_bring_fraktguiden_services_custom_prices[SERVICEPAKKE]';
                ${$var . '_id'} = "{$field_key}_{$data_var}[{$key}]";
                ${$var} = '';
                if (isset(${$data_var}[$key])) {
                    // Eg.: $custom_price = $custom_prices['SERVICEPAKKE'];
                    ${$var} = esc_html(${$data_var}[$key]);
                }
            }
            $enabled = !empty($selected) ? in_array($key, $selected) : false;
            ?>
            <tr>
              <td class="fraktguiden-services-table-col-enabled">
                <label for="<?php 
            echo $id;
            ?>
"
                       style="display:inline-block; width: 100%">
                  <input type="checkbox" id="<?php 
            echo $id;
            ?>
"
                         name="<?php 
            echo $field_key;
            ?>
[]"
                         value="<?php 
            echo $key;
            ?>
" <?php 
            echo $enabled ? 'checked' : '';
            ?>
 />
                </label>
              </td>
              <td class="fraktguiden-services-table-col-name">
                <span data-tip="<?php 
            echo $service['HelpText'];
            ?>
"
                      class="woocommerce-help-tip"></span>
                <label class="fraktguiden-service" for="<?php 
            echo $id;
            ?>
"
                       data-ProductName="<?php 
            echo $service['ProductName'];
            ?>
"
                       data-DisplayName="<?php 
            echo $service['DisplayName'];
            ?>
">
                  <?php 
            echo $service[$this->service_name];
            ?>
                </label>
              </td>
              <td class="fraktguiden-services-table-col-custom-price">
                <input type="text" name="<?php 
            echo $custom_price_id;
            ?>
"
                       value="<?php 
            echo $custom_price;
            ?>
"
                       />
              </td>
              <td class="fraktguiden-services-table-col-free-shipping">
                <label style="display:inline-block; width: 100%">
                  <input type="checkbox" name="<?php 
            echo $free_shipping_id;
            ?>
"
                    <?php 
            echo $free_shipping ? 'checked' : '';
            ?>
>
                </label>
              </td>
              <td class="fraktguiden-services-table-col-free-shipping-threshold">
                <input type="text" name="<?php 
            echo $free_shipping_threshold_id;
            ?>
"
                       value="<?php 
            echo $free_shipping_threshold;
            ?>
"
                       placeholder="0"
                       />
              </td>
            </tr>
          <?php 
        }
        ?>
          </tbody>
        </table>
        <script>
          jQuery( document ).ready( function () {
            var $ = jQuery;
            $( '#woocommerce_bring_fraktguiden_service_name' ).change( function () {
              console.log( 'change', this.value );
              var val = this.value;
              $( '.fraktguiden-services-table' ).find( 'label.fraktguiden-service' ).each( function ( i, elem ) {

                var label = $( elem );
                label.text( label.attr( 'data-' + val ) );
              } );
            } );

          } );
        </script>
      </td>
    </tr>

    <?php 
        return ob_get_clean();
    }