{{ header }}{{ column_left }}
<div id="content">
  <div class="page-header">
    <div class="container-fluid">
      <div class="pull-right"> <a href="{{ cancel }}" data-toggle="tooltip" title="{{ button_cancel }}" class="btn btn-default"><i class="fa fa-reply"></i></a> </div>
      <h1>{{ text_confirm_title }}</h1>
      <ul class="breadcrumb">
        {% for breadcrumb in breadcrumbs %}
          <li><a href="{{ breadcrumb.href }}">{{ breadcrumb.text }}</a></li>
        {% endfor %}
      </ul>
    </div>
  </div>
  <div class="container-fluid">
    <div class="panel panel-default">
      <div class="panel-body">
        <div class="alert alert-info text-center"><h3 style="margin-bottom: 0px;">{{ text_confirm_change_text }}: <strong>{{ status_mapped[change_order_status_id] }}</strong></h3></div>
        <table class="table table-bordered">
          <thead>
          <tr>
            <th class="text-center">{{ column_order_id }}</th>
            <th class="text-center">{{ column_market_order_ref }}</th>
            <th class="text-center">{{ column_channel }}</th>
            <th class="text-center">{{ column_customer }}</th>
            <th class="text-center">{{ column_status }}</th>
            <th class="text-center">{{ column_date_added }}</th>
            <th class="text-left">{{ column_additional }}</th>
            <th class="text-left">{{ column_comments }}</th>
            <th class="text-center"><input type="checkbox" name="notify_all" id="notify-all" value="1" /><br />{{ column_send_mail }}</th>
            <th class="text-center">{{ column_option }}</th>
          </tr>
          </thead>
          <tbody>
          <input type="hidden" name="order_status_id" id="order-status-id" value="{{ change_order_status_id }}"/>
          {% for order in orders %}
            <tr id="row-order-id-{{ order.order_id }}" class="">
              <input type="hidden" class="order-id" value="{{ order.order_id }}" />
              <input type="hidden" id="old-status-id-{{ order.order_id }}" value="{{ order.order_status_id }}" />
              <input type="hidden" id="order-channel-{{ order.order_id }}" value="{{ order.channel }}" />

              <td class="text-center">{{ order.order_id }}</td>
              <td class="text-center">{{ order.market_order_ref }}</td>
              <td class="text-center">{{ order.channel }}</td>
              <td class="text-left">{{ order.customer }}</td>
              <td class="text-center" id="status-text-{{ order.order_id }}">{{ order.status }}</td>
              <td class="text-center">{{ order.date_added }}</td>
              <td class="text-left" id="additional-info-{{ order.order_id }}">

                {% if order.channel == 'eBay' %}
                  {% if change_order_status_id == ebay_status_shipped_id %}
                    <div class="form-group">
                      <label class="control-label">{{ entry_carrier }}</label>
                      <select name="carrier_id" class="form-control marketplace-data-{{ order.order_id }}">
                        {% for carrier in market_options.ebay.carriers %}
                          <option{% if carrier.description == order.shipping_method %} selected{% endif %}>{{ carrier.description }}</option>
                        {% endfor %}
                      </select>
                    </div>
                    <div class="form-group">
                      <label class="control-label">{{ entry_tracking_no }}</label>
                      <input type="text" name="tracking_no" value="" placeholder="{{ entry_tracking_no }}" class="form-control marketplace-data-{{ order.order_id }}" />
                    </div>
                  {% endif %}
                {% endif %}

                {% if order.channel == 'Amazon EU' %}
                  {% if change_order_status_id == openbay_amazon_order_status_shipped %}
                    <div class="form-group">
                      <label class="control-label">{{ entry_carrier }}</label>
                      <select name="courier_id" class="form-control amazon_carrier marketplace-data-{{ order.order_id }}" id="amazon_carrier_{{ order.order_id }}">
                        {% for carrier in market_options.amazon.carriers %}
                          <option{% if carrier == market_options.amazon.default_carrier %} selected{% endif %}>{{ carrier }}</option>
                        {% endfor %}
                        <option value="other">{{ text_other }}</option>
                      </select>
                    </div>
                    <div class="form-group">
                      <label class="control-label">{{ entry_other }}</label>
                      <input type="text" name="courier_other" value="" placeholder="{{ entry_other }}" class="form-control marketplace-data-{{ order.order_id }}" id="amazon_carrier_{{ order.order_id }}_other" />
                    </div>
                    <div class="form-group">
                      <label class="control-label">{{ entry_tracking_no }}</label>
                      <input type="text" name="tracking_no" value="" placeholder="{{ entry_tracking_no }}" class="form-control marketplace-data-{{ order.order_id }}" />
                    </div>
                  {% endif %}
                {% endif %}

                {% if order.channel == 'Amazon US' %}
                  {% if change_order_status_id == openbay_amazonus_order_status_shipped %}
                    <div class="form-group">
                      <label class="control-label">{{ entry_carrier }}</label>
                      <select name="courier_id" class="form-control amazonus_carrier marketplace-data-{{ order.order_id }}" id="amazonus_carrier_{{ order.order_id }}">
                        {% for carrier in market_options.amazonus.carriers %}
                          <option{% if carrier == market_options.amazonus.default_carrier %} selected{% endif %}>{{ carrier }}</option>
                        {% endfor %}
                        <option value="other">{{ text_other }}</option>
                      </select>
                    </div>
                    <div class="form-group">
                      <label class="control-label">{{ entry_other }}</label>
                      <input type="text" name="courier_other" value="" placeholder="{{ entry_other }}" class="form-control marketplace-data-{{ order.order_id }}" id="amazonus_carrier_{{ order.order_id }}_other" />
                    </div>
                    <div class="form-group">
                      <label class="control-label">{{ entry_tracking_no }}</label>
                      <input type="text" name="tracking_no" value="" placeholder="{{ entry_tracking_no }}" class="form-control marketplace-data-{{ order.order_id }}" />
                    </div>
                  {% endif %}
                {% endif %}

              </td>
              <td class="text-left" id="comments-{{ order.order_id }}"><textarea name="comments" class="form-control" rows="2" id="order-comments-{{ order.order_id }}"></textarea></td>
              <td class="text-center" id="notify-{{ order.order_id }}">
                {% if order.channel == 'Amazon EU' or order.channel == 'Amazon US' %}
                  <input type="hidden" name="notify" id="order-notify-{{ order.order_id }}" value="0" />
                  <i class="fa fa-times-circle-o" data-toggle="tooltip" title="{{ text_link_policy }}"></i>
                {% else %}
                  <input class="notify-checkbox" type="checkbox" name="notify" id="order-notify-{{ order.order_id }}" value="1" />
                {% endif %}
              </td>
              <td class="text-center">
                <a href="{{ order.view_order_link }}" data-toggle="tooltip" title="{{ text_view_order }}" class="btn btn-info" target="_blank"><i class="fa fa-eye"></i></a>
                <button class="btn btn-danger button-remove-order" onclick="removeOrderFromUpdate({{ order.order_id }}); return false;" data-toggle="tooltip" title="{{ button_remove_order }}"><i class="fa fa-trash-o"></i></button>
              </td>
            </tr>
          {% endfor %}
          </tbody>
        </table>
        <div class="pull-right"> <button id="button-update-orders" class="btn btn-primary">{{ button_update }}</button> </div>
      </div>
    </div>

    <div class="row" style="display:none;" id="status-update-summary-container">
      <div class="col-md-4 col-md-offset-4">
        <div class="panel">
          <div class="panel-body">
            <table class="table table-bordered table-hover">
              <tbody>
              <tr>
                <td style="width: 80%;">{{ text_total }}</td>
                <td id="report-orders-total" class="text-center"></td>
              </tr>
              <tr>
                <td style="width: 80%;">{{ text_successful }}</td>
                <td id="report-total-success" class="text-center"></td>
              </tr>
              <tr>
                <td style="width: 80%;">{{ text_failed }}</td>
                <td id="report-total-error" class="text-center"></td>
              </tr>
              </tbody>
            </table>
            <div class="pull-right"> <a href="{{ cancel }}" id="button-finished" class="btn btn-primary">{{ button_finished }}</a></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true" id="overlay-processing" data-backdrop="static" data-keyboard="false">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-body">
        <div class="progress">
          <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="1" aria-valuemin="0" aria-valuemax="100" style="width: 0%" id="loading-bar"></div>
        </div>
        <p class="text-center">{{ text_order_id }}<span id="status-message-order-id">"waiting for id"</span>. {{ text_modal_status_1 }}<span id="status-message-current-count">0</span>{{ text_modal_status_2 }}<span id="status-message-total-count"></span>{{ text_modal_status_3 }}</p>
      </div>
    </div>
  </div>
