<?
error_reporting(E_ALL ^ E_DEPRECATED);
error_reporting(E_ALL ^ E_NOTICE);

DEFINE('__NO_AUTHENTICATE_REQUIRED__', '');

require_once "global_env.php";
$logger = Logger::getInstance($_SERVER['PHP_SELF']);

// memcached integrated
require_once "lib/Memcached_pool.php";
$mcache = new Memcached();
$mcache->addServers($GLOBALS['memcached-sets'][DEFAULT_MEMCACHED_SET]);

include_once "lib/sanitize.php";
//ob_start("sanitize_html");

// this will replace by login session
$db_user = $mcache->get(session_id() . MCACHE_SUFFIX);
if (!$db_user) {
  // go to index.php
  header("Location: signin.php");
  exit();
}

// Verify page authority
const pageid = 'menu04.01';
if (!isset($db_user['authority'][pageid])) {
  // go to index.php
  header("Location: signout.php");
  exit();
}

require_once "lib/Item.php";
require_once "lib/DBFactory.php";
require_once "lib/ext/DateTimeUtil.php";

if (isset($_POST['cmd'])) {
  $status = "success";
  $error = "";

  $a = $_POST;
  $affected_rows = 0;

  $logger->debug(print_r($_POST, true));

  switch ($a['cmd']) {
    case 'delete':
      foreach ($a['datas'] as $index => $data) {
        $affected_rows += (new Item())->remove(
          "id = '" . $data['id'] . "'"
          . " AND division = " . $data['division']
        );
      }
      break;

    case 'edit':
      // Update to DB
      $cols = Item::$__COLUMNS;

      // remove unwant data
      $unsets = ['id', 'division', 'create_dt', 'create_user_id', 'update_dt'];
      foreach ($unsets as $u) unset($cols[$u]);

      $cols = Util::parseArrayData($cols, $a['data'], $use_default=true);
      $cols['update_user_id'] = $db_user['user']['id'];
      $cols['period_from'] = convertTz($a['data']['period_from'], $db_user['timezone']['time_zone'], 'UTC');
      $cols['period_to'] = convertTz($a['data']['period_to'], $db_user['timezone']['time_zone'], 'UTC');
      $affected_rows = (new Item())->set($cols
        , "id='" . $a['data']['id'] . "' AND division=" . $a['data']['division']
        ) ? 1 : 0;
      break;

    case 'add':
      foreach ($a['datas'] as $index => $data) {
        // Insert to DB
        $cols = Item::$__COLUMNS;
        // remove unwant data
        $unsets = ['create_dt', 'update_dt', 'update_user_id'];
        foreach ($unsets as $u) unset($cols[$u]);

        $cols = Util::parseArrayData($cols, $data);
        $cols['create_user_id'] = $db_user['user']['id'];
        $cols['period_from'] = convertTz($data['period_from'], $db_user['timezone']['time_zone'], 'UTC');
        $cols['period_to'] = convertTz($data['period_to'], $db_user['timezone']['time_zone'], 'UTC');
        $logger->debug($cols);
        $id = (new Item())->add($cols);
        if ($id) {
          $affected_rows++;
        }
      }
      break;

    default:
      $status = "error";
      $error = "unknown command : " . $a['cmd'];
      break;
  }

  $arry = array(
    'status' => $status,
    'error' => $error,
    'affected_rows' => $affected_rows
  );
  print json_encode($arry);

  return;
}



// Inquiry datas
$items = null;
$WHERE = "1=1";

if (isset($_GET['item'])) {
  // example input 00000001-001,00000001-002,00000001-003,00000001-004
  $WHERE .= " AND id IN (" . Util::encapsulateWithQuote($_GET['item']) . ")";
}

if (isset($_GET['item_name']) && !empty($_GET['item_name'])) {

  $WHERE .= " AND ( name LIKE '%" . $_GET['item_name'] . "%' OR id LIKE '%" . $_GET['item_name'] . "%' )";
}

$items = (new Item())->get(Item::$__COLUMNS, $WHERE);
$items_all = (new DBFactory())->query('SELECT distinct id FROM Item');

