<?php
/**
 * Copyright (C) 2007,2008  Arie Nugraha (dicarve@yahoo.com)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

/* Current Stock Take Process */

// key to authenticate
define('INDEX_AUTH', '1');

// main system configuration
require '../../../sysconfig.inc.php';
// IP based access limitation
require LIB.'ip_based_access.inc.php';
do_checkIP('smc');
do_checkIP('smc-stocktake');
// start the session
require SB.'admin/default/session.inc.php';
require SB.'admin/default/session_check.inc.php';
require SIMBIO.'simbio_GUI/table/simbio_table.inc.php';
require SIMBIO.'simbio_GUI/form_maker/simbio_form_table_AJAX.inc.php';
require SIMBIO.'simbio_GUI/paging/simbio_paging.inc.php';
require SIMBIO.'simbio_DB/datagrid/simbio_dbgrid.inc.php';

// privileges checking
$can_read = utility::havePrivilege('stock_take', 'r');
$can_write = utility::havePrivilege('stock_take', 'w');

if (!($can_read AND $can_write)) {
    die('<div class="errorBox">'.__('You don\'t have enough privileges to access this area!').'</div>');
}

/* ----------------------------------------------------
 * CEK LIBRARY_ID & ROLE DARI PUSTAKAWAN YANG LOGIN
 * ---------------------------------------------------- */
$user_lib_id = $_SESSION['user_lib_id'] ?? null;

if (($user_lib_id === null || $user_lib_id === '') && isset($_SESSION['uid'])) {
    $user_q = $dbs->query("SELECT library_id FROM user WHERE user_id = " . intval($_SESSION['uid']));
    if ($user_q && $user_d = $user_q->fetch_assoc()) {
        $user_lib_id = $user_d['library_id'];
    }
}

// SUPERADMIN HANYA JIKA library_id BERISIKAN 1, NULL, ATAU 0
$is_super_admin = (empty($user_lib_id) || $user_lib_id == 1 || $user_lib_id == 0);

// Menentukan Target library_id
$target_lib_id = $user_lib_id ?: 1;
if ($is_super_admin && isset($_GET['library_id']) && $_GET['library_id'] !== '') {
    $target_lib_id = intval($_GET['library_id']);
}

// Show only current user stock take item flag
if (isset($_GET['listShow']) && $_GET['listShow'] == '1') {
    $show_only_current = 1;
}

// Cek apakah ada proses Stock Take yang AKTIF untuk unit target
$stk_sql = "SELECT * FROM stock_take WHERE is_active=1";
if (!$is_super_admin || (isset($_GET['library_id']) && $_GET['library_id'] !== '')) {
    $stk_sql .= " AND library_id = " . intval($target_lib_id);
}
$stk_query = $dbs->query($stk_sql);

