<?
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 && !defined("__NO_AUTHENTICATE_REQUIRED__")) {
  // go to index.php
  header("Location: signin.php");
  exit();
}

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

require_once "lib/DBFactory.php";
require_once "lib/Inbound.php";
require_once "lib/Supplier.php";
require_once "lib/Item.php";
require_once "lib/PackageType.php";
require_once "lib/Location.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['ib_datas'] as $index => $ib_data) {
        // Insert to DB
        $cols = Inbound::$__COLUMNS;
        // remove unwant data
        $unsets = ['create_dt', 'update_dt', 'create_user_id'];
        foreach ($unsets as $u) unset($cols[$u]);

        $cols = Util::parseArrayData($cols, $ib_data);
        $cols['update_user_id'] = $db_user['user']['id'];
        $affected_rows += (new Inbound())->remove($cols);
      }
      break;

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

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

      if ($a['ib_data']['create_dt'] == '') {
        unset($cols['create_dt']);
      } else if ( isset($db_user['timezone']['time_zone']) ) {
        // convert create_dt to UTC timezone
        $a['ib_data']['create_dt'] = convertTz($a['ib_data']['create_dt'], $db_user['timezone']['time_zone'], 'UTC');
      }

      $cols = Util::parseArrayData($cols, $a['ib_data']);
      $cols['update_user_id'] = $db_user['user']['id'];
      $affected_rows = (new Inbound())->set_($cols
        , "id=" . $a['ib_data']['id']
        , $a['ib_data']['qty'] - $a['ib_data']['oqty']
        , $a['ib_data']['oitem_id'] == $a['ib_data']['item_id']
          && $a['ib_data']['oitem_dvsn_id'] == $a['ib_data']['item_dvsn_id']
          && $a['ib_data']['olocation_id'] == $a['ib_data']['location_id']
          && $a['ib_data']['olocation_dvsn_id'] == $a['ib_data']['location_dvsn_id'] ? null : $a['ib_data']
        ) ? 1 : 0;
      break;

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

        if ($ib_data['create_dt'] == '') {
          unset($cols['create_dt']);
        } else if ( isset($db_user['timezone']['time_zone']) ) {
          // convert create_dt to UTC timezone
          $ib_data['create_dt'] = convertTz($ib_data['create_dt'], $db_user['timezone']['time_zone'], 'UTC');
        }

        $cols = Util::parseArrayData($cols, $ib_data);
        $id = (new Inbound())->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
$inbounds = null;
$suppliers = null;
$items = null;
$WHERE = "1=1";

if (isset($_GET['date_from']) && !empty($_GET['date_from']) && isset($_GET['date_to']) && !empty($_GET['date_to'])) {
  $df = convertTz($_GET['date_from'], $db_user['timezone']['time_zone'], 'UTC');
  $dt = convertTz($_GET['date_to'], $db_user['timezone']['time_zone'], 'UTC');
  $WHERE .= " AND create_dt BETWEEN '" . $df . "' AND '" . $dt . "'";
} else if (isset($_GET['date_from']) && !empty($_GET['date_from'])) {
  $df = convertTz($_GET['date_from'], $db_user['timezone']['time_zone'], 'UTC');
  $WHERE .= " AND create_dt > '" . $df . "'";
} else if (isset($_GET['date_to']) && !empty($_GET['date_to'])) {
  $dt = convertTz($_GET['date_to'], $db_user['timezone']['time_zone'], 'UTC');
  $WHERE .= " AND create_dt < '" . $dt . "'";
}

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

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

