/**
     * @param Bring_WC_Order_Adapter $order
     */
    static function render_consignments($order)
    {
        $consignments = $order->get_booking_consignments();
        if ($consignments) {
            ?>
      <div class="bring-consignments">
        <?php 
            foreach ($consignments as $consignment) {
                //$correlation_id     = $consignment->correlationId;
                $errors = $consignment->errors;
                $confirmation = $consignment->confirmation;
                $consignment_number = $confirmation->consignmentNumber;
                $links = $confirmation->links;
                $tracking = $links->tracking;
                $date_and_times = $confirmation->dateAndTimes;
                $earliest_pickup = $date_and_times->earliestPickup ? date_i18n(wc_date_format(), $date_and_times->earliestPickup / 1000) : 'N/A';
                $expected_delivery = $date_and_times->expectedDelivery ? date_i18n(wc_date_format(), $date_and_times->expectedDelivery / 1000) : 'N/A';
                $packages = $confirmation->packages;
                $labels_url = Bring_Booking_Labels::create_download_url($order->order->id);
                ?>
          <div>
            <table>
              <tr>
                <th colspan="2"><?php 
                printf('NO: %s', $consignment_number);
                ?>
</th>
              </tr>
              <tr>
                <td><?php 
                _e('Earliest Pickup', 'bring-fraktguiden');
                ?>
:</td>
                <td><?php 
                echo $earliest_pickup;
                ?>
</td>
              </tr>
              <tr>
                <td><?php 
                _e('Expected delivery', 'bring-fraktguiden');
                ?>
:</td>
                <td><?php 
                echo $expected_delivery;
                ?>
</td>
              </tr>
              <tr>
                <td><?php 
                _e('Labels', 'bring-fraktguiden');
                ?>
:</td>
                <td>
                  <a href="<?php 
                echo $labels_url;
                ?>
"
                     target="_blank"><?php 
                _e('Download', 'bring-fraktguiden');
                ?>
</a>
                </td>
              </tr>
              <tr>
                <td><?php 
                _e('Tracking', 'bring-fraktguiden');
                ?>
:</td>
                <td>
                  <a href="<?php 
                echo $tracking;
                ?>
"
                     target="_blank"><?php 
                _e('View', 'bring-fraktguiden');
                ?>
                    →</a>
                </td>
              </tr>
              <tr>
                <td>
                  <?php 
                _e('Packages', 'bring-fraktguiden');
                ?>
:
                </td>
                <td>
                  <ul>
                    <?php 
                foreach ($packages as $package) {
                    //$correlation_id = property_exists( $package, 'correlationId' ) ? $package->correlationId : 'N/A';
                    ?>
                      <li style="position: relative">
                        <span class="bring-package"></span>
                        <?php 
                    printf('NO: %s', $package->packageNumber);
                    ?>
                      </li>
                    <?php 
                }
                ?>
                  </ul>
                </td>
              </tr>
            </table>
          </div>
          <?php 
            }
            ?>
      </div>
      <?php 
        }
    }
 private static function generate_fraktguiden_options($options)
 {
     $is_pro = class_exists('WC_Shipping_Method_Bring_Pro');
     self::create_row('pro', $is_pro ? 'yes' : 'no');
     foreach ($options as $key => $option) {
         $val = '';
         if (gettype($option) == 'array') {
             $val .= '<ul>';
             foreach ($option as $o) {
                 $val .= '<li>' . $o . '</li>';
             }
             $val .= '</ul>';
         } else {
             $val = $option;
         }
         if ($key == 'mybring_api_key') {
             $val = '*******';
         }
         self::create_row($key, $val);
     }
     if ($is_pro) {
         self::create_row('labels_directory', Bring_Booking_Labels::get_local_dir());
     }
 }
    /**
     *
     */
    static function add_bulk_admin_footer()
    {
        global $post_type;
        if ($post_type == 'shop_order') {
            ?>
      <script type="text/template" id="tmpl-bring-modal-bulk">
        <div class="wc-backbone-modal">
          <div class="wc-backbone-modal-content">
            <section class="wc-backbone-modal-main" role="main">
              <header class="wc-backbone-modal-header">
                <h1 class="bgf-modal-header"><?php 
            echo __('Bring Booking', 'bring-fraktguiden');
            ?>
</h1>
                <button
                    class="modal-close modal-close-link dashicons dashicons-no-alt">
                  <span class="screen-reader-text">Close modal panel</span>
                </button>
              </header>
              <article>
                <div class="bring-form-field" style="margin-top:0">
                  <?php 
            echo __('This will only book orders that has not been booked.', 'bring-fraktguiden');
            ?>
                </div>
                <div class="bring-form-field">
                  <label><?php 
            echo __('Selected orders', 'bring-fraktguiden');
            ?>
                    :</label>
                  <span class="bring-modal-selected-orders-list"></span>
                </div>
                <div class="bring-form-field">
                  <label><?php 
            echo __('MyBring Customer', 'bring-fraktguiden');
            ?>
                    :</label>
                  <?php 
            Bring_Booking_Common_View::render_customer_selector('_bring-modal-customer-selector');
            ?>
                </div>
                <div class="bring-form-field">
                  <label><?php 
            echo __('Shipping Date', 'bring-fraktguiden');
            ?>
                    :</label>
                  <?php 
            Bring_Booking_Common_View::render_shipping_date_time('_bring-modal-shipping-date');
            ?>
                </div>
              </article>
              <footer>
                <div class="inner">
                  <button id="btn-ok"
                          class="button button-primary button-large"><?php 
            echo Bring_Booking_Common_View::booking_label(true);
            ?>
</button>
                </div>
              </footer>
            </section>
          </div>
        </div>
        <div class="wc-backbone-modal-backdrop modal-close"></div>
      </script>

      <script type="text/javascript">
        (function () {
          var $ = jQuery;

          $( document ).ready( function () {

            // Add bulk booking to action selector
            $( '<option>' ).val( 'bring_bulk_book' ).text( '<?php 
            echo Bring_Booking_Common_View::booking_label(true);
            ?>
' ).appendTo( "select[name='action']" );
            $( '<option>' ).val( 'bring_bulk_book' ).text( '<?php 
            echo Bring_Booking_Common_View::booking_label(true);
            ?>
' ).appendTo( "select[name='action2']" );

            // Add bulk print to action selector
            $( '<option>' ).val( 'bring_print_labels' ).text( '<?php 
            _e('Bring - Print labels', 'bring-fraktguiden');
            ?>
' ).appendTo( "select[name='action']" );
            $( '<option>' ).val( 'bring_print_labels' ).text( '<?php 
            _e('Bring - Print labels', 'bring-fraktguiden');
            ?>
' ).appendTo( "select[name='action2']" );

            //@todo: does this need to be global?
            var modal = $( {} );

            var form = $( 'form#posts-filter' );

            // Add input for form filter submit from modal.
            var customer_number = $( '<input type="hidden" name="_bring-customer-number" value="">' );
            var shipping_date = $( '<input type="hidden" name="_bring-shipping-date" value="">' );
            var shipping_date_hour = $( '<input type="hidden" name="_bring-shipping-date-hour" value="">' );
            var shipping_date_minutes = $( '<input type="hidden" name="_bring-shipping-date-minutes" value="">' );

            form.append( customer_number );
            form.append( shipping_date );
            form.append( shipping_date_hour );
            form.append( shipping_date_minutes );

            function get_checked_order_ids() {
              var result = [];
              $( '#the-list' ).find( 'input[type=checkbox]:checked' ).each( function ( i, elem ) {
                result.push( elem.value );
              } );
              return result;
            }


            function show_bulk_book_dialog() {
              // Open dialog.
              modal.WCBackboneModal( {
                template: 'bring-modal-bulk'
              } );

              // Initialize data picker.
              $( "[name=_bring-modal-shipping-date]" ).datepicker( {
                minDate: 0,
                dateFormat: 'yy-mm-dd'
              } );

              // Disable dialog submit button if no orders are checked.
              var order_ids = get_checked_order_ids();
              if ( order_ids.length == 0 ) {
                $( '#btn-ok' ).attr( 'disabled', 'true' );
              }
              else {
                $( '#btn-ok' ).removeAttr( 'disabled' );
              }

              // Print order ids in dialog.
              $( '.bring-modal-selected-orders-list' ).text( order_ids.join( ' - ' ) );
            }


            $( '#doaction' ).click( function ( evt ) {
              if ( $( "select[name='action']" ).val() == 'bring_bulk_book' ) {
                show_bulk_book_dialog();
                evt.preventDefault();
              }

              if ( $( "select[name='action']" ).val() == 'bring_print_labels' ) {
                var url = '<?php 
            echo Bring_Booking_Labels::create_download_url('');
            ?>
';

                url = url + get_checked_order_ids().join(',');

                window.open(url);
                evt.preventDefault();
              }
            } );


            $( '#doaction2' ).click( function ( evt ) {
              if ( $( "select[name='action2']" ).val() == 'bring_bulk_book' ) {
                show_bulk_book_dialog();
                evt.preventDefault();
              }

              if ( $( "select[name='action']" ).val() == 'bring_print_labels' ) {
                evt.preventDefault();
              }
            } );

            $( document.body ).on( 'wc_backbone_modal_response', function ( e ) {
              customer_number.val( $( '[name=_bring-modal-customer-selector]' ).val() );
              shipping_date.val( $( '[name=_bring-modal-shipping-date]' ).val() );
              shipping_date_hour.val( $( '[name=_bring-modal-shipping-date-hour]' ).val() );
              shipping_date_minutes.val( $( '[name=_bring-modal-shipping-date-minutes]' ).val() );
              form.submit();
            } );

          } );
        })();
      </script>
      <?php 
        }
    }
 /**
  * @param WC_Order $wc_order
  */
 static function send_booking($wc_order)
 {
     $order = new Bring_WC_Order_Adapter($wc_order);
     $order_id = $wc_order->id;
     $test_mode = self::is_test_mode();
     $api_key = self::get_api_key();
     $api_uid = self::get_api_uid();
     $client_url = self::get_client_url();
     $customer_number = isset($_REQUEST['_bring-customer-number']) ? $_REQUEST['_bring-customer-number'] : '';
     if (isset($_REQUEST['_bring-shipping-date']) && isset($_REQUEST['_bring-shipping-date-hour']) && isset($_REQUEST['_bring-shipping-date-minutes'])) {
         $shipping_date_time = $_REQUEST['_bring-shipping-date'] . 'T' . $_REQUEST['_bring-shipping-date-hour'] . ':' . $_REQUEST['_bring-shipping-date-minutes'] . ':00';
     } else {
         $shipping_date = self::create_shipping_date();
         $shipping_date_time = $shipping_date['date'] . "T" . $shipping_date['hour'] . ":" . $shipping_date['minute'] . ":00";
     }
     $additional_info = '';
     if (isset($_REQUEST['_bring_additional_info'])) {
         $additional_info = filter_var($_REQUEST['_bring_additional_info'], FILTER_SANITIZE_STRING);
     }
     $sender_address = self::get_sender_address($additional_info);
     $recipient_address = $order->get_recipient_address_formatted();
     // One booking request per. order shipping item.
     foreach ($order->get_fraktguiden_shipping_items() as $item_id => $shipping_method) {
         $service_id = Fraktguiden_Helper::parse_shipping_method_id($shipping_method['method_id'])['service'];
         $packages = $order->get_packages_formatted($item_id);
         $pickup_point = $order->get_pickup_point_for_shipping_item_formatted($item_id);
         $booking_request = new Bring_Booking_Request(new WP_Bring_Request());
         $booking_request->set_test_mode($test_mode)->set_content_type('application/json')->set_accept('application/json')->set_api_key($api_key)->set_api_uid($api_uid)->set_client_url($client_url);
         $consignment = new Bring_Booking_Consignment_Creator();
         $consignment->set_purchase_order($order_id)->set_shipping_date_time($shipping_date_time)->set_sender_address($sender_address)->set_recipient_address($recipient_address)->set_product_id($service_id)->set_customer_number($customer_number)->set_packages($packages);
         if (!empty($pickup_point)) {
             $consignment->set_pickup_point($pickup_point);
         }
         if (Fraktguiden_Helper::get_option('evarsling') == 'yes') {
             $product_services = ['recipientNotification' => ['email' => $recipient_address['contact']['email'], 'mobile' => $recipient_address['contact']['phoneNumber']]];
             $consignment->set_product_services($product_services);
         }
         $booking_request->add_consignment_data($consignment->create_data());
         // Start sending the booking
         if ($booking_request->is_valid()) {
             $original_order_status = $wc_order->get_status();
             // Set order status to awaiting shipping.
             $wc_order->update_status('wc-bring-shipment');
             // Send the booking.
             $response = $booking_request->send();
             // Save the response json to the order.
             $order->update_booking_response($response);
             // Download labels pdf
             if (!$order->has_booking_errors()) {
                 Bring_Booking_Labels::download_to_local($order);
             }
             // Create new status and order note.
             if (!$order->has_booking_errors()) {
                 // Check if the plugin has been configured to set a specific order status after success.
                 $status = Fraktguiden_Helper::get_option('auto_set_status_after_booking_success');
                 if ($status == 'none') {
                     // Set status back to the previous status
                     $status = $original_order_status;
                 }
                 $status_note = __("Booked with Bring" . "\n", 'bring-fraktguiden');
             } else {
                 // If there are errors, set the status back to the original status.
                 $status = $original_order_status;
                 $status_note = __("Booking errors. See the Bring Booking box for details." . "\n", 'bring-fraktguiden');
             }
             // Update status.
             $wc_order->update_status($status, $status_note);
         } else {
             // @todo: Not valid. show message?
         }
     }
 }
 static function open_pdfs()
 {
     add_submenu_page(null, 'Download', 'Download', 'manage_woocommerce', 'bring_labels', function () {
         if (!isset($_GET['order_ids']) || $_GET['order_ids'] == '') {
             return;
         }
         $current_user = wp_get_current_user();
         // ID 0 is a not an user.
         if ($current_user->ID == 0) {
             exit;
         }
         // Admins and managers can download all orders.
         $can_download = in_array('manage_woocommerce', $current_user->roles) || in_array('administrator', $current_user->roles);
         if (!$can_download) {
             exit;
         }
         $order_ids = explode(',', $_GET['order_ids']);
         $files_to_merge = [];
         foreach ($order_ids as $order_id) {
             $order = new Bring_WC_Order_Adapter(new WC_Order($order_id));
             if (!$order->has_booking_consignments()) {
                 continue;
             }
             $consignments = $order->get_booking_consignments();
             foreach ($consignments as $consignment) {
                 $confirmation = $consignment->confirmation;
                 $consignment_number = $confirmation->consignmentNumber;
                 $file_path = Bring_Booking_Labels::get_file_path($order->order->id, $consignment_number);
                 if (file_exists($file_path)) {
                     $files_to_merge[] = Bring_Booking_Labels::get_file_path($order->order->id, $consignment_number);
                 }
             }
         }
         include_once FRAKTGUIDEN_PLUGIN_PATH . '/vendor/myokyawhtun/pdfmerger/PDFMerger.php';
         $merger = new PDFMerger();
         foreach ($files_to_merge as $file) {
             $merger->addPDF($file);
         }
         $merge_result_file = Bring_Booking_Labels::get_local_dir() . '/labels-merged.pdf';
         $merger->merge('file', $merge_result_file);
         header("Content-Length: " . filesize($merge_result_file));
         header("Content-type: application/pdf");
         header("Content-disposition: inline; filename=" . basename($merge_result_file));
         header('Expires: 0');
         header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
         // Workaround for Chrome's inline pdf viewer
         ob_clean();
         flush();
         readfile($merge_result_file);
         exit;
     });
 }