<?
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']);

include_once "lib/sanitize.php";
//ob_start("sanitize_html");

// memcached integrated
require_once "lib/Memcached_pool.php";
$mcache = new Memcached();
$mcache->addServers($GLOBALS['memcached-sets'][DEFAULT_MEMCACHED_SET]);

// 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.08';
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";
require_once "lib/ext/DateTimeUtil.php";


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

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

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

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

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

$sql = 'SELECT i.id, i.name, i.unit_price, ISNULL(a.qty, 0) as qty, ISNULL(a.qty, 0)*i.unit_price as amount
  , CASE WHEN a.update_dt IS NULL THEN \'-\' ELSE CONVERT(VARCHAR, a.update_dt, 120) END AS update_dt
  FROM 
  (
    SELECT id, max(division) AS division FROM Item WHERE 1=1' . WHERE_PERIOD . ' GROUP BY id
  ) ii
  INNER JOIN Item i
  ON i.id = ii.id
  AND i.division = ii.division
  LEFT JOIN
  (
    SELECT item_id, SUM(qty) AS qty, MAX(update_dt) AS update_dt 
    FROM Stock
    GROUP BY item_id
  ) a
  ON i.id = a.item_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($_REQUEST['cmd'] && $_REQUEST['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 Summary 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>
    var qs_=qs();
    var qs_ = <?=json_encode($_REQUEST ?? null)?>;
    
    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() {
      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]
              }
            },
            {
              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]
              }
            }
        ],
        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;
            }
          });
        }


        var params = {
          cmd : 'search',
          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 Summary Report </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="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>
        </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>Unit price</th>
              <th>Stock quantity</th>
              <th>Amount</th>
              <th>Last update</th>
            </tr>
          </thead>
          <tbody>
<?

            $i = 0;
            $display_cols = array(
              'id'=>'',
              'name'=>'',
              'unit_price'=>0,
              'qty'=>0,
              'amount'=>0,
              'update_dt'=>'',
            );
            foreach ($stocks as $index => $row) {
              echo '<tr>';
              foreach ($display_cols as $key => $val) {
                
                if ($key == 'qty') {
                  echo '<td><span id="' . $key . '" class="data-display">' . number_format($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><td><span id="' . $key . '" class="data-display">' . $row[$key]  . "</span>"
                    . '</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>Unit price</th>
            <th>Stock quantity</th>
            <th>Amount</th>
            <th>Last update</th>
        </tr>
      </tfoot>
    </table>
    </div>
  </div>
</body>
<script src="js/custom-drop-down-list.js"></script>
</html>