$inbounds = (new Inbound())->get(Inbound::$__COLUMNS, $WHERE);
// create paring object from fetch rows
$items = (new DBFactory())->query(
  'SELECT a.id, a.division, b.name FROM
  (
    SELECT id, max(division) AS division FROM Item WHERE 1=1' . WHERE_PERIOD . ' GROUP BY id
  ) a INNER JOIN (
    SELECT id,division,name FROM Item
  ) b
  ON a.id=b.id AND a.division=b.division');
$items_pair = Item::DbRows2ArrayMapWithDivisions((new Item())->getAll(),'id','name','division');
$suppliers = (new DBFactory())->query(
  'SELECT a.id, a.division, b.name FROM
  (
    SELECT id, max(division) AS division FROM Supplier WHERE 1=1' . WHERE_PERIOD . ' GROUP BY id
  ) a INNER JOIN (
    SELECT id,division,name FROM Supplier
  ) b
  ON a.id=b.id AND a.division=b.division');
$suppliers_pair = Supplier::DbRows2ArrayMapWithDivisions((new Supplier())->getAll(),'id','name','division');
$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');
$packageTypes = (new PackageType())->get(PackageType::$__COLUMNS, 'item_id=\'*\'');
$packageTypes_pair = PackageType::DbRows2ArrayMap($packageTypes ,'id','package_id');
$packageTypeQtys_pair = array();
$rows = (new PackageType())->getAll();
foreach ($rows as $key => $row) {
  $packageTypeQtys_pair[$row['item_id']][$row['item_dvsn_id']][$row['package_id']] = $row['qty'];
}

/*
if (isset($_GET['cmd'] && $_GET['cmd'] == 'search')) {

}
*/

const _MAX_NEW_ENTRY = 10;
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Pegasus System -- Inbound Inquiry Register</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 item_divisions = <?=DBFactory::DbRows2OptionsMap($items, TYPE_OPTION_BY_VALUE, 'id', 'division')?>;
    var supplier_divisions = <?=DBFactory::DbRows2OptionsMap($suppliers, TYPE_OPTION_BY_VALUE, 'id', 'division')?>;
    var location_divisions = <?=DBFactory::DbRows2OptionsMap($locations, TYPE_OPTION_BY_VALUE, 'id', 'division')?>;

    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');
      /* check proper data */
      var date = tr.find('input[id^=tbDate]').val();
      var item_code = tr.find('#ddl_item_code').children("option:selected").val();
      var supplier_code = tr.find('#ddl_supplier_code').children("option:selected").val();
      var package_qty = tr.find('input[id^=package_qty]').val();
      if (item_code != 0 && supplier_code != 0 && package_qty != '' && package_qty != '0' ) {
        /* data OK lets update to DB */
        var ib_data = {
          id : tr.find('input[id^=inbound_id]').val(),
          create_dt : tr.find('input[id^=tbDate_ibdate]').val(),
          item_id : tr.find('#ddl_item_code').children("option:selected").val(),
          item_dvsn_id : tr.find('#ddl_item_code').children("option:selected").attr('division'),
          oitem_id : tr.find('span[id^=item_id]').html(),
          oitem_dvsn_id : tr.find('span[id^=item_id]').attr('division'),
          supplier_id : tr.find('#ddl_supplier_code').children("option:selected").val(),
          supplier_dvsn_id : tr.find('#ddl_supplier_code').children("option:selected").attr('division'),
          package_type : tr.find('#ddl_package_type').children("option:selected").val(),
          package_qty : tr.find('input[id^=package_qty]').val(),
          product_date : tr.find('input[id^=tbDate_product]').val(),
          qty : tr.find('span.data-editor[id^=qty]').html(),
          oqty : tr.find('span.data-display[id^=qty]').html(),
          location_id : tr.find('#ddl_location').children("option:selected").val(),
          location_dvsn_id : tr.find('#ddl_location').children("option:selected").attr('division'),
          olocation_id : tr.find('span[id^=location]').html(),
          olocation_dvsn_id : tr.find('span[id^=location]').attr('division'),
          status : tr.find('input[id$=inbound_status]').val(),
          slip_divide : tr.find('input[id$=slip_divide]').val(),
        };
        console.log(ib_data);

        var params = {
          cmd : 'edit',
          ib_data : ib_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);
              tr.find('input[id^=' + $(this).attr('map') + ']').each(function() {
                display_obj.html($(this).val());
              });
              tr.find('select[id^=' + $(this).attr('map') + ']').each(function() {
                display_obj.html($(this).children("option:selected").text());
              });
              if ($(this).attr('map') == 'supplier_name') {
                var selected_supplier_id = tr.find('select[id^=ddl_supplier_code]').children("option:selected").val();
                display_obj.html($("#ddl_supplier_hidden option[value='" + selected_supplier_id + "']").text());
              } else if ($(this).attr('map') == 'item_name') {
                var selected_item_id = tr.find('select[id^=ddl_item_code]').children("option:selected").val();
                display_obj.html($("#ddl_item_hidden option[value='" + selected_item_id + "']").text());
              } else if (/^qty/.test($(this).attr('map'))) {
                display_obj.html($('#' + $(this).attr('map')).html());
              }
            });
          } 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 show_tr_add_rows() {
      $('[class^=tr_add_row]').removeClass('hidden').addClass('hidden').show();
      $('.' + $('#ddl_tr_add_rows option::selected').val()).removeClass('hidden');
      $('tr.hidden').hide();
    }

