<?
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.06';
if (!isset($db_user['authority'][pageid])) {
  // go to index.php
  header("Location: signout.php");
  exit();
}

require_once "lib/Supplier.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 Supplier())->remove(
          "id = '" . $data['id'] . "'"
          . " AND division = " . $data['division']
        );
      }
      break;

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

      // remove unwant data
      $unsets = ['id', 'division', 'period_from', 'period_to', '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 Supplier())->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 = Supplier::$__COLUMNS;
        // remove unwant data
        $unsets = ['period_from', 'period_to', '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 Supplier())->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
$suppliers = null;
$WHERE = "1=1";

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

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

  $WHERE .= " AND name LIKE '%" . $_GET['supplier_name'] . "%'";
}

$suppliers = (new Supplier())->get(Supplier::$__COLUMNS, $WHERE);
$suppliers_all = (new DBFactory())->query('SELECT distinct id FROM Supplier');

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 -- Supplier 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>

    /* Define table fields and Primay keys */
    var col_map = [
      'id',
      'name',
      'division',
      '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(),
        division : tr.find('span[id^=division]').html(),
        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');
            tr.find('input[id^=' + $(this).attr('map') + ']').each(function() {
              display_obj.html(nf ? ($(this).val().replace(/,/g, "")*1).number_format() : $(this).val());
            });
          });
        } 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) {
            var td = $('<td '
              + (key in primary_keys ? 'class="pmkey"' : '')
              + '><input type="text" class="xxlwidth"'
              + (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);
      }
      $('#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 + ' - Supplier Master',
              exportOptions: {
                  columns: [1,2,3,4,5]
              }
            },
        ],
        select: {
            style:    'multi',
            selector: 'tr:not(.no-select) td'
        },
        'pagingType': 'full_numbers',
        'searching': false,
        "order": [[ 1, "asc" ]],
        /* no any columns unsortable */
        'columnDefs': [ {
          'targets': [0,6],
          'orderable': 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(),
              division : $(this).find('input[id^=division]').val(),
              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_supplier_from, #ddl_supplier_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();

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


        var params = {
          cmd : 'search',
          supplier : supplier_.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));
          }
        });

      });

    });
  </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> Supplier 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">
            Supplier name : <input type="text" id="supplier_name" name="supplier_name" placeholder="search supplier name" class="parse_query_str" />
          </div>
          <div>
            Supplier code :
            <div class="custom-drop-down-list">
<?
              print Util::convert2DropDownList('supplier_from',$suppliers_all,'id','id',null,null,$suppliers_all[0]['id'],null, 'parse_query_str');

?>
            </div>
            ~
            <div class="custom-drop-down-list">
<?
              print Util::convert2DropDownList('supplier_to',$suppliers_all,'id','id',null,null,$suppliers_all[count($suppliers_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>Supplier code</th>
              <th>Supplier name</th>
              <th>Division</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,
              'period_from'=>0,
              'period_to'=>0,
            );
            foreach ($suppliers 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 == '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 {
                  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>';

                }
              }
              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>Supplier code</th>
            <th>Supplier name</th>
            <th>Division</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>