</div>

<input type="hidden" id="orders-total" value="{{ order_count }}" />
<input type="hidden" id="orders-total-success" value="0" />
<input type="hidden" id="orders-total-fail" value="0" />
<input type="hidden" id="orders-total-processed" value="0" />

<script type="text/javascript"><!--
  // @todo - should the orders be locked? this might take a while and a status update might happen

  // @todo another time
  // button to open api options in new tab OR abort the update
  // correct / add permissions
  // button to retry (would retry ONLY the OC order history update) then continue loop


  // if success then remove order table row/data add replace row with order_id, customer, new status, order channel, date added, text version of the data sent to marketplace ie courier and last field if email was sent or not
  // if error then add error message, based on severity/type proceed with std status update. Was it a failure or just a warning/info


  // if error then add error message (only 3 options; browser connect error, permissions or order id not found). Permissions should have been checked before page is loaded but may change by accident
  // if connect error, sleep 10 second and try again - do this 3 times in case server is busy. If fails Add warning message and abort
  // if order if not found then just tell user (would only happen if deleted while page processing). Add to warning messages and carry on.
  // permission error - pause the submission and alert user.

  var new_order_status_id = $('#order-status-id').val();
  var order_id_data = new Array();
  var orders_success = new Array();
  var orders_failed = new Array();
  var orders_success_count = 0;
  var orders_failed_count = 0;
  var orders_total = 0;
  var orders_processed = -1;

  $('#button-update-orders').bind('click', function(e) {
    e.preventDefault();

    // Confirm the action to process
    var pass = confirm("{{ text_confirm_submit }}");

    if (pass == true) {
      // validate the input data
      if (validate() == false) {
        console.log("Data did not validate checks");
      } else {
        // show the progress status
        overlayShow();

        // populate the order ID list to process
        populateOrderIdList();

        // get the total count of orders to process
        orders_total = $('#orders-total').val();

        $('#status-message-total-count').empty().text(orders_total);

        $('#notify-all').hide();
        $('#button-update-orders').hide();
        $('.button-remove-order').hide();

        processUpdate();
      }
    }
  });

  function processUpdate() {
    console.log("processUpdate() Starting");

    // count number of iterations passed through, start on -1 so initial count is 0
    orders_processed = orders_processed + 1;
    $('#status-message-current-count').empty().text(orders_processed);
    progressBarUpdate(orders_processed, orders_total);

    // check if the array has any order_id left
    if (order_id_data.length > 0) {
      // get the next order id from the array to process
      var order_id = order_id_data.pop();

      $('#status-message-order-id').empty().text(order_id);

      console.log("Next order ID being processed: " + order_id);

      // perform the update to the marketplace method
      updateMarketOrderStatus(order_id);
    } else {
      // the order data has been processed and array exhausted
      populateSummary();
    }
  }

  function updateMarketOrderStatus(order_id) {
    console.log("updateMarketOrderStatus(" + order_id + ")");

    $.ajax({
      url: 'index.php?route=marketplace/openbay/updateorderinfo&user_token={{ user_token }}&order_id=' + order_id + '&status_id=' + new_order_status_id,
      type: 'post',
      dataType: 'json',
      data: $('.marketplace-data-' + order_id).serialize(),
      success: function(json) {
        if (json['error']) {
          console.log("Error (" + order_id + "): " + json['error']);

          $('#row-order-id-' + order_id).addClass('danger');

          orders_failed[order_id] = "{{ error_marketplace_update }}";
          orders_failed_count = orders_failed_count + 1;

          // return to the start of the flow for a new order
          processUpdate();
        }
        if (json['success']) {
          console.log("Success (" + order_id + "): " + json['success']);

          // update was ok to marketplace, update the OC store now
          updateStoreOrderStatus(order_id);
        }
      },
      error: function(xhr, ajaxOptions, thrownError) {
        //alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); // @todo console and handle properly
      }
    });
  }

  function updateStoreOrderStatus(order_id) {
    console.log("updateStoreOrderStatus(" + order_id + ")");

    $.ajax({
      url: '{{ catalog }}index.php?route=api/order/history&api_token={{ api_token }}&store_id=0&order_id=' + order_id,
      type: 'post',
      dataType: 'json',
      data: 'order_status_id=' + encodeURIComponent(new_order_status_id) + '&notify=' + ($('#order-notify-' + order_id).prop('checked') ? 1 : 0) + '&override=1&comment=' + encodeURIComponent($('#order-comments-' + order_id).val()),
      success: function(json) {
        if (json['error']) {
          console.log("Error (" + order_id + "): " + json['error']);

          $('#row-order-id-' + order_id).addClass('danger');

          orders_failed[order_id] = json['error'];
          orders_failed_count = orders_failed_count + 1;
        }

        if (json['success']) {
          console.log("Success (" + order_id + "): " + json['success']);

          $('#row-order-id-' + order_id).addClass('success');

          orders_success[order_id] = json['success'];
          orders_success_count = orders_success_count + 1;
        }

        // return to the start of the flow for a new order
        processUpdate();
      },
      error: function(xhr, ajaxOptions, thrownError) {
        // alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); // @todo console and handle properly
      }
    });
  }

  function populateSummary() {
    // display summary of processed/failed etc
    $('#report-orders-total').text(orders_total);
    $('#report-total-success').text(orders_success_count);
    $('#report-total-error').text(orders_failed_count);
    $('#status-update-summary-container').show();

    overlayHide();
  }

  function populateOrderIdList() {
    $.each($('.order-id'), function (index, element) {
      order_id = $(element).val();

      order_id_data.push(order_id);
    });
  }

  function progressBarUpdate(processed_count, total_count) {
    if (processed_count == 0) {
      $('#loading-bar').css('width', '0%');
    } else {
      var modifier = 100 / total_count;
      var current = parseFloat(modifier * processed_count);

      $('#loading-bar').css('width', current + "%");
    }
  }

  function removeOrderFromUpdate(order_id) {
    console.log("Remove row from table - order ID " + order_id);

    var total_count;

    $("#row-order-id-" + order_id).remove();

    total_count = parseInt($("#orders-total").val());

    total_count = total_count - 1;

    $("#orders-total").val(total_count);

    console.log("Row removed, new order total " + total_count);
  }

  function validate() {
    var element_id;
    var error = false;
    var error_amazon_carrier = false;
    var error_amazonus_carrier = false;

    $.each($('.amazon_carrier'), function(k,v) {
      if($(this).val() == 'other') {
        element_id = $(this).attr("id");

        if($('#' + element_id + '_other').val() == '') {
          error = true;
          error_amazon_carrier = true;
          $('#' + element_id + '_other').css('border-color','#FF0000');
        }
      }
    });

    $.each($('.amazonus_carrier'), function(k,v) {
      if($(this).val() == 'other') {
        element_id = $(this).attr("id");

        if($('#' + element_id + '_other').val() == '') {
          error = true;
          error_amazonus_carrier = true;
          $('#' + element_id + '_other').css('border-color','#FF0000');
        }
      }
    });

    if(error_amazon_carrier == true || error_amazonus_carrier == true) {
      alert('{{ text_error_carrier_other }}');
    }

    if (error == false) {
      return true;
    } else {
      return false;
    }
  }

  function overlayShow() {
    console.log("Show overlay and set totals");

    var total_orders = $('#orders-total').val();

    $('#orders-total-processed').val(0);
    $('#orders-total-fail').text(0);
    $('#orders-total-message').val(0);
    $('#orders-total-success').val(0);
    $('#status-message-total-count').text(total_orders);

    progressBarUpdate(0, total_orders);

    $('#overlay-processing').modal('toggle');
  }

  function overlayHide() {
    console.log("Hide overlay");

    $('.modal').modal('hide');
  }

  $("#notify-all").bind('click', function() {
    var value_checked = $('#notify-all').prop('checked');

    if (value_checked == true) {
      $('.notify-checkbox').prop('checked', true);
    } else {
      $('.notify-checkbox').prop('checked', false);
    }
  });
//--></script>
{{ footer }}
