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

require_once "lib/Item.php";
require_once "lib/DBFactory.php";
require_once "lib/ext/DateTimeUtil.php";


// Inquiry datas
$stocks = null;
$items = null;
$WHERE = "1=1";

$logger->debug(print_r($_GET, true));

if (isset($_GET['date_from']) && !empty($_GET['date_from']) && isset($_GET['date_to']) && !empty($_GET['date_to'])) {
  $df = convertTz($_GET['date_from'], $db_user['timezone']['time_zone'], 'UTC');
  $dt = convertTz($_GET['date_to'], $db_user['timezone']['time_zone'], 'UTC');
  $WHERE .= " AND a.create_dt BETWEEN '" . $df . "' AND '" . $dt . "'";
} else if (isset($_GET['date_from']) && !empty($_GET['date_from'])) {
  $df = convertTz($_GET['date_from'], $db_user['timezone']['time_zone'], 'UTC');
  $WHERE .= " AND a.create_dt > '" . $df . "'";
} else if (isset($_GET['date_to']) && !empty($_GET['date_to'])) {
  $dt = convertTz($_GET['date_to'], $db_user['timezone']['time_zone'], 'UTC');
  $WHERE .= " AND a.create_dt < '" . $dt . "'";
}

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

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

if (isset($_GET['item_name']) && !empty($_GET['item_name'])) {
  $search_item = Item::DbRows2ArrayMap(
    (new Item())->get(Item::$__COLUMNS, "name LIKE '%" . $_GET['item_name'] . "%'")
    , 'id'
    , 'name'
  );
  $logger->debug(print_r($search_item, true), implode (",", array_keys($search_item)));
  $WHERE .= " AND item_id IN ("
    . Util::encapsulateWithQuote(implode (",", array_keys($search_item)))
    . ")";
}

if (isset($_GET['section']) && !empty($_GET['section'])) {
  $WHERE .= " AND section = '" . $_GET['section'] . "'";
}


