<?
//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.01';
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/StockCardRecord.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_month = "";
//$sel_year = "";
$cur_d = date("d");
$show_data = false;
$day_in_month = 0;

// Inquiry datas
$list_stockcard = 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 ."' AND month_mm='". $sel_month ."' AND year_20yy='". $sel_year ."' "  ;
     $show_data = true;
     $day_in_month = cal_days_in_month(CAL_GREGORIAN, $sel_month,  $sel_year); 
     $list_non_working_flag = (new DBFactory())->query("SELECT CONVERT(varchar,cdate) as cdate FROM Calendar WHERE non_working_flg=1 AND cdate BETWEEN '$sel_year-$sel_month-01' AND '$sel_year-$sel_month-$day_in_month'");
     $total_work_day = count($list_non_working_flag);
     $list_stockcard = (new DBFactory())->query("SELECT item_id FROM StockCardRecord WHERE customer_id='$sel_customer' and month_mm='$sel_month' and year_20yy='$sel_year' GROUP BY item_id order by item_id ASC ");
     $list_transaction = (new DBFactory())->query("SELECT * FROM StockCardRecord WHERE customer_id='$sel_customer' and month_mm='$sel_month' and year_20yy='$sel_year' order by item_id, create_dt ASC");
     //$list_non_working_flag = (new DBFactory())->query("SELECT cdate FROM Calendar WHERE non_working_flg=1 and cdate BETWEEN '$sel_year-$sel_month-01' AND '$sel_year-$sel_month-$last_date_in_month'");
    //print json_encode($list_non_working_flag);
}

?>

