<div class="row">
  <div class="col-xs-12 col-sm-12 col-md-9 col-lg-9">
    <div class="card">
      <div class="body">
        <%= simple_nested_form_for([:settings,@promotion]) do |f| %>
          <%= f.error_notification %>

          <div class="form-inputs p-l-15">
            <div class="div-border">
              <div class="row">
                <div class="col-md-6 form-group">
                  <label>*Promo Code</label>
                  <div class="input-group"> 
                    <span class="input-group-addon">
                      <i class="material-icons">vpn_key</i>
                    </span>            
                    <input type="text" name="promotion[promo_code]" value="<%= @promotion.promo_code%>" class="form-control" id="promotion_promo_code">    
                  </div>
                </div>
              </div>

              <div class="row">
                <div class="col-md-6 form-group">
                  <label>* Start Date</label>
                  <div class="input-group">
                    <span class="input-group-addon">
                      <i class="material-icons">date_range</i>
                    </span>
                    <% if !@promotion.promo_start_date.nil?%>
                    <input type="text" name="promotion[promo_start_date]" value="<%= @promotion.promo_start_date.strftime('%A, %d-%m-%Y') %>" class="datepicker form-control col-md-8" placeholder="Start Date...">
                    <% else %>
                    <input type="text" name="promotion[promo_start_date]" class="datepicker form-control col-md-8" placeholder="Start Date...">
                    <% end %>
                  </div>
                </div>
                <div class="col-md-6 form-group">
                  <label>* End Date</label>
                  <div class="input-group">
                    <span class="input-group-addon">
                      <i class="material-icons">date_range</i>
                    </span>
                    <% if !@promotion.promo_end_date.nil?%>
                    <input type="text" name="promotion[promo_end_date]" value="<%= @promotion.promo_end_date.strftime('%A, %d-%m-%Y') %>" class="datepicker form-control col-md-8" placeholder="Start Date...">
                    <% else %>
                    <input type="text" name="promotion[promo_end_date]" class="datepicker form-control col-md-8" placeholder="End Date...">
                    <% end %>
                  </div>
                </div>
              </div>

              <div class="row">
                <div class="col-md-6 form-group">
                  <label class="control-label">* Start Hour</label>
                  <div class="input-group">
                    <span class="input-group-addon">
                      <i class="material-icons">access_time</i>
                    </span>
                    <% if !@promotion.promo_start_hour.nil?%>
                    <input type="text" name="promotion[promo_start_hour]" value="<%= @promotion.promo_start_hour.utc.strftime('%H:%M') %>" class="timepicker form-control col-md-8" placeholder="Start Time(hh:mm)...">
                    <% else %>
                    <input type="text" name="promotion[promo_start_hour]" class="timepicker form-control col-md-8" placeholder="Start Time(hh:mm)...">
                    <% end %>
                  </div>         
                </div>
                <div class="col-md-6 form-group">
                  <label class="control-label">* End Hour</label>
                  <div class="input-group">
                    <span class="input-group-addon">
                      <i class="material-icons">access_time</i>
                    </span>
                    <% if !@promotion.promo_end_hour.nil?%>
                    <input type="text" name="promotion[promo_end_hour]" value="<%= @promotion.promo_end_hour.utc.strftime('%H:%M') %>" class="timepicker form-control col-md-8" placeholder="End Time(hh:mm)...">
                    <% else %>
                    <input type="text" name="promotion[promo_end_hour]" class="timepicker form-control col-md-8" placeholder="End Time(hh:mm)...">
                    <% end %>
                  </div> 
                <!--  <% if !@promotion.promo_end_hour.nil?%>
                    <%= f.input :promo_end_hour, as: :string, input_html: {:value => @promotion.promo_end_hour.utc.strftime('%H:%M') },:class=>"form-control timepicker" %>
                  <% else %>
                    <%= f.input :promo_end_hour, as: :string, input_html: {},:class=>"form-control timepicker" %>
                    <% end %> -->
                  </div>
                </div>

                <br>
                <div class="row checkboxes ">
                 <div class="col-md-3">
                  <label class="control-label"><abbr title="required">*</abbr>  Promotion Day</label>
                </div>
                <%= f.hidden_field :promo_day, :class => "form-control", :id => "promotion_promo_day" %>
                <div class="col-md-9">
                  <label><input class="selectDay" type="checkbox" name="Sunday" value="0" id="0"> Sun</label> &nbsp;&nbsp;
                  <label><input class="selectDay" type="checkbox" name="Monday" value="1" id="1">Mon</label> &nbsp;&nbsp;
                  <label><input class="selectDay" type="checkbox" name="Tuesday" value="2" id="2"> Tue</label> &nbsp;&nbsp;
                  <label><input class="selectDay" type="checkbox" name="Wednesday" value="3" id="3"> Wed</label> &nbsp;&nbsp;
                  <label><input class="selectDay" type="checkbox" name="Thursday" value="4" id="4"> Thu</label> &nbsp;&nbsp;
                  <label><input class="selectDay" type="checkbox" name="Friday" value="5" id="5"> Fri</label> &nbsp;&nbsp;
                  <label><input class="selectDay" type="checkbox" name="Saturday" value="6" id="6"> Sat</label>
                </div>
              </div>

              <!--  <%= f.input :promo_type, collection: %w{Quantity Net_off Net_price Percentage},:input_html=>{:class => 'col-md-5 form-control select'} ,:label => "Promotion Type", :include_blank => 'Choose Promotion Type', :selected => '' %> -->
              <%= f.input :promo_type,input_html: { :class => 'form-control col-md-5 form-control select' },
              collection: %w{Quantity Net_off Net_price Percentage},:label => "Promotion Type" %>
               <!--  </div>
              </div>
            -->
            <div class="row">
              <% arr =  MenuItem.active.joins("JOIN menu_item_instances as b ON b.menu_item_id=menu_items.id").group("menu_items.id").order("name desc").pluck(:name,:item_code) %>
              <% Product.order("name desc").pluck(:name,:item_code).each do |p| %>
                <% arr.push(p) %>
              <% end %>
              <div class="col-md-3 form-group">
                <label class="control-label"><abbr title="required">*</abbr>  Item</label>
                <select class="form-control item_code_place">
                  <% if !@promotion.original_product.nil? %>
                    <% menuiteminstance = MenuItemInstance.find_by_item_instance_code(@promotion.original_product) %>
                    <% if menuiteminstance.nil?%>
                      <% code = @promotion.original_product %>
                    <% else %>
                      <% code = menuiteminstance.menu_item.item_code %>
                    <% end %>
                  <% end %>
                  <option value="" selected>Choose Something</option>
                  <% arr.each do |a| %>
                    <% if a[1] == code %>
                      <option value="<%= a[1]%>" selected><%= a[0]  %></option>
                    <% else %>
                      <option value="<%= a[1]%>"><%= a[0] %></option>
                    <% end %>
                  <% end %>
                </select>
              </div>

              <% sample = [] %>
              <% if !@promotion.original_product.nil? %>
                <% if !MenuItemInstance.find_by_item_instance_code(@promotion.original_product).nil? %>
                  <% sample = MenuItemInstance.where("item_instance_code=?",@promotion.original_product).pluck(:item_instance_name,:item_instance_code)%>
                <% else %>
                  <% sample = Product.where("item_code=?",@promotion.original_product).pluck(:name,:item_code)%>
                <% end %>
              <% end %>
              <div class="col-md-3 form-group"><%= f.input :original_product,collection: sample  %></div>
              <!-- <div class="col-md-6"><%= f.input :original_product,collection: MenuItemInstance.order("item_instance_name desc").pluck(:item_instance_name,:item_instance_code),input_html: { selected: 2 } %></div> -->
              <div class="col-md-6 form-group"><%= f.input :min_qty ,label: "Qualified Qty", :input_html => {:style => 'height: 37px', min: 1, step: '1', :onkeypress => "return isNumberKey(event);", :onkeyup => "greaterThanOne(this);"} %></div>
            </div>
            <br>
            <div class="card">
              <div class="p-l-25 p-t-10 ">
                <div class="row">
                  <div class="col-md-3 p-t-10">Item Code</div>
                  <div class="col-md-3 p-t-10">Item Instance</div>
                  <div class="col-md-1 p-t-10">Qty</div>
                  <div class="col-md-1 p-t-10">Net off</div>
                  <div class="col-md-1 p-t-10">Net Price</div>
                  <div class="col-md-2 p-t-10">Percentage</div>
                  <div class="col-md-1 p-t-10"></div>
                </div>
                <div class="row"></div >
                  <%= f.fields_for :promotion_products do |pro| %>
                  <div class="row">
                    <%= pro.hidden_field :item_code,:class => "promo_product" %>
                    <% arr =  MenuItem.joins("JOIN menu_item_instances as b ON b.menu_item_id=menu_items.id").group("menu_items.id").order("name desc").pluck(:name,:item_code) %>
                    <% Product.order("name desc").pluck(:name,:item_code).each do |p| %>
                    <% arr.push(p) %>
                    <% end %>
                    <div class="col-md-3 menu_item_choose form-group">
                      <select class="form-control item_code_place1">
                        <option value="">Choose Something</option>
                        <% arr.each do |a| %>
                        <option value="<%= a[1 ]%>"><%= a[0] %></option>
                        <% end %>
                      </select>
                    </div>
                    <!-- <% sample = [] %> -->

                    <div class="col-md-3">
                      <%= pro.input :item_code, :class => 'promoproduct', collection:[],input_html: { selected: 2 }, label: false %>
                    </div>

                    <div class="col-md-1">
                      <%= pro.input :min_qty , label: false, :input_html => {:style => 'height: 37px', :onkeypress => "return isNumberKey(event);", :onkeyup => "greaterThanOne(this);"}%>
                    </div>
                    <div class="col-md-1">
                      <%= pro.input :net_off , label: false, :input_html => {:style => 'height: 37px', min: 1, step: '1', :onkeypress => "return isNumberKey(event);", :onkeyup => "greaterThanOne(this);"} %>
                    </div>
                    <div class="col-md-1"><%= pro.input :net_price , label: false, :input_html => {:style => 'height: 37px', min: 1, step: '1', :onkeypress => "return isNumberKey(event);"} %></div>
                    <div class="col-md-2"><%= pro.input :percentage , label: false, :input_html => {:style => 'height: 37px', min: 1, step: '1', :onkeypress => "return isNumberKey(event);", :onkeyup => "greaterThanOne(this);"} %></div>
                    <div class="col-md-1"><%= pro.link_to_remove "X" ,:class=>"btn-primary btn m-r-45", :style => 'width: 25px'%></div>
                  </div>
                  <% end %>
                  <div class="row">
                    <div class="col-md-12 align-right m-r-10">
                      <%= f.link_to_add "Add Product", :promotion_products, :class => 'btn bg-teal addProduct m-r-20' %> 
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <br>
          <div class="form-actions">
           <%= f.submit "Submit",:class => 'btn btn-primary btn-lg waves-effect' %>
         </div>
         <% end %>
      </div>
    </div>
 </div>
 <div class="col-xs-12 col-sm-12 col-md-3 col-lg-3">
  <div class="card">
    <div class="body">
      <h5><i class="material-icons md-18">view_headline <%= t("views.right_panel.header.page_detail") %></i></h5>
      <p>
        1) <%= t("views.right_panel.detail.promotion_code") %> - <%= t("views.right_panel.detail.write_txt") %> <%= t("views.right_panel.detail.promotion_code_txt") %> <br>
        2) <%= t("views.right_panel.detail.start_date") %> - <%= t("views.right_panel.detail.select_txt") %> <%= t("views.right_panel.detail.start_date_txt") %> <br>
        3) <%= t("views.right_panel.detail.end_date") %> - <%= t("views.right_panel.detail.select_txt") %> <%= t("views.right_panel.detail.end_date_txt") %> <br>
        4) <%= t("views.right_panel.detail.start_time") %> - <%= t("views.right_panel.detail.select_txt") %> <%= t("views.right_panel.detail.start_time_txt") %> <br>
        5) <%= t("views.right_panel.detail.end_time") %> - <%= t("views.right_panel.detail.select_txt") %> <%= t("views.right_panel.detail.end_time_txt") %> <br>
        6) <%= t("views.right_panel.detail.promotion_day") %> - <%= t("views.right_panel.detail.select_txt") %> <%= t("views.right_panel.detail.promotion_day_txt") %> <br>
        7) <%= t("views.right_panel.detail.type") %> - <%= t("views.right_panel.detail.select_txt") %> <%= t("views.right_panel.detail.type_txt") %> <br>
        8) <%= t("views.right_panel.detail.item") %> - <%= t("views.right_panel.detail.select_txt") %> <%= t("views.right_panel.detail.item_txt") %> <br>
        9) <%= t("views.right_panel.detail.original_product") %> - <%= t("views.right_panel.detail.select_txt") %> <%= t("views.right_panel.detail.original_product_txt") %> <br>
        10) <%= t("views.right_panel.detail.min_qty") %> - <%= t("views.right_panel.detail.write_txt") %> <%= t("views.right_panel.detail.min_qty_txt") %> <br>
        -------------------------------------------------------------------
        <h5>ADD PRODUCT</h5>
        1) <%= t("views.right_panel.detail.item_code") %> - <%= t("views.right_panel.detail.select_txt") %> <%= t("views.right_panel.detail.item_code_txt") %> <%= t("views.right_panel.detail.product_txt") %> <br>
        2) <%= t("views.right_panel.detail.min_qty") %> - <%= t("views.right_panel.detail.write_txt") %> <%= t("views.right_panel.detail.min_qty_txt") %> <br>
        3) <%= t("views.right_panel.detail.net_off") %> - <%= t("views.right_panel.detail.write_txt") %> <%= t("views.right_panel.detail.net_off_txt") %> <br>
        4) <%= t("views.right_panel.detail.net_price") %> - <%= t("views.right_panel.detail.write_txt") %> <%= t("views.right_panel.detail.net_price_txt") %> <br>
        5) <%= t("views.right_panel.detail.percentage") %> - <%= t("views.right_panel.detail.write_txt") %> <%= t("views.right_panel.detail.percentage_txt") %> <br>
        6) " X " - <%= t("views.right_panel.detail.remove_txt") %> <%= t("views.right_panel.detail.product_txt") %> <br>
      </p>
      <h5><i class="material-icons md-18">list <%= t("views.right_panel.header.button_lists") %></i> </h5>
      <p>
        1) <%= t("views.right_panel.button.add_product") %> - <%= t("views.right_panel.detail.new_btn_txt") %> <%= t("views.right_panel.detail.product_txt") %> <br>
        2) <%= t("views.right_panel.button.submit") %> - <%= t("views.right_panel.detail.submit_btn_txt") %> <%= t("views.right_panel.detail.promotion_txt") %> <br>
      </p>
      <h5><i class="material-icons md-18">list <%= t("views.right_panel.header.link_lists") %></i> </h5>
      <p>
        1) <%= t("views.right_panel.button.home") %> - <%= t("views.right_panel.detail.home_txt") %> <br>
        2) <%= t("views.right_panel.button.back") %> - <%= t("views.right_panel.detail.back_txt") %> <%= t("views.right_panel.detail.promotion_txt") %> <br>
      </p>
    </div>
  </div>  