$stockTrackings = (new DBFactory())->query(
  " SELECT a.*, i.name AS item_name, u.name AS user_name FROM
  (
    SELECT create_dt, item_id, item_dvsn_id, product_date, inbound_qty, outbound_qty, increase
      , section, create_user_id, slip_divide
    FROM StockTracking
    WHERE section = 'Stock Maintenance'
    UNION
    SELECT create_dt, item_id, item_dvsn_id, product_date, qty AS inbound_qty, 0 AS outbound_qty, qty AS increase
      , 'Inbound' AS section, create_user_id, slip_divide
    FROM Inbound
    UNION
    SELECT create_dt, item_id, item_dvsn_id, product_date, 0 AS inbound_qty, qty AS outbound_qty, qty*-1 AS increase
      , 'Outbound' AS section, create_user_id, slip_divide
    FROM Outbound
  ) AS a
  INNER JOIN Item i
  ON i.id = a.item_id
  AND i.division = a.item_dvsn_id
  INNER JOIN
  (
    SELECT a.id, a.division, b.name FROM
    (
      SELECT id, max(division) AS division FROM Users WHERE 1=1" . WHERE_PERIOD . " GROUP BY id
    ) a INNER JOIN (
      SELECT id,division,name FROM Users
    ) b
    ON a.id=b.id AND a.division=b.division
  ) u
  ON u.id = a.create_user_id
  WHERE " . $WHERE
);
$logger->debug(print_r($stockTrackings, true));
// create paring object from fetch rows
$items = (new DBFactory())->query(
  'SELECT a.id, a.division, b.name FROM
  (
    SELECT id, max(division) AS division FROM Item WHERE 1=1' . WHERE_PERIOD . ' GROUP BY id
  ) a INNER JOIN (
    SELECT id,division,name FROM Item
  ) b
  ON a.id=b.id AND a.division=b.division');

const _MAX_NEW_ENTRY = 10;
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Pegasus System -- Stock Maintenance Inquiry / Report</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>
    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 update_default_value() {
      var qs_=qs();
      for(var q in qs_) {
        $('.info').find('.parse_query_str')
          .filter(function(){return $(this).attr('name')==q}).val(qs_[q]);
      }

      $('.custom-drop-down-list').find('select.parse_query_str').each(function() {
        var key = $(this).attr('name');
        $(this).parent().find('.select-items div')
          .filter(function(){return $(this).html()==qs_[key]}).click();
      });

    }

    $(document).ready(function() {

      update_default_value();

      var today = {
        year: new Date().getFullYear(),
        month: (new Date().getMonth()+1).pad(2),
        date: new Date().getDate().pad(2)
      };

      $.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: 'excelHtml5',
              text: 'Excel Output',
              filename:  today.year + '-' + today.month + '-' + today.date + ' - Stock_inquiry_report',
              exportOptions: {
                  columns: [1,2,3,4,5,6,7,8,9,10,11]
              }
            },
            {
              extend: 'pdfHtml5',
              orientation: 'landscape',
              pageSize: 'LEGAL',
              text: 'PDF Output',
              filename:  today.year + '-' + today.month + '-' + today.date + ' - Stock_inquiry_report',
              customize: function(doc) {
                doc['header'] = (function(page, pages) {
                  return {
                    columns: [
                      {
                        alignment: 'right',
                        text: [
                          'page ',
                          { text: page.toString(), italics: true },
      					          ' / ',
                          { text: pages.toString(), italics: true }
      				          ]
                    }],
                    margin: [10, 10]
                  }
                });
              },
              exportOptions: {
                  columns: [1,2,3,4,5,6,7,8,9,10,11]
              }
            }
        ],
        select: {
            style:    'multi',
            selector: 'tr:not(.no-select) td'
        },
        'pagingType': 'full_numbers',
        'searching': false,
        "order": [[ 1, "asc" ]],
        /* no any columns unsortable*/
        'columnDefs': [ {
          'targets': [0],
          'orderable': false,
        }],
        "pageLength": 25,

      });

      $('input[id^=tbDate]').datetimepicker({
        dateFormat: 'yy-mm-dd'
      });

      $('#btn_clear').on('click', function() {
        $('#frm-primary').trigger('reset');
        $('#ddl_item_from, #ddl_item_to').each(function() {
          $(this).parent().find('.same-as-selected').removeClass('same-as-selected');
          $(this).parent().find('.select-selected')
            .html($(this).children("option:selected").text());
        });
      });

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

        item_ = '';
        var keep = false;
        if ($('#ddl_item_from').children("option:selected").val() != 0
          && $('#ddl_item_to').children("option:selected").val() != 0) {
          $('#ddl_item_from > option').each(function() {
            if ($(this).val() == $('#ddl_item_from').children("option:selected").val()) {
              keep = true;
            }
            if (keep) {
              item_ += $(this).val() + ",";
            }
            if ($(this).val() == $('#ddl_item_to').children("option:selected").val()) {
              keep = false;
              return;
            }
          });
        }


        var params = {
          cmd : 'search',
          date_from: $('#tbDate1').val(),
          date_to: $('#tbDate2').val(),
          item : item_.slice(0, -1),
        };

        params = removeUndefined(params);
        /*console.log(params); return false;*/
        for (var key in params) {
          $('<input>').attr({ type: 'hidden', name: key, value: params[key] }).appendTo('#frm-primary');
        }

        $('#frm-primary').submit();

      });
    });
  </script>

  <style>
  @import url('https://fonts.googleapis.com/css?family=Josefin+Sans&display=swap');
  *{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    list-style: none;
    text-decoration: none;
    font-family: 'Josefin Sans', sans-serif;
  }
  </style>
</head>
<body>
  <div class="main_content">
    <div class="header" style="text-align: center; background: #0070c0; color: white;"><h2> Stock Maintenance Inquiry / Report </h2><p style="text-align:right; font-size: 10px;">Version 1.0</p></div>
      <div class="info" >
        <form method="GET" id="frm-primary">
          <div style="float:right">
            Item name : <input type="text" id="item_name" name="item_name" class="parse_query_str" placeholder="search item name" />
          </div>
          <div>
            Date :
            <input type="text" id="tbDate1" name="date_from" class="parse_query_str xlwidth tbDate" placeholder="select a date" autocomplete="off" />
            ~
            <input type="text" id="tbDate2" name="date_to" class="parse_query_str xlwidth tbDate" placeholder="select a date" autocomplete="off" />
          </div>
          <div style="float:right">
            <input id="btn_search" type="submit" value="Search">
            <input id="btn_clear" type="button" value="Clear">
          </div>
          <div>
            Item code :
            <div class="custom-drop-down-list">
