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

/* Circulation section */

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

if (!defined('SB')) {
    // main system configuration
    require '../../../sysconfig.inc.php';
    // start the session
    require SB.'admin/default/session.inc.php';
}
// IP based access limitation
require LIB.'ip_based_access.inc.php';
do_checkIP('smc');
do_checkIP('smc-circulation');

require SB.'admin/default/session_check.inc.php';
require SIMBIO.'simbio_GUI/form_maker/simbio_form_element.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 ==========

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

// ============================================================
// HANDLER UNTUK CEK MEMBER TYPE SEBELUM START TRANSACTION
// ============================================================
if (isset($_POST['memberID']) && !empty($_POST['memberID'])) {
    $member_id = trim($_POST['memberID']);
    
    // Cek apakah member ada di database
    $check_member = $dbs->query("SELECT member_id, member_name, member_type_id FROM member WHERE member_id = '" . $dbs->escape_string($member_id) . "'");
    
    if ($check_member->num_rows == 0) {
        $error_msg = '<div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <strong>Error!</strong> Member ID "' . htmlspecialchars($member_id) . '" not found in database.
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                      </div>';
        $_SESSION['circulation_error'] = $error_msg;
        header('Location: ' . MWB . 'circulation/index.php');
        exit;
    }
    
    $member_data = $check_member->fetch_assoc();
    
    // ============================================================
    // CEK APAKAH MEMBER MEMILIKI MEMBER TYPE AKTIF DI PERPUSTAKAAN INI
    // ============================================================
    $check_type = $dbs->query("
        SELECT mmt.id, mmt.is_active, mt.member_type_name, mt.library_id
        FROM member_member_type mmt
        INNER JOIN mst_member_type mt ON mmt.member_type_id = mt.member_type_id
        WHERE mmt.member_id = '" . $dbs->escape_string($member_id) . "'
          AND mmt.library_id = " . (int)$current_library_id . "
          AND mmt.is_active = 1
    ");
    
if ($check_type->num_rows == 0) {
    // Ambil nama member dari database
    $member_name = $member_data['member_name'] ?? 'Unknown Member';
    
    $error_msg = '<div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <strong>Access Denied!</strong> 
                    <strong>' . htmlspecialchars($member_name) . '</strong> (' . htmlspecialchars($member_id) . ') 
                    is not registered in your library.
                    <br><small>Please contact the member to register at ' . htmlspecialchars($lib_data['library_name'] ?? 'this library') . '.</small>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                  </div>';
    $_SESSION['circulation_error'] = $error_msg;
    header('Location: ' . MWB . 'circulation/index.php');
    exit;
}
    
    // Member valid, lanjutkan ke transaction
    $_SESSION['memberID'] = $member_id;
    header('Location: ' . MWB . 'circulation/circulation_action.php');
    exit;
}

// ============================================================
// CEK APAKAH ADA ERROR MESSAGE DI SESSION
// ============================================================
$error_display = '';
if (isset($_SESSION['circulation_error']) && !empty($_SESSION['circulation_error'])) {
    $error_display = $_SESSION['circulation_error'];
    unset($_SESSION['circulation_error']);
}

// check if there is transaction running
if (isset($_SESSION['memberID']) AND !empty($_SESSION['memberID'])) {
    define('DIRECT_INCLUDE', true);
    include MDLBS.'circulation/circulation_action.php';
} else {
?>
<div class="menuBox">
  <div class="menuBoxInner circulationIcon">
    <div class="per_title">
        <h2><?php echo __('Circulation'); ?></h2>
    </div>
    
    <!-- ========== Informasi Library ========== -->
    <?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();
    ?>
    <div class="infoBox">
        <strong><?php echo __('Library'); ?>:</strong> 
        <span style="color:#337AB7;font-weight:bold;"><?php echo $lib_data['library_code'] . ' - ' . $lib_data['library_name']; ?></span>
        <br>
        <small><?php echo __('Only members registered at this library can borrow items.'); ?></small>
    </div>
    <!-- ========== AKHIR INFORMASI ========== -->
    
    <!-- ============================================================
    TAMPILKAN ERROR MESSAGE JIKA ADA
    ============================================================ -->
    <?php if (!empty($error_display)): ?>
        <?= $error_display ?>
    <?php endif; ?>
    
    <div class="infoBox">
        <?php echo __('CIRCULATION - Insert a member ID to start transaction with keyboard or barcode reader'); ?>
    </div>
    <div class="sub_section">
      <form id="startCirc" action="<?php echo MWB; ?>circulation/index.php" method="post" class="form-inline">
        <span class="mr-2"><?php echo __('Member ID'); ?></span>
        <?php
        // create AJAX drop down
        $ajaxDD = new simbio_fe_AJAX_select();
        $ajaxDD->element_name = 'memberID';
        $ajaxDD->element_css_class = 'form-control col-3 ajaxInputField';
        $ajaxDD->handler_URL = MWB.'membership/member_AJAX_response.php';
        echo $ajaxDD->out();
        ?>
        <input type="submit" value="<?php echo __('Start Transaction'); ?>" name="start" id="start" 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=membership' ?>"><?= __('Open Barcode Reader - Experimental (F8)')?></a>
        <?php endif ?>
      </form>
    </div>
  </div>
</div>
<?php 
  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){
      // F8
      if(e.keyCode == 119) {
        $('#barcodeReader').click();
      }
    });
    parent.$(".modal-backdrop").remove();
  </script>
  <?php }
    if (isset($_POST['finishID'])) {
      $msg = str_ireplace('{member_id}', $_POST['finishID'], __('Transaction with member {member_id} is completed'));
      echo '<div class="infoBox">'.$msg.'</div>';
    }
}