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

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

if (isset($_POST['cmd'])) {
  $status = "success";
  $error = "";

  $a = $_POST;
  $affected_rows = 0;

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

  switch ($a['cmd']) {
    case 'edit':
      foreach ($a['stock_datas'] as $index => $stock_data) {
        // Insert to DB
        $cols = Stock::$__COLUMNS;

        // remove unwant data
        $unsets = ['item_id', 'item_dvsn_id', 'product_date', 'carry_over', 'stocktaking', 'stocktaking_status', 'location_id', 'location_dvsn_id', 'create_dt', 'create_user_id', 'update_dt'];
        foreach ($unsets as $u) unset($cols[$u]);
        $cols = Util::parseArrayData($cols, $stock_data);
        $cols['update_user_id'] = $db_user['user']['id'];
        $result = (new Stock())->set($cols,
          "item_id='" . $stock_data['item_id'] . "' AND item_dvsn_id=" . $stock_data['item_dvsn_id']
          . " AND location_id='" . $stock_data['location_id'] . "' AND location_dvsn_id=" . $stock_data['location_dvsn_id']
          . " AND product_date='" . $stock_data['product_date'] . "'"
        );

        if ($result > 0) {
          $cols = StockTracking::$__COLUMNS;
          // remove unwant data
          $unsets = ['id', 'create_dt', 'refer_id', 'update_dt', 'update_user_id'];
          foreach ($unsets as $u) unset($cols[$u]);
          $cols = Util::parseArrayData($cols, $stock_data);
          $cols['section'] = 'Stock Maintenance';
          $diff = $stock_data['qty'] - $stock_data['old_qty'];
          $cols['increase'] = $diff;
          if ($diff > 0) {
            $cols['inbound_qty'] = $diff;
            $cols['slip_divide'] = SlipDivide::PC_Input;
          } else if ($diff < 0) {
            $cols['outbound_qty'] = abs($diff);
            $cols['slip_divide'] = SlipDivide::PC_Output;
          }
          $cols['item_dvsn_id'] = $stock_data['item_dvsn_id'];
          $cols['create_user_id'] = $db_user['user']['id'];

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

          if ($diff != 0) {
            (new StockTracking())->add($cols);
          }

        }


        $affected_rows += $result;
      }
      break;

    default:
      $status = "error";
      $error = "unknown command : " . $a['cmd'];
      break;
  }

  $arry = array(
    'status' => $status,
    'error' => $error,
    'affected_rows' => $affected_rows
  );
  print json_encode($arry);

  return;
}

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



$stocks = (new DBFactory())->query(
  'SELECT s.*, s.qty-s.stocktaking AS difference, it.name, it.unit_price, it.order_point, s.qty*it.unit_price AS amount'
  . ' FROM Stock s'
  . ' INNER  JOIN Item it'
  . ' ON it.id = s.item_id'
  . ' AND it.division = s.item_dvsn_id'
  . ' WHERE ' . $WHERE
);

// $arry = array(
//   'stocks' => $stocks,
//  );
//  print json_encode($arry);
// 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 Maintenance</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/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 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();

      $.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.day + ' - Stock_inquiry_report',
            },
            {
              extend: 'pdfHtml5',
              orientation: 'landscape',
              pageSize: 'LEGAL',
              text: 'PDF Output',
              filename:  today.year + '-' + today.month + '-' + today.day + ' - Stock_inquiry_report',
            }
        ],
        */
        'pagingType': 'full_numbers',
        'searching': false,
        "order": [[ 0, "asc" ]],
        /* no any columns unsortable
        'columnDefs': [ {
          'targets': [12],
          '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();

      });

      $('#btn_register').on('click', function() {
        var stock_data_ = new Array();
        $('input[id^=qty_]').each(function( evt ) {
          if ($(this).val() != $(this).attr('old_data')) {
            /* check proper data */
            var stock_data = {
              item_id : $(this).closest('tr').find('span[id^=item_id]').html(),
              item_dvsn_id : $(this).closest('tr').find('span[id^=item_id]').attr('division'),
              location_id : $(this).closest('tr').find('span[id^=location_id]').html(),
              location_dvsn_id : $(this).closest('tr').find('span[id^=location_id]').attr('division'),
              qty : $(this).val(),
              old_qty : $(this).attr('old_data'),
            };
            stock_data_.push(stock_data);
          }
        });

        if (stock_data_.length == 0) return false;

        console.log(stock_data_);
        var params = {
          cmd : 'edit',
          stock_datas : stock_data_,
        }

        params = removeUndefined(params);
        $.post("", params)
        .done( function (data) {
          console.log(data);
          var json = JSON.parse(data);

          if (json.status == "success") {
            $('#info-pane', top.document).html('Data has been updated successfully.');
            $('#_if', top.document).attr('src', $('#_if', top.document).contents().get(0).location.href);
          } else {
            $('#warn-pane', top.document).html('Error! ' + json.error);
          }
        });

      });


    });
  </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 </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>
          <div>
            <input id="btn_register" type="button" value="Register">
          </div>
        </form>
     </div>

<!--
  +++++ Table preview section +++++
 -->
      <div class="display" id="display_div">
        <table id="table_preview" class="display dataTable">
          <thead>
            <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>
          </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') {
                  $format = "Y-m-d";
                  echo '<td><span id="' . $key . '" class="data-display">'
                    . $row[$key]->format($format) . "</span>"
                    . '</td>';
                } else if ($key == 'item_id') {
                  echo '<td><span id="' . $key . '" class="data-display" division="' . $row['item_dvsn_id'] . '">'
                    . $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" division="' . $row['location_dvsn_id'] . '">'
                    . $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><input type="text" id="qty_' . $i . '" old_data="' . $row[$key] . '" class="data-display mwidth" value="'
                    . $row[$key] . '">'
                    . '</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>
