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

require_once "lib/Stock.php";
require_once "lib/Item.php";
require_once "lib/Location.php";
require_once "lib/DBFactory.php";


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

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

if (isset($_GET['location']) && !empty($_GET['location'])) {
  // example input 00000001-001,00000001-002,00000001-003,00000001-004
  $WHERE .= " AND location_id IN (" . Util::encapsulateWithQuote($_GET['location']) . ")";
}

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


$sql = 'SELECT it.id AS item_id, it.division AS item_dvsn_id, it.name, it.order_point
    , ISNULL(s.qty, 0)-ISNULL(s.stocktaking, 0) AS difference
    , ISNULL(s.qty, 0) AS qty, it.unit_price
    , ISNULL(s.qty, 0)*it.unit_price AS amount
    , CASE WHEN s.product_date IS NULL THEN \'-\' ELSE CONVERT(VARCHAR, s.product_date) END AS product_date
    , ISNULL(s.carry_over, \'-\') AS carry_over
    , ISNULL(s.stocktaking, 0) AS stocktaking
    , ISNULL(s.location_id, \'-\') AS location_id
    FROM Item it
    LEFT JOIN Stock s
    ON it.id = s.item_id
    AND it.division = s.item_dvsn_id
    WHERE ' . $WHERE;
$logger->debug($sql);
$stocks = (new DBFactory())->query($sql);
// 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');
$items_name = Item::DbRows2ArrayMapWithDivisions((new Item())->getAll(),'id','name','division');
$locations = (new DBFactory())->query(
  'SELECT a.id, a.division, b.name FROM
  (
    SELECT id, max(division) AS division FROM Location WHERE 1=1' . WHERE_PERIOD . ' GROUP BY id
  ) a INNER JOIN (
    SELECT id,division,name FROM Location
  ) b
  ON a.id=b.id AND a.division=b.division');

/*
if (isset($_GET['cmd'] && $_GET['cmd'] == 'search')) {

}
*/

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 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/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>
    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,

      });

      $('#btn_clear').on('click', function() {
        $('#frm-primary').trigger('reset');
        $('#ddl_location_from, #ddl_location_to, #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;
            }
          });
        }

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


        var params = {
          cmd : 'search',
          item : item_.slice(0, -1),
          location : location_.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 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" placeholder="search item name" class="parse_query_str" />
          </div>
          <div>
            Item code :
            <div class="custom-drop-down-list">
<?
              print Util::convert2DropDownList('item_from',$items,'id','id',null,null,$items[0]['id'],null,'parse_query_str');

?>
            </div>
            ~
            <div class="custom-drop-down-list">
<?
              print Util::convert2DropDownList('item_to',$items,'id','id',null,null,$items[count($items)-1]['id'],null,'parse_query_str');
?>
            </div>
          </div>
          <div style="float:right">
            <input id="btn_search" type="submit" value="Search">
            <input id="btn_clear" type="button" value="Clear">
          </div>
          <div>
            Location :
            <div class="custom-drop-down-list">
<?
              print Util::convert2DropDownList('location_from',$locations,'id','id',null,null,$locations[0]['id'],null,'parse_query_str');

?>
            </div>
            ~
            <div class="custom-drop-down-list">
<?
              print Util::convert2DropDownList('location_to',$locations,'id','id',null,null,$locations[count($locations)-1]['id'],null,'parse_query_str');
?>
            </div>
          </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>Item code</th>
              <th>Item name</th>
              <th>Product date</th>
              <th>Carry-over</th>
              <th>Stocktaking</th>
              <th>Ordering point</th>
              <th>Difference</th>
              <th>Stock quantity</th>
              <th>Unit price</th>
              <th>Amount</th>
              <th>Location</th>
            </tr>
          </thead>
          <tbody>
<?

            $i = 0;
            $display_cols = array(
              'id'=>0,
              'item_id'=>0,
              'product_date'=>0,
              'carry_over'=>0,
              'stocktaking'=>0,
              'order_point'=>0,
              'difference'=>0,
              'qty'=>0,
              'unit_price'=>0,
              'amount'=>0,
              'location_id'=>0,
            );
            foreach ($stocks as $index => $row) {
              echo '<tr>';
              foreach ($display_cols as $key => $val) {
                
                if ($key == 'product_date') {
                  echo '<td><span id="' . $key . '" class="data-display">' . $row[$key]  . "</span>"
                    . '</td>';
                } else if ($key == 'item_id') {
                  echo '<td><span id="' . $key . '" class="data-display">' . $row[$key]  . "</span>"
                    . '</td>';
                  echo '<td><span class="data-display">' . $items_name[$row[$key]][$row['item_dvsn_id']] . '</span></td>';
                } else if ($key == 'location_id') {
                  echo '<td><span id="' . $key . '" class="data-display">' . $row[$key] . "</span>"
                    . '</td>';
                } else if ($key == 'stocktaking') {
                  echo '<td><span id="' . $key . '" class="data-display">' . number_format($row[$key]) . "</span>"
                    . '</td>';
                } else if ($key == 'order_point') {
                  echo '<td><span id="' . $key . '" class="data-display">' . number_format($row[$key]) . "</span>"
                    . '</td>';
                } else if ($key == 'qty') {
                  echo '<td><span id="' . $key . '" class="data-display">' . number_format($row[$key]) . "</span>"
                    . '</td>';
                } else if ($key == 'difference') {
                  echo '<td><span class="data-display ' . ( $row[$key] < 0 ?'warning-stock':'') . '">'
                    . number_format(abs($row[$key]))
                    . '</span></td>';
                } else if ($key == 'unit_price' || $key == 'amount') {
                  echo '<td><span class="data-display">' . number_format($row[$key], 2) . '</span>'
                    . '</td>';
                } else if ($key == 'id') {
                  echo '<td>' . ++$i
                    . '</td>';
                } else {
                  echo '<td><span id="' . $key . '_' . $row['id'] . '" class="data-display">' . $row[$key] . '</span>'
                    . '</td>';
                }
              }
              echo '</tr>';
            }
?>

      </tbody>
      <tfoot>
        <tr>
            <th>#</th>
            <th>Item code</th>
            <th>Item name</th>
            <th>Product date</th>
            <th>Carry-over</th>
            <th>Stocktaking</th>
            <th>Ordering point</th>
            <th>Difference</th>
            <th>Stock quantity</th>
            <th>Unit price</th>
            <th>Amount</th>
            <th>Location</th>
        </tr>
      </tfoot>
    </table>
    </div>
  </div>
</body>
<script src="js/custom-drop-down-list.js"></script>
</html>
