<?php
/**
 * Copyright (C) 2009  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
 *
 */

/* Stock Take Initialization */

use SLiMS\DB;

// key to authenticate
define('INDEX_AUTH', '1');
// key to get full database access
define('DB_ACCESS', 'fa');

// 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_DB/simbio_dbop.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);

?>
    <div class="menuBox">
        <div class="menuBoxInner printIcon">
            <div class="per_title">
                <h2><?php echo __('Initialize Stock Take Process'); ?></h2>
            </div>
        </div>
    </div>
<?php
$q_item = $dbs->query("SELECT last_update FROM item ORDER BY last_update DESC LIMIT 1");

if ($q_item->num_rows < 1) {
  die('
  <div class="errorBox">
    <strong>' . __('No item available. Stock take process is need item data') . '</strong>
  </div>
  ');
}

$d_item = $q_item->fetch_row();
$q_backup = $dbs->query("SELECT backup_log_id FROM backup_log WHERE backup_time >= '{$d_item[0]}'");
if ((DB::hasBackup(by: DB::BACKUP_BASED_ON_LAST_ITEM) === false) && !isset($_GET['skip_backup']) && !isset($_POST['saveData'])) {
  $_SESSION['token'] = utility::createRandomString(32);
  ?>
    <div class="container-fluid">
        <hr>
        <p class="lead"><?= __('Before stock taking, it is recommended to backup your database first.') ?>
           <br/><?= __('Looks like you have not backed up before.'); ?></p>
        <a href="<?= MWB.'system/backup_proc.php'; ?>" id="backupproc" class="notAJAX btn btn-primary"><?= __('Backup Now') ?></a>
        <a href="<?= MWB.'stock_take/init.php?skip_backup=1' ?>" class="btn btn-link" title="<?= __('Skip backup at your own risk!'); ?>"><?= __('Skip'); ?></a>
    </div>
    <script>
      $(document).ready(function(){
        $('#backupproc').click(function(e) {
          e.preventDefault()
          
          let currentLabel = $(this).html()

          $(this).removeClass('btn-primary').addClass('btn-secondary')
          $(this).html('<?= __('Please wait') ?>')

          $.post($(this).attr('href'), {start:true,tkn:'<?= $_SESSION['token'] ?>',verbose:'no',response:'json'}, function(result, status, post){
            var result = JSON.parse(result)
            if (result.status)  {
              $('#mainContent').simbioAJAX('<?= $_SERVER['PHP_SELF'] ?>')
            } else {
              $(this).html(currentLabel)
              console.error(result.message)
              window.toastr.error(result.message, '<?= __('Error') ?>')
            }
          });
        })
      })
    </script>
  <?php
  exit();
}

// Tentukan Target library_id untuk Stock Take ini
$target_lib_id = $user_lib_id ?: 1;
if ($is_super_admin && isset($_POST['library_id']) && $_POST['library_id'] !== '') {
    $target_lib_id = intval($_POST['library_id']);
}

// Cek apakah ADA Stock Take aktif untuk perpustakaan/unit INI
$stk_check_sql = "SELECT * FROM stock_take WHERE is_active=1";
if (!$is_super_admin || (isset($_POST['library_id']) && $_POST['library_id'] !== '')) {
    $stk_check_sql .= " AND library_id = " . intval($target_lib_id);
}
$stk_q = $dbs->query($stk_check_sql);

if ($stk_q->num_rows) {
  echo '<div class="errorBox">' . __('There is already stock taking proccess running for this unit!') . '</div>';
} else {
  // Simpan Inisialisasi Stock Take Baru
  if (isset($_POST['saveData']) AND empty($_POST['name'])) {
    utility::jsAlert(__('Stock Take Name must be filled!'));
    exit();
  } else if (isset($_POST['saveData']) AND !empty($_POST['name'])) {
    
    $data['stock_take_name'] = trim($dbs->escape_string(strip_tags($_POST['name'])));
    $data['start_date']      = date('Y-m-d H:i:s');
    $data['init_user']       = $_SESSION['realname'];
    $data['is_active']       = 1;
    $data['library_id']      = $target_lib_id; // Set library_id unit

    $sql_op = new simbio_dbop($dbs);
    if ($sql_op->insert('stock_take', $data)) {
      // Dapatkan stock_take_id terbaru
      $stock_take_id = $sql_op->insert_id;

      // Filter Item berdasarkan kriteria dan library_id
      $criteria = ' WHERE (ist.skip_stock_take<1 OR ist.skip_stock_take IS NULL) ';
      
      // ISOLASI UNIT: Tambahkan kriteria library_id dari tabel item
      $criteria .= ' AND i.library_id = ' . intval($target_lib_id) . ' ';

      // Filter GMD
      if ($_POST['gmdID'] != '0') {
        $criteria .= ' AND b.gmd_id=' . intval($_POST['gmdID']) . ' ';
      }
      // Filter Jenis Koleksi
      if ($_POST['collTypeID'] != '0') {
        $criteria .= ' AND i.coll_type_id=\'' . intval($_POST['collTypeID']) . '\' ';
      }
      // Filter Lokasi
      if ($_POST['location'] != '0') {
        $criteria .= ' AND i.location_id=\'' . $dbs->escape_string($_POST['location']) . '\' ';
      }
      // Filter Rak/Placement
      if (!empty($_POST['itemSite'])) {
        $criteria .= ' AND i.site LIKE \'' . $dbs->escape_string($_POST['itemSite']) . '\' ';
      }
      // Filter Klasifikasi
      if (!empty($_POST['classification'])) {
        $criteria .= ' AND (';
        $arr_class = explode(',', $_POST['classification']);
        $class_criteria = '';
        foreach ($arr_class as $each_class) {
          if (strpos($each_class, '*') !== false) {
            $each_class = str_replace('*', '%', $dbs->escape_string($each_class));
            $class_criteria .= ' b.classification LIKE \'' . $each_class . '\' OR ';
          } else {
            $each_class = $dbs->escape_string($each_class);
            $class_criteria .= ' b.classification=\'' . $each_class . '\' OR ';
          }
        }
        $class_criteria = substr_replace($class_criteria, '', -3);
        $criteria .= $class_criteria . ' )';
      }

      // BERSIHKAN DATA STOCK TAKE ITEM HANYA UNTUK UNIT INI (JANGAN TRUNCATE AGAR TIDAK MENGHAPUS UNIT LAIN)
      $dbs->query("DELETE FROM stock_take_item WHERE library_id = " . intval($target_lib_id));

      // Salin item ke tabel stock_take_item
      $insert_sql = "INSERT INTO stock_take_item 
            (stock_take_id, item_id, item_code, title, gmd_name, classification, coll_type_name, call_number, location, status, checked_by, last_update, library_id)
            SELECT $stock_take_id, i.item_id, i.item_code, b.title, g.gmd_name, b.classification, ct.coll_type_name, i.call_number, loc.location_name, 'm', NULL, NULL, " . intval($target_lib_id) . " 
            FROM item AS i
            LEFT JOIN mst_item_status AS ist ON i.item_status_id=ist.item_status_id
            LEFT JOIN mst_coll_type AS ct ON i.coll_type_id=ct.coll_type_id
            LEFT JOIN mst_location AS loc ON i.location_id=loc.location_id
            LEFT JOIN biblio AS b ON i.biblio_id=b.biblio_id
            LEFT JOIN mst_gmd AS g ON b.gmd_id=g.gmd_id
            $criteria";
      
      $dbs->query($insert_sql);

      // Hitung item yang sedang dipinjam (loan) untuk unit ini
      $item_loan_q = $dbs->query("SELECT COUNT(l.loan_id) FROM loan AS l 
                                  LEFT JOIN item AS i ON l.item_code = i.item_code 
                                  WHERE l.is_lent=1 AND l.is_return=0 AND i.library_id = " . intval($target_lib_id));
      $item_loan_d = $item_loan_q->fetch_row();
      $total_loan  = $item_loan_d[0] ?? 0;

      // Update status item yang sedang dipinjam
      $dbs->query("UPDATE stock_take_item SET status='l' 
                   WHERE library_id = " . intval($target_lib_id) . " 
                   AND item_code IN (SELECT item_code FROM loan WHERE is_lent=1 AND is_return=0)");

      // Total baris item yang harus disetujui (status missing/m)
      $total_rows_q = $dbs->query("SELECT COUNT(item_code) FROM stock_take_item WHERE stock_take_id = $stock_take_id AND status='m'");
      $total_rows_d = $total_rows_q->fetch_row();
      $total_missing = $total_rows_d[0] ?? 0;

      if ($total_missing > 0 || $total_loan > 0) {
        // Update statistik awal di tabel stock_take
        $dbs->query("UPDATE stock_take SET 
                      total_item_stock_taked = $total_missing, 
                      total_item_loan = $total_loan, 
                      total_item_lost = $total_missing 
                     WHERE stock_take_id = $stock_take_id");
        
        // Catat log
        writeLog('staff', $_SESSION['uid'], 'stock_take', $_SESSION['realname'] . ' initialize stock take (' . $data['stock_take_name'] . ') for lib_id ' . $target_lib_id, 'Initialize', 'OK');
        utility::jsAlert(__('Stock Taking Initialized'));
        echo '<script type="text/javascript">parent.location.href = \'' . SWB . 'admin/index.php?mod=stock_take\';</script>';
      } else {
        // Batalkan stock take jika tidak ada item ditemukan
        $dbs->query('DELETE FROM stock_take WHERE stock_take_id=' . $stock_take_id);
        utility::jsAlert(__('Stock Taking FAILED to Initialized.\nNo item found for this unit!'));
      }
      exit();
    }
  }

  // BENTUK FORM INISIALISASI
  $form = new simbio_form_table_AJAX('mainForm', $_SERVER['PHP_SELF'] . '?action=new', 'post');
  $form->submit_button_attr = 'name="saveData" value="' . __('Initialize Stock Take') . '" class="btn btn-default"';

  $form->table_attr = 'id="dataList" class="s-table table"';
  $form->table_header_attr = 'class="alterCell font-weight-bold"';
  $form->table_content_attr = 'class="alterCell2"';

  /* Elements Form */
  
  // 1. Dropdown / Badge Library ID
  if ($is_super_admin) {
      $lib_options = [];
      $libs = $dbs->query("SELECT library_id, library_name FROM mst_library ORDER BY library_name");
      while ($lib = $libs->fetch_assoc()) {
          $lib_options[] = [$lib['library_id'], $lib['library_name']];
      }
      $form->addSelectList('library_id', __('Perpustakaan') . '*', $lib_options, 1, 'class="form-control col-4"');
  } else {
      $user_lib_name = 'Perpustakaan Unit';
      $lib_info = $dbs->query("SELECT library_name FROM mst_library WHERE library_id = " . intval($user_lib_id));
      if ($lib_info && $lib_d = $lib_info->fetch_assoc()) {
          $user_lib_name = $lib_d['library_name'];
      }
      $str_lib = '<input type="hidden" name="library_id" value="' . htmlspecialchars($user_lib_id) . '">';
      $str_lib .= '<span class="badge badge-info p-2" style="font-size: 0.95rem;">' . htmlspecialchars($user_lib_name) . '</span>';
      $form->addAnything(__('Perpustakaan'), $str_lib);
  }

  // 2. Stock Take Name
  $form->addTextField('text', 'name', __('Stock Take Name') . '*', '', 'style="width: 60%;" class="form-control"');
  
  // 3. GMD
  $gmd_q = $dbs->query('SELECT gmd_id, gmd_name FROM mst_gmd');
  $gmd_options[] = array('0', __('ALL'));
  while ($gmd_d = $gmd_q->fetch_row()) {
    $gmd_options[] = array($gmd_d[0], $gmd_d[1]);
  }
  $form->addSelectList('gmdID', __('GMD'), $gmd_options, '', 'class="form-control col-3"');
  
  // 4. Collection Type
  $coll_type_q = $dbs->query('SELECT coll_type_id, coll_type_name FROM mst_coll_type');
  $coll_type_options[] = array('0', __('ALL'));
  while ($coll_type_d = $coll_type_q->fetch_row()) {
    $coll_type_options[] = array($coll_type_d[0], $coll_type_d[1]);
  }
  $form->addSelectList('collTypeID', __('Collection Type'), $coll_type_options, '', 'class="form-control col-3"');
  
  // 5. Location
  $location_q = $dbs->query("SELECT location_id, location_name FROM mst_location");
  $location_options[] = array('0', __('ALL'));
  while ($location_d = $location_q->fetch_row()) {
    $location_options[] = array($location_d[0], $location_d[1]);
  }
  $form->addSelectList('location', __('Location'), $location_options, '', 'class="form-control col-3"');
  
  // 6. Item Site / Shelf
  $form->addTextField('text', 'itemSite', __('Shelf Location'), '', 'style="width: 20%;" class="form-control"');
  
  // 7. Classification
  $str_input = simbio_form_element::textField('text', 'classification', '', 'style="width: 60%;" class="form-control"');
  $str_input .= '<small class="text-muted font-weight-bold d-block mt-1">' . __('Separate each class comma sign. Use * for wildcard') . '</small>';
  $form->addAnything(__('Classification'), $str_input);

  // Cetak Form
  echo $form->printOut();
}