$locations = (new DBFactory())->query(
  'SELECT a.id, a.division, b.name FROM
  (
    SELECT id, max(division) AS division FROM Location WHERE 1=1' . WHERE_PERIOD . ' GROUP BY id
  ) a INNER JOIN (
    SELECT id,division,name FROM Location
  ) b
  ON a.id=b.id AND a.division=b.division');

const _MAX_NEW_ENTRY = 1000;
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Pegasus System -- Item Master</title>
  <link rel="stylesheet" href="vendor/jquery/css/jquery.dataTables.min.css">
  <link href="vendor/jquery/css/jquery-ui.css" rel="stylesheet" />
  <link rel="stylesheet" href="vendor/fontawesome-free/css/fontawesome.min.css">
  <link rel="stylesheet" href="vendor/fontawesome-free/css/regular.css">
  <link rel="stylesheet" href="vendor/fontawesome-free/css/v4-shims.css">
  <link rel="stylesheet" href="vendor/fontawesome-free/css/solid.css">
  <link rel="stylesheet" href="vendor/jquery/css/buttons.dataTables.min.css">
  <link href="css/main.css" rel="stylesheet" />

  
  <link href="css/google-material-icons.css" rel="stylesheet">
  <link href="css/menu-popup.css" rel="stylesheet" />
  <link href="css/jquery-ui-timepicker-addon.css" rel="stylesheet" />
  <link href="css/custom-drop-down-list.css" rel="stylesheet" />

  
  <script type="text/javascript" src="vendor/jquery/js/jquery.min.js"></script>
  <script type="text/javascript" src="vendor/jquery/js/jquery-ui.js"></script>

  <script src="vendor/jquery/js/jquery.dataTables.min.js"></script>
  <script src="vendor/jquery/js/dataTables.buttons.min.js"></script>
  <script src="vendor/jquery/js/buttons.flash.min.js"></script>
  <script src="vendor/jquery/js/jszip.min.js"></script>
  <script src="vendor/jquery/js/pdfmake.min.js"></script>
  <script src="vendor/jquery/js/vfs_fonts.js"></script>
  <script src="vendor/jquery/js/buttons.html5.min.js"></script>
  <script src="vendor/jquery/js/buttons.print.min.js"></script>
  <script src="vendor/jquery/js/buttons.html5.styles.min.js"></script>
  <script src="vendor/jquery/js/buttons.html5.styles.templates.min.js"></script>
  <script src="vendor/jquery/js/dataTables.select.min.js" type="text/javascript"></script>

  <script src="js/utils.js"></script>
  <script src="js/menu-popup.js"></script>
  <script src="js/dd-icon.js"></script>
  <script src="js/datetime.js"></script>
  <script src="js/jquery-ui-timepicker-addon.js"></script>

  <script>

    var location_divisions = <?=DBFactory::DbRows2OptionsMap($locations, TYPE_OPTION_BY_VALUE, 'id', 'division')?>;

    /* Define table fields and Primay keys */
    var col_map = [
      'id',
      'name',
      'division',
      'name_id',
      'order_point',
      'safety_stock',
      'unit_price',
      'trgt_ivnt_turnover',
      'location_fix_id',
      'period_from',
      'period_to',
    ];
    var primary_keys = {
      'id':1,
      'division':1,
    };

    function select_all(e) {
      if (!$(e).hasClass('md-inactive')) {
        $(e).addClass('md-inactive').attr('title', 'Deselect all');
        $('#table_preview').DataTable().rows().select();
      } else {
        $(e).removeClass('md-inactive').attr('title', 'Select all');
        $('#table_preview').DataTable().rows().deselect();
      }
    }

    function apply_edit(e) {
      var tr = $(e).closest('tr');

      /* lets update to DB */
      var data = {
        id : tr.find('span[id^=id]').html(),
        name : tr.find('input[id^=name]').val(),
        unit_price : tr.find('input[id^=unit_price]').val(),
        division : tr.find('span[id^=division]').html(),
        name_id : tr.find('input[id^=name_id]').val(),
        order_point : tr.find('input[id^=order_point]').val(),
        safety_stock : tr.find('input[id^=safety_stock]').val(),
        trgt_ivnt_turnover : tr.find('input[id^=trgt_ivnt_turnover]').val(),
        location_fix_id : tr.find('select[id^=ddl_location]').children("option:selected").val(),
        location_fix_div : tr.find('select[id^=ddl_location]').children("option:selected").attr('division'),
        period_from : tr.find('input[id^=period_from]').val(),
        period_to : tr.find('input[id^=period_to]').val(),
      };
      console.log(data);

      var params = {
        cmd : 'edit',
        data : data,
      }

      params = removeUndefined(params);
      $.post("", params)
      .done( function (data) {
        console.log(data);
        var json = JSON.parse(data);

        if (json.status == "success" && json.affected_rows == 1) {
          $('#info-pane', top.document).html('Data has been updated successfully.');
          // update data-editor => data-display
          tr.find('.data-display').each(function() {
            var display_obj = $(this);
            var nf = $(this).hasClass('number-format');
            var map_obj = tr.find('#' + $(this).attr('map'));
            switch (map_obj.prop('tagName')) {
              case 'INPUT':
                display_obj.html(nf ? (map_obj.val().replace(/,/g, "")*1).number_format() : map_obj.val());
                break;
              case 'SELECT':
                display_obj.html(map_obj.children("option:selected").val());
                break;
            }
          });
        } else {
          $('#warn-pane', top.document).html('Error! ' + json.error);
        }

        $(e).closest('tr').find('.data-display').show();
        $(e).closest('tr').find('.data-editor').hide();
      });

    }

    function cancel_edit(e) {
      $(e).closest('tr').find('.data-display').show();
      $(e).closest('tr').find('.data-editor').hide();
    }

    function do_cmd(e, cmd) {
      if (cmd == 'edit') {
        $(e).closest('tr').find('.data-display').hide();
        $(e).closest('tr').find('.data-editor').show();
      } else if (cmd == 'delete') {
        $('#table_preview').DataTable().rows().deselect();
        $('#table_preview').DataTable().rows($(e).closest('tr')).select();
        $('#btn_delete').trigger('click');
      }
    }

    function toggle_menu(e) {
      $('.popupMenu').remove();
      var data = JSON.parse($(e).attr('data'));
      var menu_list = {
          Edit : function(){do_cmd(e, 'edit');},
          Delete : function(){do_cmd(e, 'delete');},
        };
      (new Menu('popupMenu', menu_list)).create(e,{margin:'40px 0 0 0', width:'100px'});
    }

    function verify_with_primary_key(e) {
      var err_dup = 0;
      /* Iterate on new_entry rows */
      $('tbody tr.no-select').each(function(evt) {
        if (!$(this).is($(e).closest('tr'))) {
          var i=0;
          for (const key in primary_keys) {
            if ($(this).find('input[id^=' + key + ']').val() == $(e).closest('tr').find('input[id^=' + key + ']').val()) {
              i++;
            }
          }
          if (i==Object.keys(primary_keys).length) {
            err_dup = 1;
            return;
          }
        }
      });

      /* Validate in DataTable */
      $('#table_preview').DataTable().rows().every(function(rowIdx, tableLoop, rowLoop) {
        var i=0;
        for (const key in primary_keys) {
          if ($(this.node()).find('span[id^=' + key + ']').html() == $(e).closest('tr').find('input[id^=' + key + ']').val()) {
            i++;
          }
        }
        if (i==Object.keys(primary_keys).length) {
          err_dup = 1;
          return;
        }
      });

      if (!err_dup) {
        $(e).closest('tr').removeClass('err-warning');
      } else {
        $(e).closest('tr').removeClass('err-warning').addClass('err-warning');
      }
    }

    /* CSV parameter*/
    var line_delimiter = /\r?\n/;
    var field_delimiter = ",";
    var field_encap = "";
    var remove_header = false;
    var max_insert_line = 100;
    function insert_new_entry(file_content) {
      if (!file_content) {
          return;
      }
      var lines = file_content.split(line_delimiter);

      var exact_line = 0;
      for (l in lines) {
        if (typeof lines[l] !== 'string') break;
        if (lines[l].trim() == "") continue;
        var cols = lines[l].CSVtoArray();
        if (remove_header && l == 0)
            continue;
        if (cols[0] && cols[0].trim() == "")
            continue;

        if (l > max_insert_line)
            continue;

        exact_line++;

        cols = cols.mergeWithPairedKey(col_map);

        var tr = $('<tr class="tr_add_row no-select'
          + (exact_line%2 ? " even" : " odd")
          + '"></tr>');

        $('<td></td>').appendTo(tr);
        for (const key in cols) {
          if (key == 'location_fix_id') {
            var td = $('<td><?=Util::convert2DropDownList('location_fix_id',$locations,'id','id',null,null,$locations[0]['id'],null,'location-division')?></td>');
            td.find('#ddl_dept_id').val(cols[key].trim());
          } else if (key == 'period_from' || key == 'period_to') {
            var td = $('<td><input type="text" class="tbDate xlwidth"'
              + ' id="' + key + l + '" value="' + cols[key].trim() + '" ></td>');
          } else {
            var width = 'xxlwidth';
            if (key == 'division') {
              width = 'swidth';
            } else if (key == 'name_code' || key == 'order_point' || key == 'safety_stock' 
              || key == 'unit_price' || key == 'trgt_ivnt_turnover') {
              width = 'lwidth';
            }
            var td = $('<td '
              + (key in primary_keys ? 'class="pmkey"' : '')
              + '><input type="text" class="' + width + '"'
              + (key in primary_keys ? 'placeholder="*Required field" onkeyup="javascript:verify_with_primary_key(this);"' : '')
              + ' id="' + key + l + '" value="' + cols[key].trim() + '" ></td>');
          }
          td.appendTo(tr);
        }

        var remove_icon = $('<i class="dd-icon fa fa-black fa-remove" for="reset_new_entry" title="delete"></i>')
          .on('click', function() {
            $(this).closest('tr').remove();
          });
        var tailer = $('<td></td>')
          .prepend(remove_icon)
          .appendTo(tr);

        if ($('tbody').find('.tr_add_row').length) {
          tr.insertAfter($('tbody').find('.tr_add_row').last());
        } else {
          $('tbody').prepend(tr);
        }

        verify_with_primary_key(tr);
        setSelectAttr($('.location-division'), location_divisions);

        tr.find('input.tbDate').datetimepicker({
          dateFormat: 'yy-mm-dd'
        });
      }
      $('#btn_register').show();

    }

    function reset_new_entry(e) {
      $(e).closest('tr').find('input').val('');
    }

    function update_default_value() {
      var qs_=qs();
      for(var q in qs_) {
        $('.info').find('.parse_query_str')
          .filter(function(){return $(this).attr('name')==q}).val(qs_[q]);
      }

      $('.custom-drop-down-list').find('select.parse_query_str').each(function() {
        var key = $(this).attr('name');
        $(this).parent().find('.select-items div')
          .filter(function(){return $(this).html()==qs_[key]}).click();
      });

    }

    $(document).ready(function() {

      update_default_value();

      var today = {
        year: new Date().getFullYear(),
        month: (new Date().getMonth()+1).pad(2),
        date: new Date().getDate().pad(2)
      };

      $(window).click(function() { $('.popupMenu').remove(); });
      $('.menu-icon').click(function(event){ event.stopPropagation(); });
      $(".menu-icon").each(function(){
        $(this).click(function(){
          toggle_menu($(this)[0]);
        });
      });


      $.fn.dataTable.ext.search.push(
        function(settings, data, dataIndex) {
          return $(table.row(dataIndex).node()).hasClass('hidden');
        }
      );

      var dtable = $('#table_preview').DataTable( {
        dom: 'B<"clear">lfrtip',
        buttons: [
            {
              extend: 'csv',
              text: 'CSV Output',
              filename:  today.year + '-' + today.month + '-' + today.date + ' - Item Master',
              exportOptions: {
                  columns: [1,2,3,4,5,6,7,8,10,11,12]
              }
            },
        ],
        select: {
            style:    'multi',
            selector: 'tr:not(.no-select) td'
        },
        'pagingType': 'full_numbers',
        'searching': false,
        "order": [[ 1, "asc" ]],
        /* no any columns unsortable */
        'columnDefs': [ 
          {
            'targets': [0,13],
            'orderable': false,
          },
          {
            "targets": [ 10 ],
            "visible": false
          }],
        "pageLength": 100,

      })
      .on('select', function(e, dt, type, indexes) {
        if (type === 'row') {
          var rows = dtable.rows(indexes).nodes().to$();
          $.each(rows, function() {
            if ($(this).hasClass('no-select')) dtable.row($(this)).deselect();
          })
        }
      });

      $('.buttons-csv').hide();
      $('#btn_csvexport').on('click', function(evt){
        $('.buttons-csv').trigger('click');
      });

      $('.data-editor').on('click', function( evt ) {
        evt.stopPropagation();
      });

      $('input.tbDate').datetimepicker({
        dateFormat: 'yy-mm-dd'
      });

      $('#btn_register').on('click', function() {
        var n_err_rows = $('tr.err-warning').length;
        if (n_err_rows > 0) {
          if (!confirm('There are some error input data. Continue adding?')) {
            return false;
          }
        }

        var data_ = new Array();
        $('tr:not(.err-warning)[class^=tr_add_row]').each(function( evt ) {
          /* check proper data */
          var id = $(this).find('input[id^=id]').val();
          var division = $(this).find('input[id^=division]').val();
          if (id != '' && division != '') {
            var data = {
              id : $(this).find('input[id^=id]').val(),
              name : $(this).find('input[id^=name]').val(),
              unit_price : $(this).find('input[id^=unit_price]').val(),
              division : $(this).find('input[id^=division]').val(),
              name_id : $(this).find('input[id^=name_id]').val(),
              order_point : $(this).find('input[id^=order_point]').val(),
              safety_stock : $(this).find('input[id^=safety_stock]').val(),
              trgt_ivnt_turnover : $(this).find('input[id^=trgt_ivnt_turnover]').val(),
              location_fix_id : $(this).find('#ddl_location_fix_id').children("option:selected").val(),
              location_fix_div : $(this).find('#ddl_location_fix_id').children("option:selected").attr('division'),
              period_from : $(this).find('input[id^=period_from]').val(),
              period_to : $(this).find('input[id^=period_to]').val(),
            };
            console.log(data);
            data_.push(data);
          }
        });

        console.log(data_);
        if (data_.length == 0) return false;
        var params = {
          cmd : 'add',
          datas : data_,
        }

        params = removeUndefined(params);
        $.post("", params)
        .done( function (data) {
          console.log(data);
          var json = JSON.parse(data);

          if (json.status == "success") {
            $('#info-pane', top.document).html('Data has been added successfully.');
            $('#_if', top.document).attr('src', $('#_if', top.document).contents().get(0).location.href);
          } else {
            $('#warn-pane', top.document).html('Error! ' + json.error);
          }
        });

      });

      $('#btn_delete').on('click', function() {
        var data_ = new Array();
        $('tbody tr.selected').each(function( evt ) {
          /* check proper data */
          var data = {
            id : $(this).find('span[id^=id]').html(),
            division : $(this).find('span[id^=division]').html(),
          };
          console.log(data);
          data_.push(data);
        });

        console.log(data_);
        if (data_.length == 0) return false;

        if (!confirm('Confirmation to delete ' + data_.length + ' row' + (data_.length>1?'s':'')+ '?')) {
          return false;
        }

        var params = {
          cmd : 'delete',
          datas : data_,
        }

        params = removeUndefined(params);
        $.post("", params)
        .done( function (data) {
          console.log(data);
          var json = JSON.parse(data);

          if (json.status == "success" && json.affected_rows != 0) {
            $('#info-pane', top.document).html('Data has been removed successfully.');
            $("tbody tr.selected").fadeOut(800, function () {
              dtable.row(".selected").remove().draw('page');
            });
          } else {
            $('#warn-pane', top.document).html('Error! ' + json.error);
          }
        });
      });

      $('#btn_clear').on('click', function() {
        $('#frm-primary').trigger('reset');
        $('#ddl_item_from, #ddl_item_to').each(function() {
          $(this).parent().find('.same-as-selected').removeClass('same-as-selected');
          $(this).parent().find('.select-selected')
            .html($(this).children("option:selected").text());
        });
      });

      $('#btn_search').on('click', function(evt) {
        evt.preventDefault();

        item_ = '';
        var keep = false;
        $('#ddl_item_from > option').each(function() {
          if ($(this).val() == $('#ddl_item_from').children("option:selected").val()) {
            keep = true;
          }
          if (keep) {
            item_ += $(this).val() + ",";
          }
          if ($(this).val() == $('#ddl_item_to').children("option:selected").val()) {
            keep = false;
            return;
          }
        });


        var params = {
          cmd : 'search',
          item : item_.slice(0, -1),
        };

        params = removeUndefined(params);
        /*console.log(params); return false;*/
        for (var key in params) {
          $('<input>').attr({ type: 'hidden', name: key, value: params[key] }).appendTo('#frm-primary');
        }

        $('#frm-primary').submit();

      });

      $('#btn_csvimport').on('click', function() {
        var input = $('<input/>')
        .attr('type', "file")
        .attr('name', "uploadFile")
        .css('display', "none")
        .attr('id', "file_csvimport");
        input.insertBefore($(this));
        input.trigger('click');

        input.change(function(e) {
          var ext = $(this).val().split(".").pop().toLowerCase();
          if ($.inArray(ext, ["csv", "txt"]) == -1) {
            alert('Please upload CSV or Text file');
            return false;
          }

          // insert CSV to new entry rows
          if (e.target.files != undefined) {
            var reader = new FileReader();
            reader.onload = function(e) {
              insert_new_entry(e.target.result);
            };

            reader.readAsText(e.target.files.item(0));
          }
        });

      });

      /* Add division attributes to all ddl */
      setSelectAttr($('.location-division'), location_divisions);

    });
  </script>

  <style>
  @import url('https://fonts.googleapis.com/css?family=Josefin+Sans&display=swap');
  *{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    list-style: none;
    text-decoration: none;
    font-family: 'Josefin Sans', sans-serif;
  }

  </style>
</head>
<body>
  <div class="main_content">
    <div class="header" style="text-align: center; background: #0070c0; color: white;"><h2> Item Master </h2><p style="text-align:right; font-size: 10px;">Version 1.0</p></div>
      <div class="info" >
        <form method="GET" id="frm-primary">
          <div class="float-right">
            Search : <input type="text" id="item_name" name="item_name" placeholder="search item" class="parse_query_str xxlwidth" />
          </div>
          <div>
            Item code :
            <div class="custom-drop-down-list">
<?
              print Util::convert2DropDownList('item_from',$items_all,'id','id',null,null,$items_all[0]['id'],null, 'parse_query_str');

?>
            </div>
            ~
            <div class="custom-drop-down-list">
<?
              print Util::convert2DropDownList('item_to',$items_all,'id','id',null,null,$items_all[count($items_all)-1]['id'],null, 'parse_query_str');
?>
            </div>
          </div>
          <div class="float-right">
            <input id="btn_search" type="submit" value="Search">
            <input id="btn_clear" type="button" value="Clear">
          </div>
          <div>
            <input id="btn_csvimport" type="button" value="CSV Import">
            <input id="btn_csvexport" type="button" value="CSV Export">
            <input id="btn_register" type="button" value="Register" style="display:none">
            <input id="btn_delete" type="button" value="Delete">
          </div>
        </form>
     </div>

<!--
  +++++ Table preview section +++++
 -->
      <div class="display" id="display_div">
        <table id="table_preview" class="display dataTable">
          <thead>
            <tr>
              <th><i class="data-editor dd-icon fas fa-black fa-check-double" for="select_all" title="select all"></i></th>
              <th>Item code</th>
              <th>Item name</th>
              <th>Division</th>
              <th>Name code</th>
              <th>Ordering point</th>
              <th>Safety stock</th>
              <th>Unit price</th>
              <th>Target Inventory Turnover</th>
              <th>Fixed Location</th>
              <th>Fixed Location</th>
              <th>Period From</th>
              <th>Period To</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
<?
            $i = 0;
            $display_cols = array(
              'id'=>0,
              'name'=>0,
              'division'=>0,
              'name_id'=>0,
              'order_point'=>0,
              'safety_stock'=>0,
              'unit_price'=>0,
              'trgt_ivnt_turnover'=>0,
              'location_fix_id'=>0,
              '_location_fix_id'=>0, // for export fixed location id
              'period_from'=>0,
              'period_to'=>0,
            );
            foreach ($items as $index => $row) {
              echo '<tr><td>' . ++$i . '</td>';
              foreach ($display_cols as $key => $val) {
                if ($key == 'id' || $key == 'division') {
                  echo '<td><span id="' . $key . '">' . $row[$key] . '</span>'
                    . '</td>';
                } else if ($key == 'unit_price') {
                  echo '<td><span class="data-display number-format" id="' . $key . '" map="' . $key . '_editor' . $i . '">' . number_format($row[$key],2) . '</span>'
                    . '<input type="text" class="lwidth data-editor" id="' . $key . '_editor' . $i . '" value="' . $row[$key] . '">'
                    . '</td>';
                } else if ($key == 'period_from' || $key == 'period_to') {
                  echo '<td><span class="data-display" id="' . $key . '" map="' . $key . '_editor' . $i . '">'
                    . (isset($row[$key]) ? convertTz($row[$key]->format('Y-m-d H:i:s'), 'UTC', $db_user['timezone']['time_zone']) : '')
                    . '</span>'
                    . '<input type="text" class="xlwidth data-editor tbDate" id="' . $key . '_editor' . $i . '" autocomplete="off" value="'
                    . (isset($row[$key]) ? convertTz($row[$key]->format('Y-m-d H:i:s'), 'UTC', $db_user['timezone']['time_zone']) : '') . '">'
                    . '</td>';
                } else if ($key == 'name') {
                  echo '<td><span class="data-display" id="' . $key . '" map="' . $key . '_editor' . $i . '">' . $row[$key] . '</span>'
                    . '<input type="text" class="xxlwidth data-editor" id="' . $key . '_editor' . $i . '" value="' . $row[$key] . '">'
                    . '</td>';

                } else if ($key == 'trgt_ivnt_turnover') {
                  echo '<td><span class="data-display" id="' . $key . '" map="' . $key . '_editor' . $i . '">' . $row[$key] . '</span>'
                    . '<input type="text" class="lwidth data-editor" id="' . $key . '_editor' . $i . '" value="' . $row[$key] . '">'
                    . '</td>';

                } else if ($key == 'location_fix_id') {
                  echo '<td><span class="data-display" id="' . $key . '" map="ddl_' . $key . '_editor' . $i . '">' . $row[$key] . '</span>'
                    . Util::convert2DropDownList('location_fix_id_editor' . $i ,$locations,'id','id',null,null,$row[$key],null,'data-editor location-division')
                    . '</td>';
              

                } else if ($key == '_location_fix_id') {
                  echo '<td><span class="data-display">' . $row['location_fix_id'] . '</span>'
                    . '</td>';
              

                } else {
                  echo '<td><span class="data-display" id="' . $key . '" map="' . $key . '_editor' . $i . '">' . $row[$key] . '</span>'
                    . '<input type="text" class="lwidth data-editor" id="' . $key . '_editor' . $i . '" value="' . $row[$key] . '">'
                    . '</td>';

                }
              }
              echo '<td style="display:inline-flex" class="td-icons">'
                . '<i class="data-editor dd-icon fa fa-green fa-check" for="apply_edit" title="apply" style="display:none"></i>'
                . '<i class="data-editor dd-icon fa fa-red fa-remove" for="cancel_edit" title="cancel" style="display:none"></i>'
                . '<i id="more_vert" class="menu-icon data-display fa fa-black fa-ellipsis-v" title="click for action"'
                . ' data=\'{"id": "' . $row['id'] . '"}\''
                . '></i></td>';
              echo '</tr>';
            }
?>

      </tbody>
      <tfoot>
        <tr>
            <th>#</th>
            <th>Item code</th>
            <th>Item name</th>
            <th>Division</th>
            <th>Name code</th>
            <th>Ordering point</th>
            <th>Safety stock</th>
            <th>Unit price</th>
            <th>Target Inventory Turnover</th>
            <th>Fixed Location</th>
            <th>Fixed Location</th>
            <th>Period From</th>
            <th>Period To</th>
            <th></th>
        </tr>
      </tfoot>
    </table>
    </div>
  </div>
</body>


<script src="js/custom-drop-down-list.js"></script>

</html>