<?
              print Util::convert2DropDownList('item_from',$items,'id','id',null,null,null,null, 'parse_query_str');

?>
            </div>
            ~
            <div class="custom-drop-down-list" style="margin-right:20px">
<?
              print Util::convert2DropDownList('item_to',$items,'id','id',null,null,$items[count($items)-1]['id'],null, 'parse_query_str');
?>
            </div>
            <span style="display:inline-table">
              Section :
<?
              $section_ = array(
                array('title'=>'All', 'val'=>''),
                array('title'=>'Inbound', 'val'=>'Inbound'),
                array('title'=>'Outbound', 'val'=>'Outbound'),
                array('title'=>'Stock Maintenance', 'val'=>'Stock Maintenance'),
              );
              print Util::convert2DropDownList('section',$section_,'val','title',null,null
                ,null
                ,null, 'parse_query_str' );
?>
            </span>
          </div>
        </form>
     </div>

<!--
  +++++ Table preview section +++++
 -->
      <div class="display" id="display_div">
        <table id="table_preview" class="display dataTable">
          <thead>
            <tr>
              <th><i class="data-editor dd-icon fas fa-black fa-check-double" for="select_all" title="select all"></i></th>
              <th>Date</th>
              <th>Item code</th>
              <th>Item name</th>
              <th>Product date</th>
              <th>Inbound</th>
              <th>Outbound</th>
              <th>Increase/Decrease</th>
              <th>Section</th>
              <th>User code</th>
              <th>User name</th>
              <th>Slip divide</th>
            </tr>
          </thead>
          <tbody>
<?

            $i = 0;
            $display_cols = array(
              'id'=>0,
              'create_dt'=>0,
              'item_id'=>0,
              'item_name'=>0,
              'product_date'=>0,
              'inbound_qty'=>0,
              'outbound_qty'=>0,
              'increase'=>0,
              'section'=>0,
              'create_user_id'=>0,
              'user_name'=>0,
              'slip_divide'=>0
            );
            foreach ($stockTrackings as $index => $row) {
              echo '<tr>';
              foreach ($display_cols as $key => $val) {
                if ($key == 'product_date') {
                  $format = "Y-m-d";
                  if ($row[$key])
                    $data = $row[$key]->format($format);
                  else
                    $data = "";
                  echo '<td><span class="data-display">' . $data . "</span>"
                    . '</td>';
                } else if ($row[$key] instanceof DateTime) {
                  echo '<td><span id="' . $key . '" class="data-display">'
                    . convertTz($row[$key]->format('Y-m-d H:i:s'), 'UTC', $db_user['timezone']['time_zone']) . "</span>"
                    . '</td>';
                } else if ($key == 'increase') {
                  echo '<td><span class="data-display ' . ( $row[$key]<0 ? 'warning' : '') . '">' . $row[$key] . '</span>'
                    . '</td>';
                } else if ($key == 'id') {
                  echo '<td>' . ++$i
                    . '</td>';
                } else if ($key == 'slip_divide') {
                  echo '<td><span class="data-display">' . SlipDivide::getConstant($row[$key])->toString() . "</span>"
                    . '</td>';
                } else {
                  echo '<td><span class="data-display">' . $row[$key] . '</span>'
                    . '</td>';
                }
              }
              echo '</tr>';
            }
?>

      </tbody>
      <tfoot>
        <tr>
          <th>#</th>
          <th>Date</th>
          <th>Item code</th>
          <th>Item name</th>
          <th>Product date</th>
          <th>Inbound</th>
          <th>Outbound</th>
          <th>Increase/Decrease</th>
          <th>Section</th>
          <th>User code</th>
          <th>User name</th>
          <th>Slip divide</th>
        </tr>
      </tfoot>
    </table>
    </div>
  </div>
</body>
<script src="js/custom-drop-down-list.js"></script>
</html>