<?
    echo 'var package_type_items_def = {';
    $i = 0;
    foreach ($packageTypes as $k => $row) {
      echo ($i++==0 ? '' : ',') . $row['package_id'] . ': ' . $row['qty'];
    }
    echo "};\n";
    echo 'var package_type_items = [';
    $rows = (new PackageType())->get(PackageType::$__COLUMNS, 'item_id!=\'*\'');
    $i = 0;
    foreach ($rows as $k => $row) {
      echo ($i++==0 ? '' : ',') . '{ item : "' . $row['item_id'] . '", division: ' . $row['item_dvsn_id'] . ', package : "' . $row['package_id'] . '", qty:' . $row['qty'] . "}\n";
    }
    echo '];';
?>
    function find_package_size(item, division, package) {
      for (var k in package_type_items) {
        if (package_type_items[k].item == item
          && package_type_items[k].division == division
          && package_type_items[k].package == package) {
          return package_type_items[k];
        }
      }

      return null;
    }

    function update_qty(e) {
      var selected_item_id = $(e).closest('tr').find('#ddl_item_code').children("option:selected").text();
      var selected_item_dvsn_id = $(e).closest('tr').find('#ddl_item_code').children("option:selected").attr('division');
      var selected_package_type = $(e).closest('tr').find('#ddl_package_type').children("option:selected").text();
      var unit_qty = package_type_items_def[selected_package_type];

      var res = find_package_size(selected_item_id, selected_item_dvsn_id, selected_package_type);
      if (res) {
        unit_qty = res.qty;
      }
      /*var unit_qty = $('#ddl_package_type_qty').find('option:contains("' + selected_package_type + '")').val();*/
      $(e).closest('tr').find('span.data-editor[id^=qty_]').html(
        $(e).closest('tr').find('input[id^=package_qty_]').val() * unit_qty);
    }

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

      var exact_line = 0;
      var tr_new_entry = $('tbody').find('tr.tr_add_row10');
      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++;
          console.log(cols);

          for (f in cols) {
              var tmp = cols[f];
              if (typeof tmp != 'string') break;
              if (tmp.trim() == '') break;

              // formation
              var pass=true;
              var error;
              tmp = tmp.trim();
              console.log(f, tmp.trim());
              switch (f) {
                  case '0': // datetime
                      var dt = new DateTimeChecker(tmp);

                      error = dt.getError();
                      pass = (dt.getType() === 'a' && error === 'OK');

                      $(tr_new_entry).eq(l).find('input[id^=tbDate_ibdate]').val(tmp);
                      break;
                  case '1':
                      $(tr_new_entry).eq(l).find('select[id^=ddl_item_code]')
                        .parent().find('.select-items div')
                        .filter(function(){return $(this).html()==tmp}).click();
                      break;
                  case '2':
                      $(tr_new_entry).eq(l).find('select[id^=ddl_supplier_code]')
                        .parent().find('.select-items div')
                        .filter(function(){return $(this).html()==tmp}).click();
                      break;
                  case '3':
                      $(tr_new_entry).eq(l).find('select[id^=ddl_package_type]')
                        .children("option:selected").removeAttr('selected');

                      $(tr_new_entry).eq(l).find('select[id^=ddl_package_type] option')
                        .filter(function(){return $(this).text()==tmp})
                        .prop('selected', true);
                        //.attr('selected','selected');
                      break;
                  case '4':
                      $(tr_new_entry).eq(l).find('input[id^=package_qty]').val(tmp).trigger('keyup');
                      break;
                  case '5':
                      $(tr_new_entry).eq(l).find('select[id^=ddl_location]')
                        .parent().find('.select-items div')
                        .filter(function(){return $(this).html()==tmp}).click();
                      break;
                  case '6': // product date
                      var dt = new DateTimeChecker(tmp);

                      error = dt.getError();
                      pass = (dt.getType() === 'a' && error === 'OK');

                      $(tr_new_entry).eq(l).find('input[id^=tbDate_product]').val(tmp);
                      break;
                  default:
                  error = '';
                  pass = false;
              }
          }
      }

      if (exact_line <= 1) {
      } else if (exact_line <= 5) {
        $('#ddl_tr_add_rows').val('tr_add_row5').trigger('change');
      } else {
        $('#ddl_tr_add_rows').val('tr_add_row10').trigger('change');
      }

    }

    function reset_new_entry(e) {
      $(e).closest('tr').find('input[id^=tbDate]').val('');
      $(e).closest('tr').find('select[id^=ddl_item_code]').val('');
      $(e).closest('tr').find('select[id^=ddl_item_code]')
        .parent().find('.select-selected').html(
          $(e).closest('tr').find('select[id^=ddl_item_code]').children("option:disabled").text()
        );
      $(e).closest('tr').find('select[id^=ddl_supplier_code]')
        .parent().find('.select-selected').html(
          $(e).closest('tr').find('select[id^=ddl_supplier_code]').children("option:disabled").text()
        );
      $(e).closest('tr').find('select[id^=ddl_package_type]').val(1);
      $(e).closest('tr').find('input[id^=package_qty]').val(0).trigger('keyup');
      $(e).closest('tr').find('select[id^=ddl_location]')
        .parent().find('div.select-items').find('div').first().click();

    }

    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();

      $(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',*/
        select: {
            style:    'multi',
            selector: 'tr:not(.no-select) td'
        },
        'pagingType': 'full_numbers',
        'searching': false,
        "order": [[ 1, "asc" ]],
        /* no any columns unsortable */
        'columnDefs': [ {
          'targets': [0,12],
          'orderable': false,
        }],
        "pageLength": 25,

      })
      .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();
          })
        }
      });

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

      $('input[id^=tbDate_ibdate],input[id^=tbDate1],input[id^=tbDate2]').datetimepicker({
        dateFormat: 'yy-mm-dd'
      });
      $('input[id^=tbDate_product]').datepicker({
        dateFormat: 'yy-mm-dd'
      });

      $('#btn_register').on('click', function() {
        var ib_data_ = new Array();
        $('tr:not(.hidden)[class^=tr_add_row]').each(function( evt ) {
          /* check proper data */
          var item_code = $(this).find('#ddl_item_code').children("option:selected").val();
          var supplier_code = $(this).find('#ddl_supplier_code').children("option:selected").val();
          var package_qty = $(this).find('input[id^=package_qty]').val();
          if (item_code != 0 && supplier_code != 0 && package_qty != '' && package_qty != '0' ) {
            var ib_data = {
              create_dt : $(this).find('input[id^=tbDate]').val(),
              item_id : $(this).find('#ddl_item_code').children("option:selected").val(),
              item_dvsn_id : $(this).find('#ddl_item_code').children("option:selected").attr('division'),
              supplier_id : $(this).find('#ddl_supplier_code').children("option:selected").val(),
              supplier_dvsn_id : $(this).find('#ddl_supplier_code').children("option:selected").attr('division'),
              package_type : $(this).find('#ddl_package_type').children("option:selected").val(),
              package_qty : $(this).find('input[id^=package_qty]').val(),
              product_date : $(this).find('input[id^=tbDate_product]').val(),
              qty : $(this).find('span[id^=qty_new]').html(),
              location_id : $(this).find('#ddl_location').children("option:selected").val(),
              location_dvsn_id : $(this).find('#ddl_location').children("option:selected").attr('division'),
              status : $(this).find('input[id$=inbound_status]').val(),
              slip_divide : $(this).find('input[id$=slip_divide]').val(),
              create_user_id : "<?=$db_user['user']['id']?>",
            };
            console.log(ib_data);
            ib_data_.push(ib_data);
          }
        });

        console.log(ib_data_);
        if (ib_data_.length == 0) return false;
        var params = {
          cmd : 'add',
          ib_datas : ib_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 ib_data_ = new Array();
        $('tbody tr.selected').each(function( evt ) {
          /* check proper data */
          var ib_data = {
            id : $(this).find('input[id^=inbound_id]').val(),
            item_id : $(this).find('#ddl_item_code').children("option:selected").val(),
            item_dvsn_id : $(this).find('#ddl_item_code').children("option:selected").attr('division'),
            qty : $(this).find('span[id^=qty]').html(),
            location_id : $(this).find('#ddl_location').children("option:selected").val(),
            location_dvsn_id : $(this).find('#ddl_location').children("option:selected").attr('division'),
          };
          console.log(ib_data);
          ib_data_.push(ib_data);
        });

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

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

        var params = {
          cmd : 'delete',
          ib_datas : ib_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_supplier_from, #ddl_supplier_to, #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());
        });
      });

      $('#ddl_tr_add_rows').on('change', function() {
        show_tr_add_rows();
      });
      show_tr_add_rows();

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

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

        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',
          date_from: $('#tbDate1').val(),
          date_to: $('#tbDate2').val(),
          supplier : supplier_.slice(0, -1),
          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();

      });

      $('select[id^=ddl_item_code]').parent().find('.select-selected')
        .on('DOMSubtreeModified', function() {
          update_qty(this);
        });
      $('select[id^=ddl_package_type]')
        .on('change', function() {
          update_qty(this);
        });
      $('input[id^=package_qty]')
        .on('keyup', function() {
          update_qty(this);
        })
        .on('click', function() {
          $(this).select();
        });

      $('#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) {
              console.log(e.target.result);
              insert_new_entry(e.target.result);
            };

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

      });

      /* Add division attributes to all ddl */
      setSelectAttr($('.item_code-division'), item_divisions);
      setSelectAttr($('.supplier_code-division'), supplier_divisions);
      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> Inbound Register / Edit </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">
            Supplier :
            <div class="custom-drop-down-list">