</div>
</div>

<script>
  $(document).ready(function(){
    if(($('.item_code_place').val()!=undefined) && ($('.item_code_place').val()!="")){
      getItemInstance($('.item_code_place').val());
    }

    $('#promotion_promo_start_hour').on('change', function(event) {
      $('#promotion_promo_start_hour').val($('#promotion_promo_start_hour').val().split(":")[0]+":00");
    });

    $('#promotion_promo_end_hour').on('change', function(event) {
      $('#promotion_promo_end_hour').val($('#promotion_promo_end_hour').val().split(":")[0]+":00");
    });

    $('.datepicker').bootstrapMaterialDatePicker({
      format: 'dddd DD MM YYYY',
      clearButton: true,
      weekStart: 1,
      time: false
    });

    $('.timepicker').bootstrapMaterialDatePicker({
      format: 'HH:mm',
      clearButton: true,
      date: false
    });

    var dayy = $("#promotion_promo_day").val().replace("[","").replace("]","");
    $.each( dayy.split(","), function( i, d ) {
      $("input.selectDay[value='"+d+"']").prop( "checked", true );
    });

  /*var form = document.getElementById("new_promotion");
  var inputs = $("input");
  var arr = [];
  var count = 0;
  var day = "[";*/


  $(".selectDay").click(function() {
      // debugger;
      var item_row      = $('.selectDay');
      console.log(item_row);
      check = $(item_row).prop("checked");
      var attribute_arr = [];
      $(item_row).each(function(i){
        if ($(item_row[i]).prop("checked")) {
          value = $(item_row[i]).val();
          str = value;
          attribute_arr.push(str);
        }
      });


      /*day = "[";
      for (var j = 8; j <=15; j += 1){
        if (inputs[j].type === "checkbox" && inputs[j].checked)
          {
            if(day == "["){
              day = day + (inputs[j].value);
            }
            else{
              day = day + "," + (inputs[j].value);
            }
          }
          if(j==15)
          {
            day = day + "]";
          }
        }*/

        document.getElementById("promotion_promo_day").value = '';
        document.getElementById("promotion_promo_day").value = "["+attribute_arr+"]";
      });

  // $("#promotion_original_product").select2();
  // $(".item_code_place").select2();

  $(".item_code_place").on('change', function(event) {
    var item_code =  this.value;
    getItemInstance(item_code);
  });

  function getItemInstance(item_code) {
    var ajax_url = "<%= settings_find_item_instance_path %>";
    var original_product = "<%= @promotion.original_product %>";
    $.ajax({
      type: "GET",
      url: ajax_url,
      data: 'item_code=' + item_code,
      success: function (result) {
        $("#promotion_original_product").empty();
        var itemlist;
        for (var i = 0; i < result.length; i++) {
          var selected = "";
          if(original_product == result[i][1]) selected = "selected";
          itemlist += "<option value ="+result[i][1]+" "+selected+">"+result[i][0]+"</option>"
        }
        $("#promotion_original_product").append(itemlist);
            //$("#promotion_original_product").select2();
        }
    });
  }

  //$(".promotion_promotion_products_item_code select").select2();
  //$(".item_code_place1").select2();

  callforpromoproduct();

  $(".addProduct").on('click', function(event) {
    setTimeout(function(){
     // $(".promotion_promotion_products_item_code select").select2();
     callforpromoproduct();
   }, 0);
  });

  // for promotion products data showing
  var promopdt = $(".promo_product");
  $.each( promopdt, function( i, ppdt ) {
    var ajax_url = "<%= settings_find_parent_item_path	%>";
    var item_code =  ppdt.value;
    var select_id =  ppdt.id;
    $.ajax({
      type: "GET",
      url: ajax_url,
      data: 'item_instance_code=' + item_code,
      success: function (result) {
        // console.log(result);
        var par_item_code = "";
        var arr_item_inst = "";
        if((result[0]!=undefined) && (result[0]!="")){
          $.each(result[0],function(k,val){
            par_item_code = k;
            arr_item_inst = val;
          });
        }

        if(result.length > 0){
          var iteminstlists;
          $.each(arr_item_inst,function(k2,v2al){
            $("select#"+select_id).empty();
            var selected = "";
            $.each(v2al,function(k3,v3al){
              if(k3 == item_code) selected = "selected";
              iteminstlists += "<option value='"+k3+"' "+selected+">"+v3al+"</option>";
            });
          });
          $("select#"+select_id).append(iteminstlists);
          
          $("select#"+select_id).parent().parent().siblings("div.menu_item_choose").find("select").find("option[value='"+par_item_code+"']").attr("selected","true")
                 // $("select#"+select_id).parent().parent().siblings("div.menu_item_choose").find("select").select2();
        }
      }
    });
  });

  // promotion_promotion_products_attributes_0_item_code
  function callforpromoproduct(){
    //$(".item_code_place1").select2();
    $(".item_code_place1").on('change', function(event) {
      id = $(this).parent().next().find("select").attr("id");
      var ajax_url = "<%= settings_find_item_instance_path	 %>";
      var item_code =  this.value;
      $.ajax({
        type: "GET",
        url: ajax_url,
        data: 'item_code=' + item_code,
        success: function (result) {
          $("select#"+id).empty();
          var itemlist;
          for (var i = 0; i < result.length; i++) {
            itemlist += "<option value ="+result[i][1]+">"+result[i][0]+"</option>"
          }
          $("select#"+id).append(itemlist);
              //$("select#"+id).select2();
        }
      });
    });
  }

});

$(document).on('turbolinks:load', function() {
  $('body').bootstrapMaterialDesign();
});

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    } else {
        return true;
    }      
}

function greaterThanOne(obj){
  if(parseInt(obj.value)<=0) $(obj).val(1);
}
</script>
