<?

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']);

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

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

require_once "lib/Calendar.php";
require_once "lib/DBFactory.php";
require_once "lib/ext/DateTimeUtil.php";
require_once "lib/Util.php";
require_once "lib/Customer.php";
require_once "lib/Itemforecast.php";
require_once "lib/Item.php";

// Inquiry datas
$customers[] = array('title'=>'--', 'val'=>'');
$list_cust = (new Customer())->getAll();
if( count($list_cust)>0 ){
  foreach( $list_cust as $row_cust){
    $customers[] = array('title'=>"(".$row_cust['id'].") ".$row_cust['name'], 'val'=>$row_cust['id']);
  }
}
//$Items = (new Item())->get(Item::$__COLUMNS);
//$Items = (new Item())->getAll();

$cur_year = date('Y');

$months = array(
  array('title'=>'--', 'val'=>''),
  array('title'=>'January', 'val'=>'01'),
  array('title'=>'February', 'val'=>'02'),
  array('title'=>'March', 'val'=>'03'),
  array('title'=>'April', 'val'=>'04'),
  array('title'=>'May', 'val'=>'05'),
  array('title'=>'June', 'val'=>'06'),
  array('title'=>'July', 'val'=>'07'),
  array('title'=>'August', 'val'=>'08'),
  array('title'=>'September', 'val'=>'09'),
  array('title'=>'October', 'val'=>'10'),
  array('title'=>'November', 'val'=>'11'),
  array('title'=>'December', 'val'=>'12'),
); 

$years[] = array('title'=>'--', 'val'=>'');
for( $i=$cur_year; $i>=$cur_year-2; $i-- ){
    $years[] = array('title'=>$i, 'val'=>$i);
  }
  
  $sel_customer = "";
  $sel_month = "";
  $sel_year = "";
  $show_data = false;

if (isset($_POST['cmd'])  && $_POST['cmd']!='search') {
    $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 Itemforecast())->remove(
            "item_id='" . $data['item_id'] . "' AND customer_id='" .$data['customer_id'] ."' AND month_mm='". $data['month_mm'] ."' AND year_20yy='". $data['year_20yy'] ."'"
          );
        }
        break;

        case 'add':
            foreach ($a['datas'] as $index => $data) {
              // Insert to DB
              $cols = Itemforecast::$__COLUMNS;
              // remove unwant data
              $unsets = ['create_dt', 'update_dt', 'update_user_id'];
              foreach ($unsets as $u) unset($cols[$u]);
      
              $row_customer = Util::util_search($list_cust,'id',$data['customer_id']);
              $row_item = Util::util_search($Items,'id',$data['item_id']);
              $cols = Util::parseArrayData($cols, $data);

              $forecast_cal_working_day = $data['forecast'] / $data['total_work_day'];
                
              $cols['item_dvsn_id'] = isset($row_item['division'])?$row_item['division']:"1"; 
              $cols['customer_id'] = $data['customer_id'];
              $cols['customer_dvsn_id'] = isset($row_customer['division'])?$row_customer['division']:"1";
              $cols['maximum'] = round($forecast_cal_working_day * 10);
              $cols['minimum'] = round($forecast_cal_working_day * 3);
              $cols['month_mm'] = $data['month_mm'];
              $cols['year_20yy'] = $data['year_20yy'];
              
              $cols['create_user_id'] = $db_user['user']['id'];
              $logger->debug(json_encode($cols));
              $id = (new Itemforecast())->add($cols);
              if ($id) {
                $affected_rows++;
              }
            }
        break;

        case 'edit':
          // Update to DB
          $cols = Itemforecast::$__COLUMNS;
    
          // remove unwant data
          $unsets = ['create_dt', 'create_user_id', 'update_dt'];
          foreach ($unsets as $u) unset($cols[$u]);
    
          
          $data = $a['data'];
          $row_item = Util::util_search($Items,'id',$data['item_id']);
          $cols = Util::parseArrayData($cols, $data, $use_default=true);

          $forecast_cal_working_day = $data['forecast'] / $data['total_work_day'];

          $cols['item_dvsn_id'] = isset($row_item['division'])?$row_item['division']:"1"; 
          $cols['maximum'] = round($forecast_cal_working_day * 10);
          $cols['minimum'] = round($forecast_cal_working_day * 3);
          $cols['update_user_id'] = $db_user['user']['id'];
          $affected_rows = (new Itemforecast())->set($cols
            , "item_id='" . $data['item_id'] . "' AND customer_id='" .$data['customer_id'] ."' AND month_mm='". $data['month_mm'] ."' AND year_20yy='". $data['year_20yy'] ."'"
            ) ? 1 : 0;
          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
