<?
// error_reporting(E_ALL ^ E_DEPRECATED);
// error_reporting(E_ALL ^ E_NOTICE);
error_reporting(0);
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 = 'menu08.02';
// 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/PackageType.php";
require_once "lib/Customer.php";
require_once "lib/Util.php";
require_once "lib/Item.php";
require_once "lib/Stock.php";
require_once "lib/Itemforecast.php";
require_once "lib/StockCardForecast.php";

date_default_timezone_set("Asia/Bangkok");

// 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())->getAll();
//$PackageTypes = (new PackageType())->getAll();
$PackageTypes = (new DBFactory())->query("SELECT * FROM PackageType WHERE item_dvsn_id=1");

$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 = date('m');
$sel_year = date('Y');
$sel_auto_mode = 1;
$sel_speed_mode = 15;
$show_data = false;

// Inquiry datas
$listStock = null;
$WHERE = "1=1";
$total_work_day = 0;
$real_cal = false;

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'];
     $sel_auto_mode = $_REQUEST['data_auto_mode']==""?0:$_REQUEST['data_auto_mode'];
     $sel_speed_mode = $_REQUEST['data_speed_mode']==""?15:$_REQUEST['data_speed_mode'];
     $WHERE .= " AND  customer_id='" . $sel_customer . "' " ;
     $show_data = true;
     $day_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-$day_in_month'");
     $total_work_day = $row_total_work_day[0]['work_day'];
     //$listStock = (new Stock())->get(Stock::$__COLUMNS,$WHERE);
     $listStock = (new DBFactory())->query("SELECT item_id, SUM(qty) AS qty FROM Stock WHERE ". $WHERE ." GROUP BY item_id" );
     $WHERE .= " AND  month_mm='" . $sel_month . "' AND  year_20yy='" . $sel_year . "' " ;
     $Itemforecasts = (new Itemforecast())->get(Itemforecast::$__COLUMNS,$WHERE);
     $StockCardForecast = (new StockCardForecast())->get(StockCardForecast::$__COLUMNS,$WHERE);

     $cur_month = date('m');
     $cur_year = date('Y');

     if( $cur_month==$sel_month && $cur_year==$sel_year ){
      $real_cal = true;
     }
    // print json_encode($Itemforecasts);
}



