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

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

// Tentukan Target library_id
$target_lib_id = isset($_REQUEST['library_id']) && $_REQUEST['library_id'] !== '' ? intval($_REQUEST['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 running for this library unit!').'</div>';
    
    if ($is_super_admin) {
        echo '<div class="sub_section p-3"><form method="get" action="'.$_SERVER['PHP_SELF'].'" 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();
}

if (isset($_POST['confirmFinish'])) {
    set_time_limit(0);
    
    // Ambil data opname aktif yang terisolasi berdasarkan library_id
    $stk_take_q = $dbs->query("SELECT stock_take_name, stock_take_id FROM stock_take WHERE is_active=1 AND library_id = " . intval($target_lib_id));
    $stk_take_d = $stk_take_q->fetch_row();
    
    // Update tanggal selesai opname
    $finish_time_q = $dbs->query("UPDATE stock_take SET end_date=NOW() WHERE is_active=1 AND library_id = " . intval($target_lib_id));
    $stk_take_report_filename = strtolower(str_replace(' ', '_', trim($stk_take_d[0]))).'_lib'.$target_lib_id.'_report.html';
    
    if ($dbs->affected_rows >= 0) {
        // Hapus eksemplar jika opsi 'purge' dipilih (ISOLATED BY library_id)
        if (isset($_POST['purge']) AND !empty($_POST['purge'])) {
            // Hapus data item
            $purge_item_q = $dbs->query("DELETE FROM item WHERE item_id IN (SELECT item_id FROM stock_take_item WHERE status='m' AND library_id = $target_lib_id)");
            
            // Hapus riwayat pinjam
            $purge_loan_history_q = $dbs->query("DELETE FROM loan_history WHERE loan_id IN (SELECT loan_id FROM loan WHERE item_code IN (SELECT item_code FROM stock_take_item WHERE status='m' AND library_id = $target_lib_id))");
            
            // Hapus peminjaman aktif
            $purge_loan_q = $dbs->query("DELETE FROM loan WHERE item_code IN (SELECT item_code FROM stock_take_item WHERE status='m' AND library_id = $target_lib_id)");
        }
        
        // Ubah status eksemplar hilang menjadi 'MIS' (ISOLATED BY library_id)
        $update_item_status_to_missing = $dbs->query("UPDATE item SET item_status_id='MIS' WHERE item_code IN (SELECT item_code FROM stock_take_item WHERE status='m' AND library_id = $target_lib_id)");
        
        // Tangkap output laporan akhir
        ob_start();
        echo '<html><head><title>'.$stk_take_d[0].' ' . __('Stock Take Report') . '</title>';
        echo '<meta http-equiv="Pragma" content="No-Cache">'."\n";
        echo '<meta http-equiv="Cache-Control" content="No-Cache">'."\n";
        echo '<style type="text/css">'."\n";
        echo 'body {padding: 0.2cm}'."\n";
        echo 'body * {color: black; font-size: 11pt;}'."\n";
        echo 'table {border: 1px solid #000000;}'."\n";
        echo '.dataListHeader {background-color: #000000; color: white; font-weight: bold;}'."\n";
        echo '.alterCell {border-bottom: 1px solid #666; background-color: #CCCCCC;}'."\n";
        echo '.alterCell2 {border-bottom: 1px solid #666; background-color: #FFFFFF;}'."\n";
        echo '</style>'."\n";
        echo '</head>';
        echo '<body>'."\n";
        
        define('REPECT_INCLUDE', true);
        $_GET['library_id'] = $target_lib_id; // Set GET context untuk st_report.php
        echo '<h3>'.$stk_take_d[0].' - ' . __('Stock Take Report') . '</h3><hr />';
        include MDLBS.'stock_take/st_report.php';

        // Tampilkan daftar item hilang (ISOLATED BY library_id)
        $cellClass = 'alterCell';
        $lost_item_q = $dbs->query("SELECT item_code, title, classification, coll_type_name, call_number FROM stock_take_item WHERE status='m' AND library_id = $target_lib_id");
        if ($lost_item_q->num_rows > 0) {
            echo '<br />';
            echo '<h3>' . __('LOST Item list') . '</h3><hr size="1" />';
            echo '<table style="width: 100%; border: 1px solid #666;" cellspacing="0">';
            echo '<tr>';
            echo '<th class="dataListHeader">' . __('Item Code') . '</th>
                <th class="dataListHeader">' . __('Title') . '</th>
                <th class="dataListHeader">' . __('Classification') . '</th>';
            echo '</tr>'."\n";
            while ($lost_item_d = $lost_item_q->fetch_row()) {
                $cellClass = ($cellClass == 'alterCell') ? 'alterCell2' : 'alterCell';
                echo '<tr><td class="'.$cellClass.'">'.$lost_item_d[0].'</td>
                    <td class="'.$cellClass.'">'.$lost_item_d[1].'</td>
                    <td class="'.$cellClass.'">'.$lost_item_d[2].'</td>';
                echo '</tr>'."\n";
            }
            echo '</table>'."\n";
            unset($lost_item_q);
        }

        // Tampilkan log kesalahan opname milik unit ini
        $error_log_q = $dbs->query("SELECT sl.log_date, sl.log_msg FROM system_log sl LEFT JOIN user u ON u.user_id = sl.id WHERE sl.log_location='stock_take' AND sl.log_msg LIKE 'Stock Take ERROR%' AND u.library_id = $target_lib_id");
        if ($error_log_q && $error_log_q->num_rows > 0) {
            echo '<br />';
            echo '<h3>' . __('Stock Take Error Logs') . '</h3><hr size="1" />';
            echo '<table style="width: 100%; border: 1px solid #666;" cellspacing="0">';
            echo '<tr>';
            echo '<th class="dataListHeader">' . __('Time') . '</th>
                <th class="dataListHeader">' . __('Message') . '</th>';
            echo '</tr>';
            while ($error_log_d = $error_log_q->fetch_row()) {
                $cellClass = ($cellClass == 'alterCell') ? 'alterCell2' : 'alterCell';
                echo '<tr>';
                echo '<td class="'.$cellClass.'">'.$error_log_d[0].'</td><td class="'.$cellClass.'">'.$error_log_d[1].'</td>';
                echo '</tr>';
            }
            echo '</table>';
            unset($error_log_q);
        }
        echo '</html>';
        $html_str = ob_get_clean();
        
        // Simpan file laporan ke folder reports
        $file_write = @file_put_contents(REPBS.$stk_take_report_filename, $html_str);
        if ($file_write) {
            echo '<script type="text/javascript">top.$.colorbox({href: "'.SWB.'/'.FLS.'/'.REP.'/'.$stk_take_report_filename.'", width: 800, height: 500, title: "Stock Take Report"})</script>';
        } else { 
            utility::jsAlert(str_replace('{directory}', REPBS, __('ERROR! Stock take report failed to generate, possibly because {directory} directory is not writable'))); 
        }
        
        // Simpan nama file laporan dan nonaktifkan opname KHUSUS UNIT INI
        $update_st_q = $dbs->query("UPDATE stock_take SET report_file='$stk_take_report_filename', is_active=0 WHERE is_active=1 AND library_id = $target_lib_id");
        
        // Hapus log kesalahan opname KHUSUS UNIT INI
        $clean_log_q = $dbs->query("DELETE sl FROM system_log sl LEFT JOIN user u ON u.user_id = sl.id WHERE sl.log_location='stock_take' AND sl.log_msg LIKE 'Stock Take ERROR%' AND u.library_id = $target_lib_id");
        
        // Write system log
        writeLog('staff', $_SESSION['uid'], 'stock_take', $_SESSION['realname'].' finish stock take ('.$stk_take_d[0].') for Library ID '.$target_lib_id.' from address '.$_SERVER['REMOTE_ADDR'], 'Finished', 'OK');
        
        // Notifikasi dan konfirmasi selesai
        echo '<script type="text/javascript">';
        echo 'alert(\''.__('Stock Take Proccess Finished!').'\');';
        echo 'parent.location.href = \''.SWB.'admin/index.php?mod=stock_take\';';
        echo '</script>';
    }
    exit();
} else {
?>
<div class="menuBox">
<div class="menuBoxInner errorIcon">
    <div class="per_title">
        <h2><?php echo __('Finish Stock Take'); ?></h2>
    </div>
    <div class="infoBox">
        <?php if ($is_super_admin): ?>
            <form method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="form-inline mb-3">
                <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-3" style="font-size: 0.9rem;">Unit: <?= htmlspecialchars($user_lib_name) ?></span>
        <?php endif; ?>
        
        <div><span class="important"><?php echo __('Are you sure to end current stock take proccess? Once it finished there is no way you can rollback this stock take'); ?></span></div>
    </div>
</div>
</div>
<?php
    // Form konfirmasi penyelesaian opname
    $form = new simbio_form_table_AJAX('stockTakeForm', $_SERVER['PHP_SELF'], 'post');
    $form->submit_button_attr = 'value="'.__('Finish Stock Take').'" class="button btn btn-delete btn-danger"';

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

    $purge_options[] = array('1', __('Yes'));
    $form->addCheckBox('purge', __('Purge Lost Item'), $purge_options);
    $form->addHidden('confirmFinish', 'true');
    $form->addHidden('library_id', $target_lib_id);
    
    echo $form->printOut();
}