<%= stylesheet_link_tag    'addorder', media: 'all', 'data-turbolinks-track': 'reload' %>

  <div class="container-fluid " style="padding:0px 3px 0px 3px;">
    <div id="oqs_loading_wrapper" style="display:none;">
      <div id="oqs_loading"></div>
    </div>
    <div class="row m-t--20">
      <div class="col-lg-2 col-md-2 col-sm-2 hidden" id="menu_data"> 
        <li class="list-menu">
          <a href="javascript:void(0);" class="menu-toggle dropdown-toggle toggled my-toggle " style="">

            <span class="main_menu" id="main_menu menu_name" >
              <%if @menu.present? %>
              <%=@menus[0].name%>
              <% end%>
            </span>
          </a>
          <ul class="ml-menu menu_list aria-hidden " style="border-top: 1px solid #fff">
            <% @menus.each do |menu| %>
            <li class="nav-item menu_click" data-name="<%=menu.name%>" data-id="<%=menu.id%>" style="">
             <a class="nav-link" data-toggle="tab" href="" role="tab" style="text-transform: lowercase;"><%=menu.name%></a>
           </li>
           <%end%>
         </ul>
        </li> 
        <div id="menu1-slimscroll" data-height="0">
          <ul class="nav nav-tabs flex-column category_list" role="tablist" id="ul-navbar">
            <li class="nav-item product" data-ref="<%= origami_get_all_product_path %>">
              <a class="nav-link" data-toggle="tab" href="" role="tab">Products</a>
            </li>
            <% @menu.each do |menu| %>
              <% if !menu.valid_time.nil? %>
                <% if menu.menu_category_id.nil? %>
                  <!--if type quick_service or cashier for table -->
                  <% if !menu.code.include? "SPL" %>
                    <li class="nav-item ">
                      <p class="hidden menu-id"><%= menu.id  %></p> 
                      <a class="nav-link menu_category sub_click first_<%=menu.id%>" data-toggle="tab" href="" role="tab" data-id="<%=menu.id%>" data-sub-id="<%=menu.get_sub_category%>"> <%= menu.name%>
                      </a>
                      <ul class=" sub_category_list hidden fadeInTop animated" id="sub_category_list"></ul>
                    </li>
                  <% end%>
                <% end%>
              <% end %>
            <%end %>
          </ul>
        </div>
      </div>
      <div class="col-lg-2 col-md-2 col-sm-2 hidden" id="menu_cache">
        <li class="list-menu">
          <a href="javascript:void(0);" class="menu-toggle dropdown-toggle toggled my-toggle " style="">
            <span class="main_menu menu_cache_name" id="main_menu menu_cache_name"></span>
          </a>
          <ul class="ml-menu menu_list aria-hidden menu_cache_list" style="border-top: 1px solid #fff">
          </ul>
        </li> 
        <div id="menu-slimscroll" data-height="0">
          <ul class="nav nav-tabs flex-column category_list category_cache_list" role="tablist" id="ul-navbar">
            <li class="nav-item product" data-ref="<%= origami_get_all_product_path %>">
             <a class="nav-link" data-toggle="tab" href="" role="tab">Products</a>
            </li>
          </ul>
        </div>
      </div>
      <div class="col-md-7 col-lg-7 col-sm-7 m-t-10" >
        <div class="card">
          <div class="card-block" style="">
            <div class="card-text" id="custom-slimscroll">
              <div class="row menu_items_list" style="margin:0px 1px 0px 1px ;">
             <!-- append data -->
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3" >
        <button type="button" class="btn btn-lg btn-block btn-default waves-effect m-t-5" id='back'>
          <i class="material-icons">reply</i>Back
        </button>

        <div class="card-block">
          <div class="card-text" id="order-detail-slimscroll" data-height="140">
           <table class="table table-striped summary-items" id="order-items-table" >
              <thead>
               <tr>
                 <th>#</th>
                 <th class="item-name">Items</th>
                 <th class="item-qty">Min Qty</th>
                 <th class="item-attr">Max Qty</th>
               </tr>
              </thead>
              <tbody class="font-13" >

              </tbody>
            </table>
          </div>
        </div>
        <div class="card-footer">
          <button type="button" class="btn btn-lg btn-block btn-primary waves-effect m-t-5" id='stock_taking'>Stock Taking
        </button>
        </div>
     </div>
      </div>
    </div>

    <div class="item-modal modal sx_item_detailModal" id="sx_item_detailModal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
      <div class="modal-dialog custom-modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header" style="background-color: #54A5AF;padding-top:10px !important;">
            <h4 class="modal-title" style="color:#fff;" id="title_name"></h4>
            <button type="button" class="close" id="close" data-dismiss="modal" aria-hidden="true" style="font-size: 20px;color:#fff;">&times;</button>
          </div>
          <div class="modal-body">
              <div class="form-inputs">

                <div class="form-group">
                  <div class="form-group">
                    <label class="control-label" for="attribute">Menu Item</label>
                    <input class="form-control col-md-6" type="text" value="" id="item_name" readonly="true">
                  </div>
                  
                    <input type="hidden" name="item_code" id="instance_code">
                  <div class="form-group">
                    <label class="control-label" for="attribute">Instances</label>
                    <div class="attributes-list col-md-6"></div>
                  </div>

                  <div class="form-group">
                    <label class="control-label" for="attribute">Min Order Level</label>
                     <input type="text" name="min_order_level" id="min_qty" value="1" class="col-md-5 form-control">
                  </div>

                  <div class="form-group">
                    <label class="control-label" for="attribute">Max Order Level</label>
                    <input type="text" name="max_order_level" id="max_qty" value="1" class="col-md-5 form-control">
                  </div>
                  
                </div>
              </div>
          </div>
          <div class="modal-footer">
            <div class="row">
              <div class="col-md-4">
                <button type="button" class="btn btn-default " data-dismiss="modal" id="close">Close</button>
              </div>
              <div class="col-md-6">
                <button type="button" class="btn btn-primary submit " data-dismiss="modal" id="submit">Submit</button>
              </div>
            </div>
          </div>
        
      </div>
    </div>