<?
              print Util::convert2DropDownList('supplier_from',$suppliers,'id','id',null,null,$suppliers[0]['id'],null, 'parse_query_str');
?>
            </div>
            ~
            <div class="custom-drop-down-list">
<?
              print Util::convert2DropDownList('supplier_to',$suppliers,'id','id',null,null,$suppliers[count($suppliers)-1]['id'],null, 'parse_query_str');
?>
            </div>
          </div>
          <div>
            Inbound date :
            <input type="text" id="tbDate1" name="date_from" placeholder="select a date" class="parse_query_str xlwidth tbDate" autocomplete="off" />
            ~
            <input type="text" id="tbDate2" name="date_to" placeholder="select a date" class="parse_query_str xlwidth tbDate" autocomplete="off" />
          </div>
          <div class="float-right">
            <input id="btn_search" type="submit" value="Search">
            <input id="btn_clear" type="button" value="Clear">
          </div>
          <div>
            Item code :
            <div class="custom-drop-down-list">
<?
              print Util::convert2DropDownList('item_from',$items,'id','id',null,null,$items[0]['id'],null, 'parse_query_str');

?>
            </div>
            ~
            <div class="custom-drop-down-list">
<?
              print Util::convert2DropDownList('item_to',$items,'id','id',null,null,$items[count($items)-1]['id'],null, 'parse_query_str');
