<?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
 *
 */

/* Stock Take Upload */

// 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';

// 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);

// Tentukan Target library_id (bisa dari POST atau unit pengguna)
$target_lib_id = isset($_POST['library_id']) && $_POST['library_id'] !== '' ? intval($_POST['library_id']) : ($user_lib_id ?: 1);

if (!$is_super_admin) {
    $target_lib_id = intval($user_lib_id);
}

// Cek apakah ada proses Stock Take yang AKTIF untuk unit perpustakaan target
$stk_sql = "SELECT * FROM stock_take WHERE is_active=1 AND library_id = " . intval($target_lib_id);
$stk_query = $dbs->query($stk_sql);

if ($stk_query->num_rows < 1) {
    echo '<div class="errorBox">'.__('NO active stock taking proccess initialized for this library unit!').'</div>';
    
    if ($is_super_admin) {
        echo '<div class="sub_section p-3"><form method="get" action="'.MWB.'stock_take/st_upload.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>';
    }
    die();
}

// File upload process
if (isset($_POST['stUpload']) && isset($_FILES['stFile'])) {
    require SIMBIO.'simbio_FILE/simbio_file_upload.inc.php';
    
    // create upload object
    $upload = new simbio_file_upload();
    $upload->setAllowableFormat(array('.txt'));
    $upload->setAllowableMimeTypes(array(
      'text/plain',
      'application/octet-stream'
    ));
    $upload->setMaxSize($sysconf['max_upload']*1024);
    $upload->setUploadDir(UPLOAD);
    
    // upload the file
    $upload_status = $upload->doUpload('stFile');
    if ($upload_status == UPLOAD_SUCCESS) {
        // write log
        writeLog('staff', $_SESSION['uid'], 'stock_take', $_SESSION['realname'].' upload stock take file '.$upload->new_filename.' (Library ID: '.$target_lib_id.')', 'Upload data', 'OK');
        
        // open file
        $stfile = @fopen(UPLOAD.$upload->new_filename, 'r');
        if (!$stfile) {
            echo '<script type="text/javascript">'."\n";
            echo 'parent.$(\'#stUploadMsg\').html(\'Failed to open stock take file '.$upload->new_filename.'. Please check permission for directory '.UPLOAD.'\')';
            echo '.toggleClass(\'errorBox\').css( {\'display\': \'block\'} );'."\n";
            echo '</script>';
            exit();
        }
        
        // start loop
        $i = 0;
        while (!feof($stfile)) {
            $curr_time = date('Y-m-d H:i:s');
            $item_code = fgets($stfile, 80);
            
            // strip any html tags
            $item_code = strip_tags(trim($item_code));
            if (!$item_code) {
                continue;
            }
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $item_code)) {
                continue;
            }

            // check item status ISOLATED BY library_id
            $item_code_escaped = $dbs->real_escape_string($item_code);
            $item_check = $dbs->query(sprintf("SELECT * FROM stock_take_item WHERE item_code='%s' AND library_id = %d", $item_code_escaped, $target_lib_id));
            $item_check_d = $item_check->fetch_assoc();
            
            if ($item_check && $item_check->num_rows > 0) {
                if ($item_check_d['status'] == 'l') {
                    // record to log
                    writeLog('staff', $_SESSION['uid'], 'stock_take', 'Stock Take ERROR : Item '.$item_check_d['title'].' ('.$item_check_d['item_code'].') is currently ON LOAN (from uploaded file '.$upload->new_filename.')', 'Item', 'Error');
                    continue;
                } else if ($item_check_d['status'] == 'e') {
                    continue;
                } else {
                    // UPDATE ISOLATED BY library_id
                    $update = @$dbs->query("UPDATE LOW_PRIORITY stock_take_item SET status='e', checked_by='".$dbs->escape_string($_SESSION['realname'])."', last_update='".$curr_time."' WHERE item_code='$item_code_escaped' AND library_id = $target_lib_id");
                    $update = @$dbs->query("UPDATE LOW_PRIORITY stock_take SET total_item_lost=total_item_lost-1, total_item_exists=total_item_exists+1 WHERE is_active=1 AND library_id = $target_lib_id");
                    $i++;
                }
            } else {
                // record to log
                writeLog('staff', $_SESSION['uid'], 'stock_take', 'Stock Take ERROR : Item Code '.$item_code.' doesnt exists in stock take data for library ID '.$target_lib_id.'. Invalid Item Code OR Maybe out of Stock Take range (from uploaded file '.$upload->new_filename.')');
            }
        }
        fclose($stfile);
        
        // message
        echo '<script type="text/javascript">'."\n";
        echo 'parent.$(\'#stUploadMsg\').html(\''.__('Succesfully upload stock take file ').$upload->new_filename.', <b>'.$i.'</b>'.__(' item codes scanned!').'\')';
        echo '.css( {\'display\': \'block\'} );'."\n";
        echo '</script>';
    } else {
        // write log
        writeLog('staff', $_SESSION['uid'], 'stock_take', 'ERROR : '.$_SESSION['realname'].' FAILED TO upload stock take file '.$upload->new_filename.', with error ('.$upload->error.')', 'Upload data', 'Fail');
        echo '<script type="text/javascript">'."\n";
        echo 'parent.$(\'#stUploadMsg\').html(\'Failed to upload stock take file! <div>Error : '.$upload->error.'</div>\')';
        echo '.toggleClass(\'errorBox\').css( {\'display\': \'block\'} );'."\n";
        echo '</script>';
    }
    exit();
}

