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

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

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


// Inquiry datas
$datas = null;
$WHERE = "";

$month_ini = new DateTime("first day of last month");
$month_end = new DateTime("last day of last month");
$WHERE_DATE = " BETWEEN '" . $month_ini->format('Y-m-d') . " 00:00:00' AND '" . $month_end->format('Y-m-d') . " 23:59:59'";

if (isset($_GET['dtype'])) {
  if ($_GET['dtype'] == 'monthly') {
    $month_ini = (new DateTime($_GET['real_date']))->format('Y-m-01');
    $month_end = (new DateTime($_GET['real_date']))->format('Y-m-t');
    $WHERE_DATE = " BETWEEN '" . $month_ini . " 00:00:00' AND '" . $month_end . " 23:59:59'";
  } else {
    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_DATE = " 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_DATE = " > '" . $df . "'";
    } else if (isset($_GET['date_to']) && !empty($_GET['date_to'])) {
      $dt = convertTz($_GET['date_to'], $db_user['timezone']['time_zone'], 'UTC');
      $WHERE_DATE = " < '" . $dt . "'";
    }
  }
}

if (isset($_GET['department'])) {
  // example input 00000001-001,00000001-002,00000001-003,00000001-004
  $WHERE .= " AND d.id IN (" . Util::encapsulateWithQuote($_GET['department']) . ")";
}

//$datas = (new Inbound())->get(Inbound::$__COLUMNS, $WHERE);
$datas = (new DBFactory())->query(
  "SELECT d.name AS 'department', i.id AS 'item_id', i.name AS 'item_name'
  , b.qty AS qty, i.unit_price, b.qty*i.unit_price AS amount
  FROM item i
  INNER JOIN
  (
    SELECT ob.item_id, ob.item_dvsn_id, d.id AS dept_id, d.division AS dept_dvsn_id, sum(ob.qty) AS qty FROM
    (
      SELECT ob.id, max(u.division) AS user_division, max(d.division) AS dept_division
      FROM Outbound ob
      INNER JOIN Users u
      ON ob.create_user_id = u.id
      AND (
    		ob.create_dt BETWEEN u.period_from AND u.period_to
    		OR (u.period_to IS NULL AND ob.create_dt > u.period_from)
    		OR (u.period_from IS NULL AND ob.create_dt < u.period_to)
    	)
      INNER JOIN Department d
      ON u.dept_id = d.id
      AND (
    		ob.create_dt BETWEEN d.period_from AND d.period_to
    		OR (d.period_to IS NULL AND ob.create_dt > d.period_from)
    		OR (d.period_from IS NULL AND ob.create_dt < d.period_to)
    	)
      WHERE ob.create_dt " . $WHERE_DATE . "
      GROUP BY ob.id
    ) o
    INNER JOIN Outbound ob
    ON o.id = ob.id
    INNER JOIN Users u
    ON ob.create_user_id = u.id
    AND o.user_division = u.division
    INNER JOIN Department d
    ON u.dept_id = d.id
    AND o.dept_division = d.division
    GROUP BY ob.item_id, ob.item_dvsn_id, d.id, d.division
  ) b
  ON b.item_id = i.id
  AND b.item_dvsn_id = i.division
  INNER JOIN Department d
  ON b.dept_id = d.id
  AND b.dept_dvsn_id = d.division
  WHERE 1=1 " . $WHERE
);


// create paring object from fetch rows
$departments = (new DBFactory())->query(
  'SELECT a.id, a.division, b.name FROM
  (
    SELECT id, max(division) AS division FROM Department WHERE 1=1' . WHERE_PERIOD . ' GROUP BY id
  ) a INNER JOIN (
    SELECT id,division,name FROM Department
  ) b
  ON a.id=b.id AND a.division=b.division');

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

}
*/