if ($stk_query->num_rows < 1) {
    echo '<div class="errorBox">'.__('NO stock taking proccess initialized yet for this library unit!').'</div>';
    
    // Jika Superadmin, tampilkan dropdown pilihan unit agar bisa berpindah perpustakaan
    if ($is_super_admin) {
        echo '<div class="sub_section p-3"><form method="get" action="'.MWB.'stock_take/current.php" class="form-inline">';
        echo '<label class="mr-2 font-weight-bold">'.__('Pilih Perpustakaan').' : </label>';
        echo '<select name="library_id" class="form-control col-md-3 mr-2" onchange="this.form.submit()">';
        $libs = $dbs->query("SELECT library_id, library_name FROM mst_library ORDER BY library_name");
        while ($lib = $libs->fetch_assoc()) {
            $selected = ($target_lib_id == $lib['library_id']) ? 'selected' : '';
            echo '<option value="' . $lib['library_id'] . '" ' . $selected . '>' . htmlspecialchars($lib['library_name']) . '</option>';
        }
        echo '</select>';
        echo '</form></div>';
    }
} else {
    // Ambil data stock take yang aktif
    $active_stk_data = $stk_query->fetch_assoc();
    $active_lib_id   = $active_stk_data['library_id'];

    // Check view mode
    $view = 'e';
    if (isset($_GET['view']) AND $_GET['view']) {
        $view = trim($_GET['view']);
    }

    // Include Barcode Scanner
    if($sysconf['barcode_reader']) {
        ob_start();
        require SB.'admin/'.$sysconf['admin_template']['dir'].'/barcodescannermodal.tpl.php';
        $barcode = ob_get_clean();
        echo $barcode;
        echo '<script>parent.$(".modal-backdrop").remove(); </script>';
    } 
?>
    <div class="menuBox">
    <div class="menuBoxInner stockTakeIcon">
      <div class="per_title">
        <h2><?php
        if ($view != 'm') {
          echo __('Stock Take Process');
        } else {
          echo __('Current Missing/Lost Items');
        }
        ?>
        </h2>
      </div>

      <!-- Header Unit Info / Superadmin Selector -->
      <div class="sub_section pb-0">
        <?php if ($is_super_admin): ?>
            <form method="get" action="<?php echo MWB; ?>stock_take/current.php" class="form-inline mb-2">
                <label class="mr-2 font-weight-bold"><?php echo __('Unit Perpustakaan'); ?>:</label>
                <select name="library_id" class="form-control col-md-3 mr-2" onchange="this.form.submit()">
                    <?php
                    $libs = $dbs->query("SELECT library_id, library_name FROM mst_library ORDER BY library_name");
                    while ($lib = $libs->fetch_assoc()) {
                        $selected = ($active_lib_id == $lib['library_id']) ? 'selected' : '';
                        echo '<option value="' . $lib['library_id'] . '" ' . $selected . '>' . htmlspecialchars($lib['library_name']) . '</option>';
                    }
                    ?>
                </select>
                <input type="hidden" name="view" value="<?php echo htmlspecialchars($view); ?>">
            </form>
        <?php else: ?>
            <?php
            $user_lib_name = 'Perpustakaan Unit';
            $lib_info = $dbs->query("SELECT library_name FROM mst_library WHERE library_id = " . intval($active_lib_id));
            if ($lib_info && $lib_d = $lib_info->fetch_assoc()) {
                $user_lib_name = $lib_d['library_name'];
            }
            ?>
            <span class="badge badge-info p-2 mb-2" style="font-size: 0.9rem;">Unit: <?= htmlspecialchars($user_lib_name) ?></span>
        <?php endif; ?>
      </div>

      <div class="infoBox">
      <?php if ($view != 'm') { ?>
      <form action="<?php echo MWB ?>stock_take/stock_take_action.php" method="post" target="stockTakeAction" name="stockTakeForm" class="notAJAX" >
          <input type="hidden" name="library_id" value="<?php echo htmlspecialchars($active_lib_id); ?>" />
          <div class="form-group">
              <label><?php echo __('Item Code') ?></label>
              <div class="form-row">
                  <input type="text" id="itemCode" name="itemCode" size="30" class="form-control col-2" autofocus />
                  <input type="submit" value="<?php echo __('Change Status') ?>" class="btn btn-primary" id="checkItem" />
                  <?php if($sysconf['barcode_reader']) : ?>
                  &nbsp;<a class="s-btn btn btn-default notAJAX" id="barcodeReader" href="<?php echo MWB.'circulation/barcode_reader.php?mode=stockopname' ?>">Open Barcode Reader - Experimental (F8)</a>
                  <?php endif ?>
              </div>
          </div>
          <div class="form-row">
              <label><?php echo __('List stocktakes by') ?></label>
              <div class="form-check mr-2">
                  <input type="radio" id="listShow" name="listShow" value="1" onclick="$('#mainContent').simbioAJAX('<?php echo MWB ?>stock_take/current.php?library_id=<?php echo $active_lib_id; ?>&listShow=1')" <?php echo ( isset($show_only_current)?'checked="checked"':'' ) ?> />
                  <label for="listShow"><?php echo __('Current User Only') ?></label>
              </div>
              <div class="form-check">
                  <input type="radio" id="listShow2" name="listShow" value="0" onclick="$('#mainContent').simbioAJAX('<?php echo MWB ?>stock_take/current.php?library_id=<?php echo $active_lib_id; ?>&listShow=0')" <?php echo ( isset($show_only_current)?'':'checked="checked"' ) ?> />
                  <label for="listShow2"><?php echo __('All User') ?></label>
              </div>
          </div>
          <iframe name="stockTakeAction" style="display: none; width: 0; height: 0; visibility: hidden;"></iframe>
          <?php if($sysconf['barcode_reader']) : ?>
          <script type="text/javascript">
              $('#barcodeReader').click(function(e){
                  e.preventDefault();
                  var url = $(this).attr('href');
                  parent.$('#iframeBarcodeReader').attr('src', url);
                  parent.$('#barcodeModal').modal('show');
              });
          </script>
          <?php endif ?>
      </form>
      <?php } ?>
      </div>

      <div class="sub_section">
        <form name="search" id="search" action="<?php echo MWB; ?>stock_take/current.php" method="get" class="form-inline">
          <div class="form-group">
            <label class="mr-2"><?php echo __('Search'); ?> </label>
            <input type="text" name="keywords" class="form-control mr-2" value="<?php echo isset($_GET['keywords']) ? htmlspecialchars($_GET['keywords']) : ''; ?>" />
            <input type="hidden" name="view" value="<?php echo $view; ?>" />
            <input type="hidden" name="library_id" value="<?php echo $active_lib_id; ?>" />
            <input type="submit" id="doSearch" value="<?php echo __('Search'); ?>" class="btn btn-default" />
          </div>
        </form>
      </div>
    </div>

    <!-- give focus to itemCode text field -->
    <script type="text/javascript">
    $('#itemCode').focus();
    </script>
    <div id="stError" class="errorBox" style="display: none;">&nbsp;</div>
<?php
    /* CURRENT STOCK TAKE ITEM LIST */
    $table_spec = 'stock_take_item AS sti';

    // Create Datagrid
    $datagrid = new simbio_datagrid();
    $datagrid->setSQLColumn('sti.item_code AS \''.__('Item Code').'\'',
        'sti.title AS \''.__('Title').'\'',
        'sti.call_number AS \''.__('Call Number').'\'',
        'sti.coll_type_name AS \''.__('Collection Type').'\'',
        'sti.classification AS \''.__('Classification').'\'',
        'IF(sti.status=\'e\', \''.__('Exists').'\', IF(sti.status=\'l\', \''.__('On Loan').'\', \''.__('Missing').'\')) AS \'Status\'');
    $datagrid->setSQLorder("sti.last_update DESC");

    // ISOLASI DATA BERDASARKAN UNIT PERPUSTAKAAN YANG AKTIF
    $criteria = "sti.item_id <> 0 AND sti.library_id = " . intval($active_lib_id) . " ";

    // Filter Pencarian Keywords
    if (isset($_GET['keywords']) AND $_GET['keywords']) {
        $keyword = $dbs->escape_string(trim($_GET['keywords']));
        $words = explode(' ', $keyword);
        if (count($words) > 1) {
            $concat_sql = ' (';
            foreach ($words as $word) {
                $concat_sql .= " (sti.title LIKE '%$word%' OR sti.item_code LIKE '%$word%') AND";
            }
            $concat_sql = substr_replace($concat_sql, '', -3);
            $concat_sql .= ') ';
            $criteria .= ' AND '.$concat_sql." AND sti.status='".$view."'";
        } else {
            $criteria .= " AND (sti.title LIKE '%$keyword%' OR sti.item_code LIKE '%$keyword%') AND sti.status='".$view."'";
        }
    } else {
        $criteria .= " AND sti.status='".$view."'";
    }

    if (isset($show_only_current)) {
        $criteria .= ' AND sti.checked_by=\''.$dbs->escape_string($_SESSION['realname']).'\'';
    }

    // Set criteria
    $datagrid->setSQLCriteria($criteria);

    // Set table and table header attributes
    $datagrid->table_attr = 'id="dataList" class="s-table table"';
    $datagrid->table_header_attr = 'class="dataListHeader" style="font-weight: bold;"';
    $datagrid->delete_URL = $_SERVER['PHP_SELF'];
    $datagrid->column_width = array('10%', '60%', '10%', '10%', '10%');
    $datagrid->disableSort('Current Status');

    // Result Output
    $datagrid_result = $datagrid->createDataGrid($dbs, $table_spec, 20, false);
    if (isset($_GET['keywords']) AND $_GET['keywords']) {
        $msg = str_replace('{result->num_rows}', $datagrid->num_rows, __('Found <strong>{result->num_rows}</strong> from your keywords'));
        echo '<div class="infoBox">'.$msg.' : "'.htmlspecialchars($_GET['keywords']).'"</div>';
    }

    echo $datagrid_result;
}