?>
<div class="menuBox">
<div class="menuBoxInner stockTakeIcon">
  <div class="per_title">
    <h2><?php echo __('Stock Take Upload'); ?></h2>
  </div>

  <!-- Section Pilihan Unit / Badge Unit -->
  <div class="sub_section pb-0">
    <?php if ($is_super_admin): ?>
        <form method="get" action="<?php echo MWB; ?>stock_take/st_upload.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 = ($target_lib_id == $lib['library_id']) ? 'selected' : '';
                    echo '<option value="' . $lib['library_id'] . '" ' . $selected . '>' . htmlspecialchars($lib['library_name']) . '</option>';
                }
                ?>
            </select>
        </form>
    <?php else: ?>
        <?php
        $user_lib_name = 'Perpustakaan Unit';
        $lib_info = $dbs->query("SELECT library_name FROM mst_library WHERE library_id = " . intval($target_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 echo __('Upload a plain text file (.txt) containing list of Item Code to stock take. Each Item Code separated by line.'); ?></div>
  <div class="sub_section">
    <form name="uploadForm" class="notAJAX" method="post" enctype="multipart/form-data" action="<?php echo MWB.'stock_take/st_upload.php'; ?>" target="uploadAction" class="form-inline">
    <input type="hidden" name="library_id" value="<?= htmlspecialchars($target_lib_id) ?>">
    <div class="container-fluid">
        <div class="row">
            <div class="custom-file col-6">
                <input type="file" name="stFile" id="stFile" value="" class="custom-file-input" accept=".txt,text/plain">
                <label class="custom-file-label" for="customFile"><?= __('Choose file')?></label>
            </div>
            <div class="col"><div class="mt-2"><?= __(sprintf('Maximum %s KB',$sysconf['max_upload']))?></div></div>
        </div>
    </div>
    <div style="margin: 3px;" class="mt-3">
        <input type="submit" name="stUpload" id="stUpload" value="<?php echo __('Upload File'); ?>" class="btn btn-primary" />
        <iframe name="uploadAction" style="width: 0; height: 0; visibility: hidden;"></iframe>
    </div>
    </form>
  </div>
</div>
</div>
<div id="stUploadMsg" class="infoBox" style="display: none;">&nbsp;</div>