$Itemforecasts = null;
$WHERE = "1=1";
$total_work_day = 0;

if( (isset($_REQUEST['data_cust']) && !empty($_REQUEST['data_cust'])) && (isset($_REQUEST['data_month']) && !empty($_REQUEST['data_month'])) && (isset($_REQUEST['data_year']) && !empty($_REQUEST['data_year'])) ){
     $sel_customer = $_REQUEST['data_cust'];
     $sel_month = $_REQUEST['data_month'];
     $sel_year = $_REQUEST['data_year'];
     $WHERE .= " AND  customer_id='" . $sel_customer. "' ";
     $Items = (new Item())->get(Item::$__COLUMNS,$WHERE);
     $WHERE .= " AND  month_mm='" . $sel_month . "' AND year_20yy='".$sel_year."' " ;
     $show_data = true;
     $last_date_in_month = cal_days_in_month(CAL_GREGORIAN, $sel_month,  $sel_year); 
     $row_total_work_day = (new DBFactory())->query("SELECT count(*) AS work_day FROM Calendar WHERE non_working_flg=0 AND cdate BETWEEN '$sel_year-$sel_month-01' AND '$sel_year-$sel_month-$last_date_in_month'");
     print $row_total_work_day[0]['work_day'];
     $total_work_day = $row_total_work_day[0]['work_day'];
     $Itemforecasts = (new Itemforecast())->get(Itemforecast::$__COLUMNS,$WHERE);

}


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 -- Calendar 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 qs_=qs();
    var qs_ = <?=json_encode($_REQUEST ?? null)?>;
    /* Define table fields and Primay keys */
    var col_map = [
      'item_id',
      // 'name',
      'forecast',
      'maximum',
      'minimum',
    ];
    var primary_keys = {
      // 'item_id':1,
      // 'forecast':1
    };

    var modified_data = false;

    /* CSV parameter*/
    var line_delimiter = /\r?\n/;
    var field_delimiter = ",";
    var field_encap = "";
    var remove_header = true;
    var max_insert_line = 1000;

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

      var total_work_day = $('#total_work_day').val();
      /* lets update to DB */
      var data = {
                    item_id : tr.find('span[id^=item_id]').html(),
                    forecast : tr.find('input[id^=forecast_editor]').val(),
                    customer_id : $('#ddl_data_cust').val(),
                    month_mm :  $('#ddl_data_month').val(),
                    year_20yy : $('#ddl_data_year').val(),
                    total_work_day : total_work_day,
                };

      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) {
          modified_data = true;
          $('#info-pane', top.document).html('Data has been updated successfully.');
              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());
                });
                // tr.find('span[id^=' + $(this).attr('map') + ']').each(function() {
                //   display_obj.html($(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();
        //cancel_edit(e);
      });

    }

    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:'10px 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 && Object.keys(primary_keys).length!=0) {
            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 && Object.keys(primary_keys).length!=0) {
          err_dup = 1;
          return;
        }
      });

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

    function update_default_value() {
      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();
      });

    }


    function insert_new_entry(file_content) {
            if (!file_content) {
                return;
            }
            var lines = file_content.split(line_delimiter);

            var exact_line = 0;
            console.log(lines)
            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 == 'forecast') {
                        var td = $('<td '
                        + (key in primary_keys ? 'class="pmkey"' : '')
                        + '><input type="text" class=" xxlwidth "'
                        + (key in primary_keys ? 'placeholder="*Required field" ' : '')
                        + ' id="' + key + l + '" value="' + cols[key].trim() + '" ></td>');
                    } else if (key == 'item_id') {
                        var td = $('<td><div >'
                                  +'<?=Util::convert2DropDownList('data_item',$Items,'id','id',null,null,'0',null,'data-editor')?>'
                                   +'</div></td>');
                            td.find('#ddl_data_item').val(cols[key].trim());
                    } else if(key == 'maximum' || key == 'minimum') {
                        var td = $('<td></td>');
                    }
                    td.appendTo(tr);
                // call tbDate
                }

                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 js_cal(item_id){
        var forecast =  $('.forecast_'+item_id).val();
        var total_work_day = $('#total_work_day').val();
        var forecast_cal_working_day = parseInt(forecast) / parseInt(total_work_day);
        $('.maximum_'+item_id).html( Math.round(parseInt(forecast_cal_working_day)*10) );
        $('.minimum_'+item_id).html( Math.round(parseInt(forecast_cal_working_day)*3) );
    }

    $(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 + ' - Forecast Item 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,
                                },
                                {
                                    'targets': [5],
                                    'visible': false,
                                }
                                ],
                                "pageLength": 50,

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


            $('#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 customer_id = $('#ddl_data_cust').val();
                var month_mm    = $('#ddl_data_month').val();
                var year_20yy   = $('#ddl_data_year').val();
                var total_work_day = $('#total_work_day').val();

                var data_ = new Array();
                $('tr:not(.err-warning)[class^=tr_add_row]').each(function( evt ) {
                    /* check proper data */
                    var item_id =  $(this).find('#ddl_data_item').children("option:selected").val();
                    var forecast = $(this).find('input[id^=forecast]').val();
                    if (item_id != '' && forecast!='' ) {
                            var data = {
                                item_id : item_id,
                                forecast : forecast,
                                customer_id : customer_id,
                                month_mm : month_mm,
                                year_20yy : year_20yy,
                                total_work_day : total_work_day,
                            };
                            data_.push(data);
                    }
                });


                //console.log(data_);
                //console.log(data_fix);

                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);
                    $('#frm-primary').submit();
                    } else {
                    $('#warn-pane', top.document).html('Error! ' + json.error);
                    }
                });
            });

            $('#btn_delete').on('click', function() {
                var data_ = new Array();
                var customer_id = $('#ddl_data_cust').val();
                var month_mm    = $('#ddl_data_month').val();
                var year_20yy   = $('#ddl_data_year').val();
                $('tbody tr.selected').each(function( evt ) {
                    /* check proper data */
                    var data = {
                    //cdate : $(this).closest('tr').find('span#cdate').html(),
                        item_id : $(this).find('span[id^=item_id]').html(),
                        customer_id : customer_id,
                        month_mm :  month_mm,
                        year_20yy : year_20yy,
                    };
                    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(evt) {
                evt.preventDefault();
                  $('#frm-primary').trigger('reset');
                  $('#ddl_data_cust').val('');
                  $('#ddl_data_month').val('');
                  $('#ddl_data_year').val('');
                  $('#frm-primary').submit();
            });

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

                    customer_ = $('#ddl_data_cust').val();
                    month_ =  $('#ddl_data_month').val();
                    year_ =  $('#ddl_data_year').val();

                    if (customer_.length>0 && month_.length>0 && year_.length>0 ){
                        $('#frm-primary').submit();
                    }else{
                        alert("Select option before Search")
                    }
               });

            });

            $('#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));
                        }
                    });
            });

     });     
 


  </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;
        }
        
        .on {          
            position: absolute;
        }
        
        .off {
            position: absolute;
            z-index:1;
            height: 40px;
            cursor: not-allowed;
        }
  </style>