?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Pegasus System -- Outbound List by Department</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" />
  <link href="css/ext/jsuites/v4/jsuites.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/datetime.js"></script>
  <script src="js/jquery-ui-timepicker-addon.js"></script>
  <script src="js/ext/jsuites/v4/jsuites.js"></script>

  <script>
    var qs_=qs();

    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:not(input[type=radio])')
          .filter(function(){return $(this).attr('name')==q}).val(qs_[q]);
      }

      $('.info').find('input[type=radio].parse_query_str').each(function() {
        if (qs_[$(this).attr('name')])
          $(this).prop('checked', qs_[$(this).attr('name')] == $(this).val() ? true : false);
      });

      $('.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).attr('value')==qs_[key]}).click();
      });

    }

    function dtype_on_change(e) {
      $('.' + $(e).attr('for')).prop("disabled", !$(e).is(":checked"));
    }

    $(document).ready(function() {

      var today = {
        year: new Date().getFullYear(),
        month: (new Date().getMonth()+1).pad(2),
        smonth: MonthArry[new Date().getMonth()],
        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',
              title: function () { return $('#pdf-title').val(); },
              filename:  today.year + '-' + today.month + '-' + today.date + ' - Outbound_list_by_department_report',
              exportOptions: {
                  columns: [1,2,3,4,5,6]
              }
            },
            {
              extend: 'pdfHtml5',
              //orientation: 'landscape',
              pageSize: 'LEGAL',
              text: 'PDF Output',
              title: function () { return $('#pdf-title').val(); },
              filename:  today.year + '-' + today.month + '-' + today.date + ' - Outbound_list_by_department_report',
              customize: function(doc) {
                doc['header'] = (function(page, pages) {
                  return {
                    columns: [
                      {
                        alignment: 'left',
                        text: [
                          'Date : ',
                          today.date,
      					          '-',
                          today.smonth,
      					          '-',
                          today.year,
      				          ]
                      },
                      {
                        alignment: 'right',
                        text: [
                          'page ',
                          { text: page.toString(), italics: true },
      					          ' / ',
                          { text: pages.toString(), italics: true }
      				          ]
                      },
                    ],
                    margin: [15, 15]
                  }
                });
              },
              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,

      });

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

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

        department_ = '';
        var keep = false;
        $('#ddl_department_from > option').each(function() {
          if ($(this).val() == $('#ddl_department_from').children("option:selected").val()) {
            keep = true;
          }
          if (keep) {
            department_ += $(this).val() + ",";
          }
          if ($(this).val() == $('#ddl_department_to').children("option:selected").val()) {
            keep = false;
            return;
          }
        });
        //
        // $('.enable_on').each(function() {
        //   console.log($(this)[0], $(this).html(), $(this).val(), $(this).is(':checked'));
        // });
        // console.log($('.enable_on:checked').val()); return;

        var params = {
          cmd : 'search',
          department : department_.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();

      });

      var _3y_early = new Date().getFullYear()-3;
      $('input.calendar')
      .each(function() {
        jSuites.calendar($(this)[0], {
          type: 'year-month-picker',
          format: 'Mon-YYYY',
          validRange: [ _3y_early + '-01-01', today.year + '-' + today.month + '-31' ],
          onchange: function(el, newValue, oldValue) {
            console.log(el, newValue, oldValue);
              var month_year = new DateFormatter('%N %y').format(new Date(newValue));
              $('#pdf-title').val(month_year + ' Monthly Report for outbound list by department');
              $('#real_date').val(new DateFormatter('%y-%m-%d').format(new Date(newValue)));
          }
        });
        $(this).val('last month');
      });

      $('.enable_on')
      .on('change', function() {
        $('[class^=enable_on_]').prop("disabled", true);
        dtype_on_change($(this)[0]);
      });

      update_default_value();
      $('.enable_on').each(function() {
        dtype_on_change($(this)[0]);
      });

      if ($('#r_monthly').is(':checked')) {
        var dstr = $('#txt_month').val();
        var a_ = [1,2,3,4,5,6,7,8,9,10,11,12].mergeWithPairedKey(MonthArry);
        if (dstr == 'last month') dstr = getFirstDayOfLastMonth(1);
        else {
          var tmp = dstr.split('-');
          dstr = tmp[1] + '-' + a_[tmp[0]] + '-01';
        }
        var last_month_year = new DateFormatter('%N %y').format(new Date(dstr));
        $('#pdf-title').val(last_month_year + ' Monthly Report for outbound list by department');
      } else {
        if (qs_['date_from'] && qs_['date_from']!=''
          && qs_['date_to'] && qs_['date_to']!='') {
          $('#pdf-title').val(qs_['date_from'] + ' - ' + qs_['date_to'] + ' Report for outbound list by department');
        } else if (qs_['date_from'] && qs_['date_from']!='') {
          $('#pdf-title').val('After ' + qs_['date_from'] + ' Report for outbound list by department');
        } else if (qs_['date_to'] && qs_['date_to']!='') {
          $('#pdf-title').val('Before ' + qs_['date_to'] + ' Report for outbound list by department');
        } else {
          var last_month_year = new DateFormatter('%N %y').format(getFirstDayOfLastMonth(1));
          $('#pdf-title').val(last_month_year + ' Monthly Report for outbound list by department');
        }
      }

    });
  </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;
  }
  input.calendar {
    outline: none;
    border: solid 1px #333;
  }
  </style>
