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

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

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

$is_super_admin = (empty($user_lib_id) || $user_lib_id == 1 || $user_lib_id == 0);

// Tentukan Target library_id (utamakan via POST jika dikirim oleh form)
$target_lib_id = isset($_POST['library_id']) && !empty($_POST['library_id']) ? intval($_POST['library_id']) : ($user_lib_id ?: 1);

// Jika bukan Superadmin, KUNCI PERPUSTAKAAN sesuai unitnya
if (!$is_super_admin) {
    $target_lib_id = intval($user_lib_id);
}

// Transaction process
if (isset($_POST['itemCode'])) {
    echo '<!DOCTYPE html>';
    echo '<html><body>';
    
    // Filter input item_code
    $item_code = utility::filterData('itemCode', 'post', true, true, true);
    if (!$item_code) {
        echo '<script type="text/javascript">'."\n";
        echo 'parent.$(\'#stError\').html(\''.__('Please enter a valid item code/barcode. You enter a BLANK code!').'\')';
        echo '.css( {\'display\': \'block\'} );'."\n";
        echo 'parent.$(\'#itemCode\').val(\'\').focus();'."\n";
        echo '</script>';
        echo '</body></html>';
        exit();
    }

    // Cek ketersediaan eksemplar dalam tabel stock_take_item DENGAN FILTER library_id
    $item_check = $dbs->query("SELECT * FROM stock_take_item WHERE item_code='$item_code' AND library_id = " . intval($target_lib_id));
    $item_check_d = $item_check->fetch_assoc();

    if ($item_check->num_rows > 0) {
        if ($item_check_d['status'] == 'l') {
            // Record to log: Eksemplar Sedang Dipinjam
            writeLog('staff', $_SESSION['uid'], 'stock_take', 'Stock Take ERROR : '.sprintf(__('Item %s (%s) is currently ON LOAN'), $item_check_d['title'], $item_check_d['item_code']), 'Error', 'On Loan');
            echo '<script type="text/javascript">'."\n";
            echo 'parent.$(\'#stError\').html(\''.sprintf(__('Item %s is currently ON LOAN'), $item_code).'\')';
            echo '.css( {\'display\': \'block\'} );'."\n";
            echo 'parent.$(\'#itemCode\').val(\'\').focus();'."\n";
            echo '</script>';
        } else if ($item_check_d['status'] == 'e') {
            // Record to log: Sudah Pernah Di-scan
            echo '<script type="text/javascript">'."\n";
            echo 'parent.$(\'#stError\').html(\''.sprintf(__('Item %s is already SCANNED!'), $item_code).'\')';
            echo '.css( {\'display\': \'block\'} );'."\n";
            echo 'parent.$(\'#itemCode\').val(\'\').focus();'."\n";
            echo '</script>';
        } else {
            // UPDATE STATUS EKSEMPLAR MENJADI EXISTS ('e')
            $listShow = 0;
            if (isset($_POST['listShow']) && $_POST['listShow'] == '1') {
                $listShow = 1;
            }

            $curr_time = date('Y-m-d H:i:s');
            
            // 1. Update status item spesifik berdasarkan item_code dan library_id
            $update = $dbs->query("UPDATE stock_take_item SET status='e', checked_by='".$dbs->escape_string($_SESSION['realname'])."', last_update='".$curr_time."' WHERE item_code='$item_code' AND library_id = " . intval($target_lib_id));
            
            // 2. Update jumlah rekapitulasi HANYA PADA OPNAME AKTIF UNIT TERSEBUT
            $update = $dbs->query("UPDATE stock_take SET total_item_lost=total_item_lost-1, total_item_exists=total_item_exists+1 WHERE is_active=1 AND library_id = " . intval($target_lib_id));

            // 3. Update daftar partisipan opname unit tersebut
            $user = array();
            $user[$_SESSION['realname']] = $_SESSION['realname'];
            $stock_take_users = serialize($user);
            
            $_q = $dbs->query("SELECT stock_take_users FROM stock_take WHERE is_active=1 AND library_id = " . intval($target_lib_id));
            if ($_q && $_q->num_rows > 0) {
                $_d = $_q->fetch_row()[0];
                if ($_d == NULL) {
                    $dbs->query("UPDATE stock_take SET stock_take_users='".$dbs->escape_string($stock_take_users)."' WHERE is_active=1 AND library_id = " . intval($target_lib_id));
                } else {
                    $user = unserialize($_d);
                    $user[$_SESSION['realname']] = $_SESSION['realname'];
                    $stock_take_users = serialize($user);
                    $dbs->query("UPDATE stock_take SET stock_take_users='".$dbs->escape_string($stock_take_users)."' WHERE is_active=1 AND library_id = " . intval($target_lib_id));
                }
            }

            // Reload tampilan di halaman induk
            echo '<script type="text/javascript">'."\n";
            echo 'parent.$(\'#mainContent\').simbioAJAX(\''.MWB.'stock_take/current.php?library_id='.$target_lib_id.'&listShow='.$listShow.'\');'."\n";
            echo '</script>';
        }
    } else {
        // Cek jika eksemplar dikecualikan dari stock take
        $status_q = $dbs->query(sprintf("SELECT item.item_code FROM item 
                     LEFT JOIN mst_item_status ON item.item_status_id=mst_item_status.item_status_id
                     WHERE item.item_code = '%s' AND item.library_id = %d AND mst_item_status.skip_stock_take=1", $item_code, $target_lib_id));
        
        if ($status_q && $status_q->num_rows > 0) {
            $message = 'Stock Take ERROR : '.sprintf(__('Item Code (%s) have rule to skipped by stock take'), $item_code);
            $alert   = sprintf(__('Item Code %s have rule to skipped by stock take'), $item_code);
        } else {
            $message = 'Stock Take ERROR : '.sprintf(__('Item Code (%s) doesnt exists in stock take data for this library. Invalid Item Code OR Maybe out of Stock Take range'), $item_code);
            $alert   = sprintf(__('Item Code %s doesnt exists in stock take data for this library.\\nInvalid Item Code OR Maybe out of Stock Take range'), $item_code);
        }

        // Record log kesalahan
        writeLog('staff', $_SESSION['uid'], 'stock_take', $message, 'Error', 'No Item');
        echo '<script type="text/javascript">'."\n";
        echo 'parent.$(\'#stError\').html(\''.$alert.'\')';
        echo '.css( {\'display\': \'block\'} );'."\n";
        echo 'parent.$(\'#itemCode\').val(\'\').focus();'."\n";
        echo '</script>';
    }
    echo '</body></html>';
}