?>
            </div>
          </div>
          <div style="float:right;right: 0;position: absolute;margin-right: 15%;padding-top: 40px;">
            Add records :
            <select id='ddl_tr_add_rows'>
              <option value="tr_add_row1" selected>1</option>
              <option value="tr_add_row5">5</option>
              <option value="tr_add_row10">10</option>
            </select>
          </div>
          <div>
            <input id="btn_register" type="button" value="Register">
            <input id="btn_delete" type="button" value="Delete">
            <input id="btn_csvimport" type="button" value="CSV Import">
          </div>
        </form>
     </div>

<?
    print Util::convert2DropDownList('item_hidden',$items,'id','name',null,null,$items[0]['id'],false,'hidden');
    print Util::convert2DropDownList('supplier_hidden',$suppliers,'id','name',null,null,$suppliers[0]['id'],false,'hidden');
?>

<!--
  +++++ 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>Inbound date</th>
              <th>Item code</th>
              <th>Item name</th>
              <th>Product date</th>
              <th>Supplier code</th>
              <th>Supplier name</th>
              <th>Package</th>
              <th>Package quantity</th>
              <th>Quantity</th>
              <th>Location</th>
              <th>Status</th>
              <th>Slip divide</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
<?
            $inboundStatus = ItemStatus::getArrayConstants('val', 'id');
            $slipDivide = SlipDivide::getArrayConstants('val', 'id');
            for ($i = 0 ; $i < _MAX_NEW_ENTRY ; $i++) {
              echo '<tr class="' .
                ($i<1?' tr_add_row1 ':'') .
                ($i<5?' tr_add_row5 ':'') .
                ($i<_MAX_NEW_ENTRY?' tr_add_row10 ':'') .
                ' no-select">' .
                '<td></td>' .
                '<td><input type="text" class="xlwidth tbDate" id="tbDate_ibdate_new' . $i . '" autocomplete="off"></td>' .
                '<td><div class="custom-drop-down-list">' .
                Util::convert2DropDownList('item_code',$items,'id','id',array('display'=>'no select', 'value'=>''),null,0,null,'item_code-division') .
                '</div></td><td></td>' .
                '<td><input type="text" class="lwidth tbDate" id="tbDate_product_new' . $i . '" autocomplete="off"></td>' .
                '<td><div class="custom-drop-down-list">' .
                Util::convert2DropDownList('supplier_code',$suppliers,'id','id',array('display'=>'no select', 'value'=>''),null,0,null,'supplier_code-division') .
                '</div></td><td></td>' .
                '<td>' .
                Util::convert2DropDownList('package_type',$packageTypes,'id','package_id',null,null,$packageTypes[0]['id']) .
                '</td>' .
                '<td><input type="text" class="swidth" id="package_qty_new' . $i . '" value="0"></td>' .
                '<td><span id="qty_new' . $i . '" class="data-editor">0</span></td>' .
                '<td><div class="custom-drop-down-list">' .
                Util::convert2DropDownList('location',$locations,'id','id',null,null,$locations[0]['id'],null,'location-division') .
                '</div></td>' .
                '<td>Store In' .
                '<input type="hidden" class="lwidth" id="inbound_status" value="' . ItemStatus::Store_In . '"></td>' .
                '<td>PC Input' .
                '<input type="hidden" class="lwidth" id="slip_divide" value="' . SlipDivide::PC_Input . '"></td>' .
                '<td><i class="dd-icon fa fa-black fa-remove" for="reset_new_entry" title="delete"></i></td>' .
                '</tr>';
            }

            $i = 0;
            $display_cols = array(
              'id'=>0,
              'create_dt'=>0,
              'item_id'=>0,
              'product_date'=>0,
              'supplier_id'=>0,
              'package_type'=>0,
              'package_qty'=>0,
              'qty'=>0,
              'location_id'=>0,
              'status'=>0,
              'slip_divide'=>0,
            );
            foreach ($inbounds as $index => $row) {
              echo '<tr>';
              foreach ($display_cols as $key => $val) {
                if ($row[$key] instanceof DateTime) {
                  if ($key == 'create_dt') {
                    $tmp = "ibdate";
                    $format = "Y-m-d H:i:s";
                    $width = "xlwidth";
                    echo '<td><span id="' . $key . '" map="tbDate_' . $tmp . '_edit_' . $row['id'] . '" class="data-display">'
                      . convertTz($row[$key]->format($format), 'UTC', $db_user['timezone']['time_zone']) . "</span>"
                      . '<input type="text" id="tbDate_' . $tmp . '_edit_' . $row['id'] . '" class="data-editor ' . $width . ' tbDate" value="'
                      . convertTz($row[$key]->format($format), 'UTC', $db_user['timezone']['time_zone']) . '" autocomplete="off">'
                      . '</td>';
                  } else {
                    $tmp = "product";
                    $format = "Y-m-d";
                    $width = "lwidth";
                    echo '<td><span id="' . $key . '" map="tbDate_' . $tmp . '_edit_' . $row['id'] . '" class="data-display">'
                      . $row[$key]->format($format) . "</span>"
                      . '<input type="text" id="tbDate_' . $tmp . '_edit_' . $row['id'] . '" class="data-editor ' . $width . ' tbDate" value="'
                      . $row[$key]->format($format) . '" autocomplete="off">'
                      . '</td>';
                  }
                } else if ($key == 'item_id') {
                  echo '<td><span id="' . $key . '" map="ddl_item_code" class="data-display" division="' . $row['item_dvsn_id'] . '">' . $row[$key]  . "</span>"
                    . '<div class="custom-drop-down-list data-editor" style="display:none">'
                    . Util::convert2DropDownList('item_code',$items,'id','id',null,null,$row[$key],null,'item_code-division')
                    . '</div></td>';
                  echo '<td><span class="data-display" map="item_name">' . $items_pair[$row[$key]][$row['item_dvsn_id']] . '</span></td>';
                } else if ($key == 'supplier_id') {
                  echo '<td><span id="' . $key . '" map="ddl_supplier_code" class="data-display" division="' . $row['supplier_dvsn_id'] . '">' . $row[$key] . "</span>"
                    . '<div class="custom-drop-down-list data-editor" style="display:none">'
                    . Util::convert2DropDownList('supplier_code',$suppliers,'id','id',null,null,$row[$key],null,'supplier_code-division')
                    . '</div></td>';
                  echo '<td><span class="data-display" map="supplier_name">' . $suppliers_pair[$row[$key]][$row['supplier_dvsn_id']] . '</span></td>';
                } else if ($key == 'location_id') {
                  // add current location if it doesn't exist.
                  $tmp_locations = $locations; // copy array
                  if (!array_key_exists($row[$key], Location::DbRows2ArrayMap($tmp_locations, 'id', 'id') )) {
                    array_push($tmp_locations, array("id"=>$row[$key], "available"=>0));
                  }

                  echo '<td><span id="' . $key . '" map="ddl_location" class="data-display" division="' . $row['location_dvsn_id'] . '">' . $row[$key] . "</span>"
                    . '<div class="custom-drop-down-list data-editor" style="display:none">'
                    . Util::convert2DropDownList('location',$tmp_locations,'id','id',null,null,$row[$key],null,'location-division')
                    . '</div></td>';
                } else if ($key == 'package_type') {
                  echo '<td><span id="' . $key . '" map="ddl_package_type" class="data-display">' . $packageTypes_pair[$row[$key]]  . "</span>"
                    . Util::convert2DropDownList('package_type',$packageTypes,'id','package_id',null,null,$row[$key],false,'data-editor')
                    . '</td>';
                } else if ($key == 'status') {
                  echo '<td><span id="' . $key . '" map="ddl_inbound_status">' . ItemStatus::getConstant($row[$key])->toString() . "</span>"
                    . '<input type="hidden" class="lwidth data-editor" id="inbound_status" value="' . ItemStatus::Store_In . '">'
                    . '</td>';
                } else if ($key == 'slip_divide') {
                  echo '<td><span id="' . $key . '" map="ddl_slip_divide">' . SlipDivide::getConstant($row[$key])->toString() . "</span>"
                    . '<input type="hidden" class="lwidth data-editor" id="slip_divide" value="' . SlipDivide::PC_Input . '">'
                    . '</td>';
                } else if ($key == 'id') {
                  echo '<td>' . ++$i . '<input type="hidden" id="inbound_id" value="' . $row[$key] . '"></td>';
                } else if ($key == 'qty') {
                  echo '<td>' .
                    '<span id="' . $key . '_' . $row['id'] . '" map="' . $key . '_edit_' . $row['id'] . '" class="data-display">' . $row[$key] . '</span>' .
                    '<span id="' . $key . '_edit_' . $row['id'] . '" class="data-editor">' . $row[$key] . '</span>' .
                    '</td>';
                } else {
                  echo '<td><span id="' . $key . '_' . $row['id'] . '" map="' . $key . '_' . $row['id'] . '" class="data-display">' . $row[$key] . '</span>'
                    . '<input id="' . $key . '_' . $row['id'] . '" type="text" class="data-editor swidth" 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=\'{"inbound_id": ' . $row['id'] . ' ,"status": ' . $row['status'] . '}\''
                . '></i></td>';
              echo '</tr>';
            }
?>

      </tbody>
      <tfoot>
        <tr>
            <th>#</th>
            <th>Inbound date</th>
            <th>Item code</th>
            <th>Item name</th>
            <th>Product date</th>
            <th>Supplier code</th>
            <th>Supplier name</th>
            <th>Package</th>
            <th>Package quantity</th>
            <th>Quantity</th>
            <th>Location</th>
            <th>Status</th>
            <th>Slip divide</th>
            <th></th>
        </tr>
      </tfoot>
    </table>
    </div>
  </div>
</body>


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

</html>
