<?
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 = '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";

// 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 = "";
$sel_year = "";
$sel_auto_mode = 0;
$show_data = false;

// Inquiry datas
$listStock = 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'];
     $sel_auto_mode = $_REQUEST['data_auto_mode']==""?0:$_REQUEST['data_auto_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);
     $auto_mode = $_REQUEST['data_mode'];
}



?>

<!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 = 3; // 1=Fast , 2=Medium , 3=Slow
        var interval = speed * 5;
        var ducmentH = 0;
        var paused = auto_mode==0?true:false;

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


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


            //  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:14px;
    }

    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: 25px;
    }

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

    </style>

  </head>
  <body>
    
      <div class="main_content">
          <div class="header" style="text-align: center; background: #0070c0; color: white;"><h2> Stock Card Board </h2><p style="text-align:right; font-size: 10px;">Version 1.0</p></div>
                    <div class="info " style="fix-layout">
                      <form method="POST" id="frm-primary">
                      <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; 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;">
                                <? $x[]  = array('title'=>'','val'=>1 );?>
                                Auto Mode : <?=Util::convert2CheckBox('data_auto_mode', $x, 'val','title', null, null, $sel_auto_mode, false, null);?>
                            </span>
                        </div>
                      </form>

                      
                    </div>
 

            <div class="display" id="display_div" style="margin-top:20px;">
            <?if( $show_data==true ){?>
                    <hr/>
                      <div style="margin:40px auto 20px;">
                          <h3><?=$sel_customer?> Finish Goods Delivery Condition & Stock Control Vision</h3>
                      </div>
                      <?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">Current</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( $listStock as $row_stock ){ 

                                            $row_item = Util::util_search($Items,'id',$row_stock['item_id']);
                                            $row_forecasts = Util::util_search($Itemforecasts,'item_id',$row_stock['item_id']);
                                            if( isset($row_forecasts['item_id']) ){
                                                $row_stock_forecast = Util::util_search($StockCardForecast,'id',$row_forecasts['item_id']);
                                                $forcast_pre_day = round($row_forecasts['forecast'] / $total_work_day);
                                                $current_stoack = $row_forecasts['current_stock']>0?$row_forecasts['current_stock']:$row_stock['qty'];
                                            }else{
                                                $row_stock_forecast = false;
                                                $forcast_pre_day = 0;
                                                $current_stoack = 0;
                                            }?>


                                            <?//if($current_stoack>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"; 
                                            ?>
                                              
                                                        <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_stock['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_forecasts['forecast'])?$row_forecasts['forecast']:'-'?></td>
                                                            <td class="text-right border-right-weight border-bottom-weight"><?=isset($row_forecasts['maximum'])?$row_forecasts['maximum']:'-'?></td>
                                                            <td class="text-right border-right-weight border-bottom-weight"><?=isset($row_forecasts['minimum'])?$row_forecasts['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"><?=$current_stoack?></td>
                                                              <td class="text-right border-right-weight border-bottom-weight"><?=$forcast_pre_day?></td>
                                                        </tr>
                                              
                                            <?//}?>       

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

                <?}?>                      

            </div>  
          </div>
      </div> 

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

</html>