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

/* Quick Return page */

// key to authenticate
if (!defined('INDEX_AUTH')) {
    define('INDEX_AUTH', '1');
}
// key to get full database access
define('DB_ACCESS', 'fa');

require '../../../sysconfig.inc.php';
// IP based access limitation
require LIB.'ip_based_access.inc.php';
do_checkIP('smc');
do_checkIP('smc-circulation');

// start the session
require SB.'admin/default/session.inc.php';
require SB.'admin/default/session_check.inc.php';

// ========== TAMBAHAN MULTI-LIBRARY ==========
$current_library_id = isset($_SESSION['library_id']) ? (int)$_SESSION['library_id'] : 1;
$is_superadmin = isset($_SESSION['uid']) && $_SESSION['uid'] == 1;
// ========== AKHIR TAMBAHAN ==========

// load settings from database
utility::loadSettings($dbs);

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

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

// check if quick return is enabled
if (!$sysconf['quick_return']) {
    die('<div class="errorBox">'.__('Quick Return is disabled').'</div');
}

if($sysconf['barcode_reader']) {
ob_start();
require SB.'admin/'.$sysconf['admin_template']['dir'].'/barcodescannermodal.tpl.php';
$barcode = ob_get_clean();
echo $barcode;
?>
  <script type="text/javascript">
    $('#barcodeReader').click(function(e){
      e.preventDefault();
      var url = $(this).attr('href');
      $('#iframeBarcodeReader').attr('src', url);
      $('#barcodeModal').modal('show');
    });

    $(document.body).bind('keyup', this, function(e){
      if(e.keyCode == 119) {
        $('#barcodeReader').click();
      }
    });
    parent.$(".modal-backdrop").remove();
  </script>
  <?php } ?>
  
<!-- Pesan -->
<div id="quickReturnMessage" class="alert alert-info" style="margin: 10px 15px; display: none;">
    <i class="fa fa-info-circle"></i> <span id="quickReturnMsgText"></span>
</div>

<div class="menuBox">
<div class="menuBoxInner quickReturnIcon">
    <div class="per_title">
        <h2><?php echo __('Quick Return'); ?></h2>
    </div>
    <div class="infoBox">
        <?php echo __('Insert an item ID to return collection with keyboard or barcode reader'); ?>
        <br><br>
        <strong><?php echo __('Library'); ?>:</strong> 
        <?php 
        $lib_query = "SELECT library_code, library_name FROM mst_library WHERE library_id = " . $current_library_id;
        $lib_result = $dbs->query($lib_query);
        $lib_data = $lib_result->fetch_assoc();
        echo '<span style="color:#337AB7;font-weight:bold;">' . $lib_data['library_code'] . ' - ' . $lib_data['library_name'] . '</span>';
        ?>
        <br>
        <small class="text-muted"><?php echo __('Only items from this library can be returned here (Pulang Kandang).'); ?></small>
    </div>
    <div class="sub_section">
      <form action="<?php echo MWB; ?>circulation/circulation_action.php" target="circAction" method="post" class="form-inline" id="quickReturnForm">
        <?php echo __('Item ID'); ?>
        <input type="text" name="quickReturnID" id="quickReturnID" size="30" class="form-control col-3" autofocus />
        <input type="hidden" name="return_library_id" value="<?php echo $current_library_id; ?>" />
        <input type="submit" value="<?php echo __('Return'); ?>" id="quickReturnProcess" class="s-btn btn btn-default" />
        <?php if($sysconf['barcode_reader']) : ?>
        <a class="s-btn btn btn-default notAJAX" id="barcodeReader" href="<?php echo MWB.'circulation/barcode_reader.php?mode=quickreturn' ?>">Open Barcode Reader - Experimental (F8)</a>
        <?php endif ?>
      </form>
      <iframe name="circAction" id="circAction" style="display: inline; width: 5px; height: 5px; visibility: hidden;"></iframe>
    </div>
</div>
</div>
<div id="circulationLayer">&nbsp;</div>

<!-- ============================================================
SCRIPT: VALIDASI SEBELUM SUBMIT (DENGAN AJAX)
============================================================ -->
<script type="text/javascript">
$(document).ready(function() {
    $('#quickReturnID').focus();
    
    // ============================================================
    // VALIDASI SEBELUM SUBMIT KE circulation_action.php
    // ============================================================
    $('#quickReturnForm').on('submit', function(e) {
        var itemCode = $('#quickReturnID').val().trim();
        
        if (itemCode === '') {
            showQuickReturnMessage('<?php echo __('Please enter item code/barcode.'); ?>', 'warning');
            e.preventDefault();
            return false;
        }
        
        // ============================================================
        // CEK APAKAH ITEM MILIK PERPUSTAKAAN INI (VIA AJAX)
        // ============================================================
        $.ajax({
            url: '<?php echo MWB; ?>circulation/ajax_action.php',
            type: 'POST',
            data: {
                check_item_library: true,
                item_code: itemCode,
                return_library_id: <?php echo $current_library_id; ?>
            },
            dataType: 'json',
            success: function(response) {
                if (response.status === 'error') {
                    showQuickReturnMessage(response.message, 'danger');
                    $('#quickReturnID').val('').focus();
                    $('#quickReturnProcess').prop('disabled', false).val('<?php echo __('Return'); ?>');
                    e.preventDefault();
                    return false;
                } else {
                    // Item valid, lanjutkan submit form
                    showQuickReturnMessage('<?php echo __('Processing return...'); ?>', 'info');
                    $('#quickReturnProcess').prop('disabled', true).val('<?php echo __('Processing...'); ?>');
                    // Submit form
                    $('#quickReturnForm').off('submit').submit();
                }
            },
            error: function() {
                showQuickReturnMessage('<?php echo __('Error validating item. Please try again.'); ?>', 'danger');
                $('#quickReturnProcess').prop('disabled', false).val('<?php echo __('Return'); ?>');
                e.preventDefault();
                return false;
            }
        });
        
        e.preventDefault();
        return false;
    });
    
    // ============================================================
    // HANDLE RESPONSE DARI IFRAME (untuk menampilkan hasil)
    // ============================================================
    var iframe = document.getElementById('circAction');
    if (iframe) {
        iframe.addEventListener('load', function() {
            try {
                var content = iframe.contentDocument || iframe.contentWindow.document;
                var body = content.body;
                if (body) {
                    var html = body.innerHTML;
                    // Cek apakah ada pesan error/success
                    if (html.indexOf('errorBox') !== -1 || html.indexOf('alert-danger') !== -1) {
                        // Ada error, tampilkan
                        var msg = $(body).find('.errorBox, .alert-danger').text().trim();
                        if (msg) {
                            showQuickReturnMessage(msg, 'danger');
                        }
                    } else if (html.indexOf('success') !== -1 || html.indexOf('infoBox') !== -1) {
                        showQuickReturnMessage('<?php echo __('Item successfully returned!'); ?>', 'success');
                    }
                }
            } catch(e) {
                // Ignore
            }
            $('#quickReturnProcess').prop('disabled', false).val('<?php echo __('Return'); ?>');
            $('#quickReturnID').val('').focus();
        });
    }
});

function showQuickReturnMessage(message, type) {
    var msgBox = $('#quickReturnMessage');
    var msgText = $('#quickReturnMsgText');
    msgText.text(message);
    msgBox.removeClass('alert-info alert-success alert-warning alert-danger');
    msgBox.addClass('alert-' + (type || 'info'));
    msgBox.show();
    
    clearTimeout(window.quickReturnTimer);
    window.quickReturnTimer = setTimeout(function() {
        msgBox.fadeOut();
    }, 5000);
}
</script>