?>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pegasus System -- Stock Card Board</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/jquery-ui-timepicker-addon.js"></script>
    <script>


        var auto_mode = '<?=$sel_auto_mode;?>';
        var scrollerID;
        var next = false;
        var speed = '<?=$sel_speed_mode?>'; // 1=Fast , 2=Medium , 3=Slow
        var interval = speed * 5;
        var ducmentH = 0;
        var paused = auto_mode==0?true:false;
        var timeout;
        function start_auto_scroll(){
            var id = setInterval(function(){
              window.scrollBy(0,2);
                      if( window.innerHeight + window.scrollY >= ducmentH ){
                          //paused = true; //ถ้าใส่ตรงนี้จะหยุดทำงาน เราไม่ใส่เพราะต้องการให้ load ลูกค้ารายใหม่
                          stop_auto_scroll();  
                      }
                      //console.log( window.scrollY ) // 3162.39990234375
            },interval);
            return id;
        }


        function stop_auto_scroll(){
            clearInterval(scrollerID);
            setTimeout( function(){ auto_load_next(); } ,10000); 
            
        }



        function auto_load_next(){

            if( paused==false ){
                  var length = $('#ddl_data_cust option').length; // ลูกค้า 12 + 1 blank = 13 index
                  var cur_index = $("#ddl_data_cust option:selected").index(); 
                  var new_index = cur_index+1
         
                  if( new_index>=length ){
                      new_index = 1;
                  }     

                  //console.log('length = '+length+' : cur_index = '+cur_index+ ' : new_index = '+new_index);

                  $('#ddl_data_cust option').eq(new_index).prop('selected',true);
                  
                  $('#frm-primary').submit();
            }else{
              console.log('paused = true');
            }    
        }
         
    
        function func_auto_mode(me){
            if( me.prop('checked')==true ){
               $('#data_auto_mode').val(1);
               $('#frm-primary').submit();
            }else{
               $('#data_auto_mode').val(" ");
               clearTimeout(timeout);
               paused = true;
               stop_auto_scroll();
            }
        }  
        

        function func_speed_mode(me){
            speed = me.val()
            interval = speed * 5;
            $('#data_speed_mode').val(speed);
            if( $('#ddl_data_auto_mode').prop("checked") ){
              clearInterval(scrollerID);
              scrollerID = start_auto_scroll();
            }
        }

        function js_control_auto_mode(){
              if(paused == false) {
                  scrollerID = start_auto_scroll();
              }
              
              if(paused == true){
                  stop_auto_scroll();
              }
        }


        $(document).ready(function() {
          
           ducmentH = $( document ).height()-10; // safety area

                $('#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_clear').on('click', function(evt) {
                  evt.preventDefault();
                    $('#frm-primary').trigger('reset');
                    $('#ddl_data_cust').val('');
                    $('#ddl_data_month').val('');
                    $('#ddl_data_year').val('');
                    $('#display_div').html('');
              });


              let title_report = $('#id_title_report').html();
              if(title_report.length>0){
                 $('#id_head_title').html(title_report);
                }
            //  console.log($( document ).height()) // 4286
            //console.log(document.body.offsetHeight); //159
            //console.log(window.scrollY); // 0
            //console.log(view_height); // 40116
           // console.log( window.innerHeight); // 1123
             //console.log( window.scrollY ) //สุด ตารางประมาณ 3531

            // $("#ddl_data_cust option:selected").index() 
        });  





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

    .text-center {
      text-align: center;
    }

    .text-right {
      text-align: right;
    }

    table, td, th {  
      border: 1px solid #ddd;
      font-size:22px;
    }

    table {
      border-collapse: collapse;
      width: 100%;
    }

    th, td {
      padding: 5px;
    }


    .arrow-up {
      width: 0; 
      height: 0; 
      border-top: 25px solid  white;
      border-left: 50px solid transparent;
    }

    .nopading{
      padding: 0px;
    }
    
    td {
      height: 55px;
    }

    .border-top-weight {
      border-top: 1.5px solid black;
    }

    .border-right-weight {
      border-right: 1.5px solid black;
    }

    .border-bottom-weight {
      border-bottom: 1.5px solid black;
    }

    .border-left-weight {
      border-left: 1.5px solid black;
    }

    .light-slate-gray{
      background-color:#778899;
    }

    .f-size-14{
      font-size: 14px;
    }

    .f-size-13{
      font-size: 13px;
    }

    .f-size-12{
      font-size: 12px;
    }

    div.sticky {
        position: -webkit-sticky;
        position: sticky;
        top: 0;
      }

    .bgcolor-status {
      background-color: #DDD;
    }

    .td-current-stock {
       background: #efff0066;
       /* color:white; */
    }
    </style>

  </head>
  <body>
    
      <div class="main_content" style="position:absolute; width:100%">
          <div class="header " style="text-align: center; background: #0070c0; color: white; z-index:999; top:0; position:sticky">
            <div>
              <h2> <div id="id_head_title"> Stock Card Board </div><?//=($real_cal)?'current':'history'?><p style="text-align:right; font-size: 10px;"   >Version 1.1</p></h2>
            </div>
            
            <div style="text-align:right; margin-top:10px;">

                      <span style="margin-right:10px;">
                            Speed :  <input type="radio" name="sel_speed"  value="5" <?=($sel_speed_mode)==5?"checked":""?> onclick="func_speed_mode($(this));" style=""/> Fast
                                     <input type="radio" name="sel_speed"  value="10" <?=($sel_speed_mode)==10?"checked":""?> onclick="func_speed_mode($(this));" style="margin-left:10px;"/> Medium
                                     <input type="radio" name="sel_speed"  value="15" <?=($sel_speed_mode)==15?"checked":""?> onclick="func_speed_mode($(this));" style="margin-left:10px;"/> Slow
                      </span>
                      ,
                      <span style="margin-left:10px;">
                            Auto Mode : <input type="checkbox" id="ddl_data_auto_mode"  value="1" <?=($sel_auto_mode)==1?"checked":""?> onclick="func_auto_mode($(this));" />
                      </span>
            </div>
         
          </div>
                    <div class="info " style="fix-layout">
                      <form method="POST" id="frm-primary">

                        <div style="margin-bottom:0px;">
                              <div style="display: inline-block;">
                                  <div style="margin-bottom:0px;" >
                                          Customer :  
                                          <div class="custom-drop-down-list" style="width:350px;" >
                                              <?=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; margin-right:25px;">
                                          Year : <?=Util::convert2DropDownList('data_year',$years,'val','title',null,null,$sel_year,null,'parse_query_str');?>
                                      </span>

                                      <span style="display:inline-table;">
                                          <input type="hidden" id="data_auto_mode" name="data_auto_mode" value="<?=$sel_auto_mode?>" />
                                          <input type="hidden" id="data_speed_mode" name="data_speed_mode" value="<?=$sel_speed_mode?>" />
                                          <!-- <? //$x[]  = array('title'=>'','val'=>1 );?>
                                          Auto Mode : <?//=Util::convert2CheckBox('data_auto_mode', $x, 'val','title', null, null, $sel_auto_mode, false, null);?> -->
                                          <!-- Auto Mode : <input type="checkbox" id="ddl_data_auto_mode" name="data_auto_mode" value="1" <?=($sel_auto_mode)==1?"checked":""?> onclick="func_auto_mode($(this));" /> -->
                                      </span>
                                  </div>
                              </div>

                              <div  style=" display: inline-block; vertical-align: top; margin-left: 20px; ">
                                    <input id="btn_search" type="submit" value="Search">
                                    <input id="btn_clear" type="button" value="Clear"> 
                              </div>
                        </div>
                      </form>                  
                    </div>
 

            <div class="display" id="display_div" >
            
                    <hr/>
                      <div style="margin:40px auto 20px;">
                          <h3 id="id_title_report"><?=$sel_customer?> Finish Goods Delivery Condition & Stock Control Vision</h3>
                      </div>
                      
              <?if( $show_data==true ){?>        
                      <?if(count($listStock)>0 && count($Itemforecasts)>0){?>
                          <table id="table_preview" class="" style="marign-right:50px;">
                              <thead>
                                <tr>
                                  <th rowspan="2" class="text-center border-left-weight border-right-weight border-bottom-weight border-top-weight">No.</th>
                                  <th rowspan="2" class="text-center border-right-weight border-bottom-weight border-top-weight">Parts No.</th>
                                  <th rowspan="2" class="text-center border-right-weight border-bottom-weight border-top-weight">name</th>
                                  <th rowspan="2" class="text-center border-right-weight border-bottom-weight border-top-weight">Forecast</th>
                                  <th rowspan="2" class="text-center border-right-weight border-bottom-weight border-top-weight">Maximum</th>
                                  <th rowspan="2" class="text-center border-right-weight border-bottom-weight border-top-weight">Minimum</th>
                                  <th colspan="15" class="text-center border-right-weight border-bottom-weight border-top-weight">Status of delivery</th>
                                  <th class="text-center border-right-weight  border-top-weight"><?=($real_cal)?'Current':$sel_month."/".$sel_year?> </th>
                                  <th class="text-center border-right-weight  border-top-weight">Day</th>
                                </tr>
                                <tr>
                                    <?for($i=1; $i<=15; $i++){?>
                                        <th class="text-center border-right-weight border-bottom-weight" width="40px;"><?=$i?></th>
                                    <?}?>
                                    <th class="text-center border-right-weight border-bottom-weight">Stock</th>
                                    <th class="text-center border-right-weight border-bottom-weight">Forecast</th>
                                </tr>
                              </thead>
                                

                              <tbody >
                                    <? $count =0;
                                      foreach( $Itemforecasts as $row_forecast ){ 

                                                  $row_item = Util::util_search($Items,'id',$row_forecast['item_id']);
                                                  $status_of_delivery = null;
                                                  if( $real_cal==true || count($StockCardForecast)==0){
                                                          $row_stock = Util::util_search($listStock,'item_id',$row_forecast['item_id']);
                                                          $forcast_pre_day = round($row_forecast['forecast'] / $total_work_day);
                                                          $current_stoack = isset($row_stock['qty'])?$row_stock['qty']:0;
                                                          
                                                          if( $forcast_pre_day>0 ){
                                                                $status_of_delivery = round($current_stoack/$forcast_pre_day);
                                                                if ( $status_of_delivery<1 ){ $status_of_delivery=1; } 
                                                                if ( $status_of_delivery>15 ){ $status_of_delivery=15; } 
                                                                $color = "green";
                                                                if ( $status_of_delivery<6 ) $color="yellow";
                                                                if ( $status_of_delivery<4 ) $color="red"; 
                                                          }else{
                                                                if($current_stoack>0){ $status_of_delivery=15; $color = "green";}
                                                          }
                                                  }else{
                                                          $row_StockCardForecast = Util::util_search($StockCardForecast,'itemforecast_id',$row_forecast['item_id']);
                                                          $forcast_pre_day = isset($row_StockCardForecast['forecast_per_day'])?$row_StockCardForecast['forecast_per_day']:0;
                                                          $current_stoack = isset($row_StockCardForecast['current_stock'])?$row_StockCardForecast['current_stock']:0;
                                                          $status_of_delivery = isset($row_StockCardForecast['status_of_deli_1to15'])?$row_StockCardForecast['status_of_deli_1to15']:'';

                                                          if( $forcast_pre_day>0 ){
                                                                if ( $status_of_delivery<1 ){ $status_of_delivery=1; } 
                                                                if ( $status_of_delivery>15 ){ $status_of_delivery=15; } 
                                                                $color = "green";
                                                                if ( $status_of_delivery<6 ) $color="yellow";
                                                                if ( $status_of_delivery<4 ) $color="red"; 
                                                          }else{
                                                                if($current_stoack>0){ $status_of_delivery=15; $color = "green";} 
                                                          }
                                                         
                                                  }


                                         ?>
                                              
                                                        <tr>
                                                            <td class="text-center border-left-weight border-right-weight border-bottom-weight"><?=++$count?></td>
                                                            <td class="border-right-weight border-bottom-weight"><?=$row_item['id']?></td>
                                                            <td class="border-right-weight border-bottom-weight"><?=$row_item['name']?></td>
                                                            <td class="text-right border-right-weight border-bottom-weight"><?=isset($row_forecast['forecast'])?number_format($row_forecast['forecast']):'-'?></td>
                                                            <td class="text-right border-right-weight border-bottom-weight"><?=isset($row_forecast['maximum'])?number_format($row_forecast['maximum']):'-'?></td>
                                                            <td class="text-right border-right-weight border-bottom-weight"><?=isset($row_forecast['minimum'])?number_format($row_forecast['minimum']):'-'?></td>

                                                              <?for($i=1; $i<=15; $i++){?>
                                                                    <td class="text-center border-right-weight border-bottom-weight bgcolor-status">
                                                                          <?=($status_of_delivery==$i)?"<i class='fas fa-circle' style='color:$color;'></i>":''?>
                                                                    </td>  
                                                              <?}?>  

                                                              <td class="text-right border-right-weight border-bottom-weight td-current-stock"><?=number_format($current_stoack)?></td>
                                                              <td class="text-right border-right-weight border-bottom-weight"><?=number_format($forcast_pre_day)?></td>
                                                        </tr>
                                              
                                            <?//}?>       

                                    <?}?>  
                              </tbody>
                          </table>  
                                <script> 
                                     timeout = setTimeout( function(){ js_control_auto_mode(); } ,5000);                       
                                </script>     
                      <?}else{?>
                              <div class="text-center" style="color:red;"><h3>Data Not Found.</h3></div>
                              <script>
                                     timeout =  setTimeout( function(){ auto_load_next(); } ,5000);
                              </script>
                      <?}?>

              <?}else{?>
                          <script>
                             timeout = setTimeout( function(){  $('#frm-primary').submit(); } ,3000);
                          </script>
              <?}?>                      

              <? //echo json_encode($Items);?>
            </div>  
          </div>
      </div> 

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

</html>