</head>

<body>
    <div class="main_content">
          <div class="header" style="text-align: center; background: #0070c0; color: white;"><h2> Forecast Item Master </h2><p style="text-align:right; font-size: 10px;">Version 1.0</p></div>
            <div class="info" style="">
              <form method="POST" id="frm-primary">
                <input type="hidden" name="total_work_day" id="total_work_day" value="<?=$total_work_day?>" />
                <div class="float-right">
                            <input id="btn_search" type="submit" value="Search">
                            <input id="btn_clear" type="button" value="Clear">
                </div>  

                <div class style="margin-bottom:0px;" >
                        Customer :  
                        <div class="custom-drop-down-list" style="width:200px;" >
                            <?=Util::convert2DropDownList('data_cust',$customers,'val','title',null,null,$sel_customer,null,'parse_query_str');?>
                        </div>
                </div>
                         
                <div class=""  style="margin-bottom:0px;"> 
                    <span style="display:inline-table; margin-right:25px;" >
                        Month : <?=Util::convert2DropDownList('data_month',$months,'val','title',null,null,$sel_month,null,'parse_query_str');?>
                    </span>

                    <span style="display:inline-table;">
                        Year : <?=Util::convert2DropDownList('data_year',$years,'val','title',null,null,$sel_year,null,'parse_query_str');?>
                    </span>
                </div>
              </form>
            </div>
            <div id="display_result_mm_yy_cust" style="margin-top:20px;">
                    <? if($show_data==true) {?>    
                        <hr/>
                        <div style="margin-top:10px;">
                        <div style="">
                                <div style="float:right;">
                                    <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>  
                                <div style="paddin-top:20px; padding-left:40px;">
                                      <?
                                        $row_customer = Util::util_search($customers,'val',$sel_customer);
                                        $row_month = Util::util_search($months,'val',$sel_month);
                                        $row_year = Util::util_search($years,'val',$sel_year);
                                      ?>
                                      <? if($show_data==true) { ?>
                                            <h3><?=$row_customer['title']?> Forecast Item <?=$row_month['title']?> <?=$row_year['title']?></h3>
                                      <?}?>
                                </div>  
                                
                        </div> 
                            </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><i class="data-editor dd-icon fas fa-black fa-check-double" for="select_all" title="select all"></i></th>
                                        <th>Part No.</th>
                                        <th>Forecast</th>
                                        <th>Maximum</th>
                                        <th>Minimum</th>
                                        <th></th>
                                        <th></th>
                                        </tr>
                                    </thead>

                                    <tbody>  

                                            <?if( count($Itemforecasts)>0 ){  
                                              $i = 0;?>
                                                <? foreach( $Itemforecasts as $row_forecast ){?>
                                                    <tr>
                                                            <td><?=++$i?></td>
                                                            <td>
                                                                <span id="item_id" ><?=$row_forecast['item_id']?></span>
                                                                <!-- <input type="hidden" name="item_id" id="item_id" value="<?=$row_forecast['item_id']?>" /> -->
                                                            </td>
                                                            <td style="text-align:right">
                                                                <span id="forecast" class="data-display " map="forecast_editor" ><?=$row_forecast['forecast']?></span>
                                                                <input type="text"  id="forecast_editor" class="xxlwidth data-editor number-format forecast_<?=$row_forecast['item_id']?>" style="display:none" placeholder="*Required field" onblur="js_cal('<?=$row_forecast['item_id']?>')" value="<?=$row_forecast['forecast']?>" />
                                                            </td>
                                                            <td style="text-align:right">
                                                                <span id="maximum" class="data-display maximum_<?=$row_forecast['item_id']?>" map="maximum_editor"><?=$row_forecast['maximum']?></span>
                                                                <!-- <span id="maximum_editor" class="data-editor maximum_<?=$row_forecast['item_id']?>" style="display:none"><?=$row_forecast['maximum']?></span> -->
                                                            </td>
                                                            <td style="text-align:right">
                                                                <span id="minimum" class="data-display minimum_<?=$row_forecast['item_id']?>" map="minimum_editor"><?=$row_forecast['minimum']?></span>
                                                                <!-- <span id="minimum_editor" class="data-editor minimum_<?=$row_forecast['item_id']?>" style="display:none"><?=$row_forecast['minimum']?></span> -->
                                                            </td>
                                                            <td></td>
                                                            <td style="display:inline-flex; text-algin:center;" 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_forecast['item_id']?>"}' ></i>
                                                            </td>
                                                    </tr>
                                                <?}?>
                                            <?}?>    

                                    </tbody>

                                </table>
                            </div>

                          <script>
         
                          </script>
                    <?}?>
            </div>  
          </div>
    </div> 


    <?// $row = Util::util_search($Items,'id','ZHG507-208A-B2');
       // echo json_encode($row);
       
    ?>
    
    
</body>
        <script src="js/custom-drop-down-list.js"></script>
</html>