</head>
<body>
  <div class="main_content">
    <div class="header" style="text-align: center; background: #0070c0; color: white;"><h2> Outbound List by Department </h2><p style="text-align:right; font-size: 10px;">Version 1.0</p></div>
      <div class="info" >
        <form method="GET" id="frm-primary">
          <input type="hidden" id="pdf-title">
          <div class="float-right">
            Department :
            <div class="custom-drop-down-list">
<?
              print Util::convert2DropDownList('department_from',$departments,'id','name',null,null,$departments[0]['id'],null,'parse_query_str');
?>
            </div>
            ~
            <div class="custom-drop-down-list">
<?
              print Util::convert2DropDownList('department_to',$departments,'id','name',null,null,$departments[count($departments)-1]['id'],null,'parse_query_str');
?>
            </div>
          </div>
          <div>
            <input type="hidden" name="real_date" id="real_date" value="last month" class="parse_query_str" >
            <input type="radio" name="dtype" id="r_monthly" value="monthly" class="enable_on parse_query_str" for="enable_on_r1" checked><label for="r_monthly"> Monthly :</label>
            <input type="text" name="txt_month" id="txt_month" class="enable_on_r1 xlwidth calendar parse_query_str"><br/>
            <input type="radio" name="dtype" id="r_date" value="date" class="enable_on parse_query_str" for="enable_on_r2"><label for="r_date"> Date Range</label><br/>
            Date :
            <input type="text" id="tbDate1" name="date_from" placeholder="select a date" class="enable_on_r2 parse_query_str xlwidth tbDate" autocomplete="off" disabled />
            ~
            <input type="text" id="tbDate2" name="date_to" placeholder="select a date" class="enable_on_r2 parse_query_str xlwidth tbDate" autocomplete="off" disabled />
          </div>
          <div class="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>Department</th>
              <th>Parts No</th>
              <th>Parts Name</th>
              <th>OUT Qty</th>
              <th>Unit Price</th>
              <th>Amount Price</th>
            </tr>
          </thead>
          <tbody>
<?

            $i = 0;
            $display_cols = array(
              'id'=>0,
              'department'=>0,
              'item_id'=>0,
              'item_name'=>0,
              'qty'=>0,
              'unit_price'=>0,
              'amount'=>0,
            );
            foreach ($datas as $index => $row) {
              echo '<tr>';
              foreach ($display_cols as $key => $val) {
                if ($key == 'id') {
                  echo '<td>' . ++$i
                    . '</td>';
                } else if ($key == 'amount' || $key == 'unit_price') {
                  echo '<td><span id="' . $key . '_' . $row['id'] . '" map="' . $key . '_' . $row['id'] . '" class="data-display">' . number_format($row[$key], 2) . '</span>'
                    . '</td>';
                } else {
                  echo '<td><span id="' . $key . '_' . $row['id'] . '" map="' . $key . '_' . $row['id'] . '" class="data-display">' . $row[$key] . '</span>'
                    . '</td>';
                }
              }
              echo '</tr>';
            }
?>

      </tbody>
      <tfoot>
        <tr>
            <th>#</th>
            <th>Department</th>
            <th>Parts No</th>
            <th>Parts Name</th>
            <th>OUT Qty</th>
            <th>Unit Price</th>
            <th>Amount Price</th>
        </tr>
      </tfoot>
    </table>
    </div>
  </div>
</body>

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