<!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 Record</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>
        $(document).ready(function() {
                $('#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 ){
                        //console.log(  customer_.length, month_.length, year_.length );
                        $('#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('');
              });

              // $("td").hover(function() {
              //   var index = $(this).index();
              //   console.log('1: '+index);
              // }, function() {
              //   var index = $(this).index();
              //   console.log('2: '+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:16px;
    }

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

    th, td {
      padding: 5px;
    }

    td:hover {background-color: coral;}

    .arrow-up {
      width: 0; 
      height: 0; 
      border-top: 25px solid  #b0c1d7;
      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-18{
      font-size: 18px !important;
    }

    .f-size-16{
      font-size: 16px !important;
    }

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

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

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

    .td-outbound {
       background: #efff0066 !important;
       /* color:white; */
    }

    .td-balance-minus {
       background: red !important;
       color:white;
    }

    .td-today {
       background: #a0fffc !important;
    }

    .td-non-working{
       background: #f5d5cf66;
       /* fcf4f4
       f8e4e4 #f8e6e666 #efe0e0 */
    }

    .float-right{
      float: right !important;
    }
    </style>

  </head>
  <body>
    
      <div class="main_content">
          <div class="header" style="text-align: center; background: #0070c0; color: white;"><h2> Stock Card Record </h2><p style="text-align:right; font-size: 10px;">Version 1.0</p></div>
            <div class="info" >
              <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;">
                                  Year : <?=Util::convert2DropDownList('data_year',$years,'val','title',null,null,$sel_year,null,'parse_query_str');?>
                              </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" >
                  <?if( $show_data==true ){
                      $row_month = Util::util_search($months,'val',$sel_month)
                  ?>
                     <hr/>
                      <div style="margin:40px auto 20px;">
                          <h3>Stock Card Record <?=$sel_customer?> For <?=$sel_year?> <?=isset($row_month['title'])?$row_month['title']:'?'?></h3>
                      </div>
                      <?if( count($list_stockcard)>0 && $day_in_month>0){?>
                        <table id="table_preview" class="" style="marign-right:50px;" >
                            <thead>
                              <tr >
                                <th class="border-left-weight border-right-weight border-bottom-weight border-top-weight">No.</th>
                                <th class="border-right-weight border-bottom-weight border-top-weight">Parts No.</th>
                                <th class="border-right-weight border-bottom-weight border-top-weight">Parts name</th>
                                <th class="border-right-weight border-bottom-weight border-top-weight">Pcs/Box</th>
                                <th class="border-right-weight border-bottom-weight border-top-weight" colspan="2" width="380px;" >Balance (End of Month)</th>
                                <th class="border-right-weight border-bottom-weight border-top-weight">Date</th>
                                
                                <? for( $i=1; $i<=$day_in_month; $i++ ){ ?>
                                    <th colspan="2" class="border-right-weight border-bottom-weight border-top-weight th-key-<?=$i?>"><?=$i?>/<?=$sel_month?></th>
                                <? } ?>

                              </tr>
                            </thead>
                              

                            <tbody >
                                <? $count = 0;
                                      foreach( $list_stockcard as $row_card ) { 
                                        $row_item = Util::util_search($Items,'id',$row_card['item_id']);
                                        $row_package = Util::util_search($PackageTypes,'item_id',$row_card['item_id']);
                                        $list_trans = Util::util_search($list_transaction,'item_id',$row_card['item_id'],true);
                                        ?>
                                          <tr>
                                              <td rowspan="4" class="text-center f-size-16 border-bottom-weight border-left-weight border-right-weight" ><?=++$count?></td>
                                              <td rowspan="4" class="f-size-16 border-bottom-weight border-right-weight"><?=$row_item['id']?></td>
                                              <td rowspan="4" class="f-size-16 border-bottom-weight border-right-weight"><?=$row_item['name']?></td>
                                              <td rowspan="4" class="f-size-16 border-bottom-weight border-right-weight text-center"><?=number_format($row_package['qty'])?></td>
                                              <td class="text-center light-slate-gray border-right-weight" width="100x;">BOX</td>
                                              <td class="text-center light-slate-gray border-right-weight" width="200px;">PCS</td>
                                              <td class="border-right-weight light-slate-gray "></td>

                                              <!-- loop day in month  -->
                                              <? for( $i=1; $i<=$day_in_month; $i++ ){ ?>
                                                  <td class="text-center light-slate-gray border-right-weight">BOX</td>
                                                  <td class="text-center border-right-weight light-slate-gray " width="250px;">PCS</td>
                                              <? } ?>
                                          </tr>

                                          <tr>
                                              <td rowspan="3" class="border-bottom-weight border-right-weight text-center"><?=Util::clean_00(isset($list_trans[0]['stockcard_pack'])?number_format($list_trans[0]['stockcard_pack']):'-')?></td>
                                              <td rowspan="3" class="border-bottom-weight border-right-weight text-center"><div style="width:70px;"><?=Util::clean_00(isset($list_trans[0]['stockcard_pcs'])?number_format($list_trans[0]['stockcard_pcs']):'-')?></div></td> 
                                              <td class="border-right-weight">IN</td>
                                              <? for( $i=1; $i<=$day_in_month; $i++ ){ ?>
                                                  <? $clean_d = strlen($i)==1?"0".$i:$i;
                                                     $clean_m = strlen($sel_month)==1?"0".$sel_month:$sel_month;
                                                     $sum_date = $sel_year.'-'.$clean_m.'-'.$clean_d;
                                                     $row_tran = Util::util_search($list_trans, 'sum_date', "$sum_date");

                                                     $td_color_inbound = '';
                                                     if( Util::util_search($list_non_working_flag, 'cdate', "$sum_date") ){ $td_color_inbound=' td-non-working '; }
                                                     if( $cur_d==$clean_d ){ $td_color_inbound=' td-today '; }

                                                     //$non_working = '';
                                                     //if( Util::util_search($list_non_working_flag, 'cdate', "$sum_date") ){ $non_working=' td-non-working '; }
                                                    ?>

                                                  <td title="<?=$row_item['id']?> : date <?=$i?>/<?=$sel_month?>" class="border-bottom-weight border-right-weight f-size-16 <?=$td_color_inbound?> " ><?=Util::clean_00(isset($row_tran['inbound_pack'])&&$row_tran['inbound_pack']!=0?number_format($row_tran['inbound_pack']):'')?></td>  <!-- transaction in box -->
                                                  <td class="nopading border-right-weight border-bottom-weight  <?=$td_color_inbound?> " ><div class="arrow-up "></div></td>
                                              <? } ?>
                                          </tr>
                                          <tr>
                                              <td class="border-right-weight">OUT</td>
                                              <? for( $i=1; $i<=$day_in_month; $i++ ){ ?>
                                                  <? $clean_d = strlen($i)==1?"0".$i:$i;
                                                    $clean_m = strlen($sel_month)==1?"0".$sel_month:$sel_month;
                                                    $sum_date = $sel_year.'-'.$clean_m.'-'.$clean_d;
                                                    $row_tran = Util::util_search($list_trans,'sum_date', "$sum_date");

                                                    $td_color_outbound = '';
                                                    if( Util::util_search($list_non_working_flag, 'cdate', "$sum_date") ){ $td_color_outbound=' td-non-working '; }
                                                    if( $cur_d==$clean_d ){ $td_color_outbound=' td-today '; }
                                                    if( isset($row_tran['outbound_pack'])&&$row_tran['outbound_pack']!=0 ) { $td_color_outbound = ' td-outbound '; }
                                                    ?>
                                                  <td title="<?=$row_item['id']?> : date <?=$i?>/<?=$sel_month?>" colspan="2"  class="border-right-weight border-bottom-weight f-size-16 <?=$td_color_outbound?>"><?=Util::clean_00(isset($row_tran['outbound_pack'])&&$row_tran['outbound_pack']!=0?number_format($row_tran['outbound_pack']):'')?></td> <!-- transaction out box -->
                                              <? } ?>
                                          </tr>
                                          <tr>
                                              <td class="border-right-weight border-bottom-weight">Balance</td>
                                              <? for( $i=1; $i<=$day_in_month; $i++ ){ ?>
                                                  <? $clean_d = strlen($i)==1?"0".$i:$i;
                                                    $clean_m = strlen($sel_month)==1?"0".$sel_month:$sel_month;
                                                    $sum_date = $sel_year.'-'.$clean_m.'-'.$clean_d;
                                                    $row_tran = Util::util_search($list_trans,'sum_date', "$sum_date");

                                                    $td_color_balance = '';
                                                    if( Util::util_search($list_non_working_flag, 'cdate', "$sum_date") ){ $td_color_balance=' td-non-working '; }
                                                    if( $cur_d==$clean_d ){ $td_color_balance=' td-today '; }
                                                    if( isset($row_tran['balance_pcs'])&&$row_tran['balance_pcs']<0 ){ $td_color_balance=' td-balance-minus '; }
                                                    ?>
                                                  <!-- <td title="<?=$row_item['id']?> : date <?=$i?>/<?=$sel_month?>" class="border-bottom-weight f-size-16  <?=$td_color_balance?> "><?=Util::clean_00(isset($row_tran['balance_pack'])?$row_tran['balance_pack']:'')?></td> balance current stock + in - out box -->
                                                  <!-- <td title="<?=$row_item['id']?> : date <?=$i?>/<?=$sel_month?>" class="nopading text-right border-right-weight border-bottom-weight  f-size-16 <?=$td_color_balance?> " ><?=isset($row_tran['balance_pcs'])?number_format($row_tran['balance_pcs']):''?></td> balance current stock + in - out pcs -->

                                                  <td colspan="2" title="<?=$row_item['id']?> : date <?=$i?>/<?=$sel_month?>" class=" border-right-weight border-bottom-weight  f-size-16  <?=$td_color_balance?> "><span><?=Util::clean_00(isset($row_tran['balance_pack'])?number_format($row_tran['balance_pack']):'')?></span><span class="float-right"><?=isset($row_tran['balance_pcs'])?number_format($row_tran['balance_pcs']):''?></span></td>
                                              <? } ?>
                                          </tr>
                                                
                                <?     // unset($row_tran);
                                      } ?>     
                            </tbody>
                        </table>    

                      <?}?>

                  <?}?>          

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

</body>

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

</html>