<style type="text/css">
  .fadeInRight{
  -webkit-animation-duration: 350ms !important;
  }
</style>
<script>
  var cashier_type = $('#cashier_type').val();

  jQuery(function(){
    var menus = JSON.parse(localStorage.getItem("menus"));
    if (menus != null) {
      var id = menus[0]["categories"][0]["id"];
          // console.log(id);
    }else{
       var id = 1;
     }
    jQuery('.first_'+id).click();
  });

  $(document).ready(function () {
    var menus = JSON.parse(localStorage.getItem("menus"));;
    if (menus != null) {
      menu_cache_append(menus);
    }else{
      $("#menu_data").removeClass("hidden");
    }      

    function menu_cache_append(menus){
      $("#menu_cache").removeClass("hidden");
      $(".menu_cache_name").text(menus[0]["name"])       
      for(var i in menus) {
        menu_list_template(menus[i]);
      }
      var category = menus[0]["categories"];

      for(var ii in category) {
        if (category[ii]["is_available"]== true){
          if (category[ii]["valid_time"]== true){
            if (category[ii]["parent_id"] == null ){                         
              if (category[ii]["code"].includes("SPL") != true) {
                category_list_template(category[ii]);
              }                               
            }
          }
        }
      }        
    }

    $(document).on('click', '.menu_click', function(event){

      $('.my-toggle').removeClass('toggled');
      $('.menu_list').css('display', 'none');
      var menu_id = $(this).attr("data-id");
      var name = $(this).attr("data-name");
      var menus = JSON.parse(localStorage.getItem("menus"));;

      if (menus != null) {  
      console.log("hi")       
        menu_click_cache_append(name,menus,menu_id);
      }else{
        console.log("sssdfdf")
        var url = "/origami/addorders/get_menu/"+menu_id;
        show_menu_cat_list(name, url); 
      }
    }); 
      //End menu category Click

    function menu_click_cache_append(name,menus,menu_id) {
       var menu_list = $('.menu_items_list');
       menu_list.empty();

       var menu_cat = $('.category_list');
       menu_cat.empty();

       $(".main_menu").text(name);

        for(var i in menus) {  

          if (menu_id == menus[i]["id"] && menus[i]["is_active"] == true) {

              // menu_list_template(menus[i]);
              var category = menus[i]["categories"];
              
              for(var ii in category) {                  
                if (category[ii]["is_available"]== true){                    
                  if (category[ii]["valid_time"]== true){
                    if (category[ii]["parent_id"] == null ){   
                                       
                        if (category[ii]["code"].includes("SPL") != true) {
                          category_list_template(category[ii]);
                        }          
                     
                    }
                  }
                }
              }  
            }
          }
        }

    function category_list_template(menu) {
      row = '<li class="nav-item">'
      +'<p class="hidden menu-id">'+menu.id+'</p> '
      +'<a class="nav-link menu_category sub_click first_'+menu.id+'" '
      +'data-toggle="tab" href="" role="tab" data-id="'+menu.id+'" '
      +'data-sub-id="'+menu.sub_category+'">'+menu.name+''
      +'</a>'
      +'<ul class="sub_category_list hidden fadeInTop animated" '
      +'id="sub_category_list">'
      +'</ul>'

      +' </li>';
      $(".category_cache_list").append(row);           
    }

    function menu_list_template(menu) {
       row = '<li class="nav-item menu_click" data-name="'+menu.name+'" '
       +' data-id="'+menu.id+'" style="">'
       +' <a class="nav-link" data-toggle="tab" href="" role="tab"'
       +' style="text-transform: lowercase;">'+menu.name+'</a>'
       +'</li>';
       $(".menu_cache_list").append(row);           
    } 

    //show menu item list when click menu category
    function show_menu_cat_list(name, url_item){ 
        var menu_list = $('.menu_items_list');
        menu_list.empty();

        var menu_cat = $('.category_list');
        menu_cat.empty();

        $(".main_menu").text(name);
       
        //Start Ajax
      $.ajax({      
        type: "GET",         
        url: url_item, 
        data: {},
        dataType: "json",
        success: function(data) {
          for(var i in data) {  
            if (data[i].is_available == true) {
                list = '<li class="nav-item menu_category sub_click" data-id="'+ data[i].id +'">'
                +'<p class="hidden menu-id">'+ data[i].id +'</p> '
                +'<a class="nav-link" data-toggle="tab" href="" role="tab"> '+ data[i].name +''
                +'<ul class=" sub_category_list hidden fadeInTop animated"' 
                +'id="sub_category_list">'
                +'</ul>'
                +'</a>'
                +'</li>';
                $('.category_list').append(list);
            }
          }
        }
      });
        //end Ajax 
    }
    //end show list function 

    //click menu sidebar menu category
    $(document).on('click', '.menu_category', function(e){
        e.preventDefault();
        $('.sub_category_list').addClass("hidden");
        var menu_id = $(this).attr("data-id");
        var url     = "/inventory/get_menu_category/"+menu_id;
        show_menu_item_list(url,menu_id);
        var sub_id  = $(this).attr("data-sub-id");
        if (sub_id == "true") {
          var sub_url = "/inventory/get_menu_sub_category/"+menu_id;
          sub_category = $(this).siblings('.sub_category_list');
          show_sub_category_list(sub_url,sub_category,menu_id);
        }
    });  
    //End menu category Click

    //click menu sidebar menu category
    $(document).on('click', '.menu_sub_category', function(event){
    //   event.preventDefault();
    // $(".menu_sub_category").on("click", function(){
      $('.sub_category_list').addClass("hidden");
      var menu_id = $(this).attr("data-id");
      var url     = "/inventory/get_menu_category/"+menu_id;
      show_menu_item_list(url,menu_id);
    });  
      //End menu category Click

    //show menu item list when click menu category
    function show_menu_item_list(url_item,menu_id){ 
        var menu_list = $('.menu_items_list');
        menu_list.empty();

        menus = JSON.parse(localStorage.getItem("menus"));
        if (menus != null) {
          for(var i in menus) { 
            var categories = menus[i]["categories"];
            for(var ii in categories) { 
              if (categories[ii]["id"] == menu_id) {
                var menu_items = categories[ii]["items"];
                show_menu_list(menu_items);
              }
            }
          }
        }else{     

          //Start Ajax
          $.ajax({      
            type: "GET",         
            url: url_item, 
            data: {},
            dataType: "json",
            success: function(data) {
              var menu_items_list = $('.menu_items_list');
              menu_items_list.empty();
              menu_items = data.menu_items;
              show_menu_list(menu_items);
            }
          });
          //end Ajax 
        }
      }
    //end show list function
    function show_menu_list(menu_items) {
      var menu_list = $('.menu_items_list');
      menu_list.empty();
      for(var field in menu_items) {  
              if (menu_items[field].is_sub_item == false) {
                instances = menu_items[field].instances ;

                if (!instances.length > 0) {
                  swal("Hello Please Check!","Does not have instance item in this menu items ("+ menu_items[field].name+")","warning");
                }
                if (instances.length > 0) {
                  qty = 1;
                  options = [];
                  price = 0;

                    fa_plus = 'material-icons';
                    add = 'view_list'
                    menu_item_box = 'menu_item_box';
                    data_target = 'sx_item_detailModal';
                    data_modal  = ''
                    add_icon = "add_icon"

                    $(instances).each(function(i){
                      if (instances[i].is_default === true) {
                       code            = instances[i].code;
                       name            = instances[i].name;
                       price           = parseFloat(instances[i].price).toFixed(2);
                       is_available    = instances[i].is_available ;
                       is_on_promotion = instances[i].is_on_promotion;
                       item_attributes = instances[i].values;
                       promotion_price = instances[i].promotion_price;
                       code            = instances[i].code;
                     }
                    });

                  if (menu_items[field].image) {                   
                      image_path = menu_items[field].image;                    
                    
                  }else{
                      image_path = "image/logo.png";
                  }

                  row = '<div class="col-md-3">'
                  +'<div class="card custom-card testimonial-card fadeInRight card-box"' 
                     +'data-toggle="modal" data-target=".'+data_target+'" '
                     +'style="height:100%;background-image:url(../../'+image_path+');background-repeat: no-repeat;">'
                           +'<div class="custom-card-head card-head row" style="line-height:14px;margin:0px;" style="">'
                            +'<div class="col-md-10 " style="padding:0px !important;">'+ menu_items[field].name +'</div>'
                            +"<div class='col-md-2 "+menu_item_box+" ' data-item-code='"
                              + menu_items[field].code +"' data-instance = '"
                              +JSON.stringify(menu_items[field].instances)+"' data-id = '"
                              +JSON.stringify(menu_items[field].attributes)+"' data-item = '"
                              +JSON.stringify(item_attributes)+"' data-option = '"
                              +JSON.stringify(menu_items[field].options)+"'data-opt = '"
                              +JSON.stringify(menu_items[field].options)+"' data-item-sets = '"
                              +JSON.stringify(menu_items[field].item_sets)+"' data-toggle='modal' data-target='."+data_target+"' style='padding:0px 5px 0px 5px'>"
                            +"<i class='m-l--5 fa "+fa_plus+" '>"
                            +add+ '</i>'
                            +'</div>'
                           +'</div>'
                        +"<div  class='"+add_icon+" p-t-65 m-r-' data-item-code='"
                              + menu_items[field].code +"' data-name='"
                              + menu_items[field].name +"' data-qty = '"+ qty +"' data-price = '"
                              + price +"' data-instance-code = '"+ code +"' data-instance = '"
                              + name +"' data-promotion-price = '"+ promotion_price +"' data-attributes = '"
                              + JSON.stringify(item_attributes) +"' data-options = '"
                              + JSON.stringify(menu_items[field].options) +"' data-opt = '"
                              + JSON.stringify(menu_items[field].options) +"' data-image='"+image_path+"' data-toggle='"
                              +data_modal+"' data-target='."+data_target+"' data-item-sets = '"
                          +JSON.stringify(menu_items[field].item_sets)+"'data-instances = '"
                          +JSON.stringify(menu_items[field].instances)+"'>"

                          // +"<div class='card-block custom-card-block'>"
                          //   +"<img id='logo' height='' src='"+image_path+"'>"
                          // +"</div>"

                        +'</div>'
                        +'</div>'; ; 
                  $('.menu_items_list').append(row);
                }
                //end instances in menu-items alest 1 instance
              }
              //end is_sub_item false
          }
       }

       //click item row for add order
      $(document).on('click', '.card-box', function(event){ 

        item_data =  $(this).children().siblings('.add_icon');

        $('#item_code').val(item_data.attr('data-item-code'));
        $('#item_name').val(item_data.attr('data-name'));
        $('#instance_code').val(item_data.attr('data-instance-code'));

        $('.attributes-list').empty();

        data =  $(this).children().children('.menu_item_box');
        // data =  $(this).parent().siblings('.add_icon');

        attributes         = $(data).data('id');
        selected_item      = $(data).data('item');
        instances          = $(data).data('instance');

        instance_attributes = []
        for(var field in instances) { 
          value = instances[field].values;
          $(value).each(function(i){
             options = value[i];
             instance_attributes.push(options);
          });
        }

        for(var field in attributes) { 
          value = attributes[field]["values"];
          type  = attributes[field]["type"]
          row = "";

          $(value).each(function(i){
            disabled = ""
            status ="";
            if(parseInt(jQuery.inArray(value[i], selected_item)) !== -1){
              status = "selected-attribute";
            }
            if(parseInt(jQuery.inArray(value[i], instance_attributes)) == -1){
              disabled = "disabled";
            }
            row +="<button type='button' id='selected-attribute' data-instances='"+JSON.stringify(instances)+"' data-type='"
            +type+"' data-value='"+value[i]+"' class='btn btn- waves-effect attribute_btn "
            + status +" "+ type +" '"+ disabled +" >"
            +value[i]
            +"</button>";   
          });
          $(".attributes-list").append(row); 
        }
      });

      // click select option icon for add 
      $(document).on('click', '.attribute_btn', function(event){ 

        // $('.change_qty').val(1);
        value      = $(this).data('value');
        type       = $(this).data('type');
        instances  = $(this).data('instances');
        
        attributes = $(".attribute_btn");
        $(attributes).each(function(i){
          if ($(attributes[i]).attr('data-type')==type){
            $('.'+type).removeClass("selected-attribute");
          }
        });
        $(this).addClass('selected-attribute');
        
        var selected_attr = get_selected_attributes('selected-attribute');

        for(var field in instances) { 
          item_attr = instances[field].values;
          
          if(JSON.stringify(item_attr) == JSON.stringify(selected_attr)){
            $('#instance_code').val(instances[field].code);
          }     
        }
        
      }); //End selecct attribute buttom

       // Get Selected Class
      function get_selected_attributes(selected_class) {
        var item_row      = $('.'+selected_class);
        var attribute_arr = [];
        $(item_row).each(function(i){
          value = $(item_row[i]).attr('data-value');
          str = value;
          attribute_arr.push(str);
        });
        return attribute_arr;
      }

      $(document).on('click', '.cashier_number', function(event){
        if(event.handled !== true) {
          var original_value;
          original_value = $('#modal-qty').attr('data-value');
          original_qty   = $('#modal-qty').val();
          var input_type = $(this).attr("data-type");

          switch (input_type) {
            case 'num':
            var input_value = $(this).attr("data-value");
            if (original_value == "0"){
              $('#modal-qty').val(input_value);
              $('#modal-qty').attr('data-value',input_value);
                // update_total_amount();
              }else{
                $('#modal-qty').val(original_qty + input_value);
                $('#modal-qty').attr('data-value',original_qty + input_value);
                // update_total_amount();
              }
              break;
              case 'add':
              
              case 'del' :
              
              case 'clr':
              $('#modal-qty').val(1);
              $('#modal-qty').attr('data-value',0);
              // update_total_amount();
              break;

            }
            event.handled = true;
          } else {
            return false;
          }
        });
         
      // click select option icon for add 
      $(document).on('click', '.submit', function(event){ 

        var item_code = $("#instance_code").val();
        var min_qty = $("#min_qty").val();
        var max_qty = $("#max_qty").val();
        var item_name = $("#item_name").val();

        console.log(item_code);
        console.log(min_qty);
        console.log(max_qty);
        var params = {'item_code': item_code, 
                        'min_order_level': min_qty,
                        'max_stock_level': max_qty};
        var ajax_url = '<%=inventory_inventory_definitions_path%>';
         $.ajax({
          type: "POST",
          url: ajax_url,
          data: params,
          dataType: "json",
           success:function(result){ 
             if (result.status) {
              var rowCount = $('.summary-items tbody tr').length+1;
              row ="<tr class=''>"
                  +'<td class="">'+rowCount+'</td>'
                  +'<td class="">' + item_name +'</td>'
                  +'<td class="">' + min_qty + '</td>' 
                  +'<td class="">' + max_qty + '</td>' 
              +'</tr>';
             $(".summary-items tbody").append(row);
              swal("Success",result.message,"success");
             }else{
              swal("Opps",result.message,"warning");
             }
           }
        });
        
      });

      $('#back').on('click', function () {
        window.location.href = '/inventory';
      });
      $('#stock_taking').on('click', function () {
        window.location.href = '/inventory/stock_checks';
      });

    });
  </script>