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

// key to authenticate
if (!defined('INDEX_AUTH')) {
    define('INDEX_AUTH', '1');
}

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

// ========== 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 ==========

// ============================================================
// HANDLER: CHECK ITEM LIBRARY (UNTUK QUICK RETURN VALIDATION)
// ============================================================
if (isset($_POST['check_item_library']) && isset($_POST['item_code']) && isset($_POST['return_library_id'])) {
    header('Content-Type: application/json');
    
    $item_code = $dbs->escape_string(trim($_POST['item_code']));
    $library_id = (int)$_POST['return_library_id'];
    
    // ============================================================
    // 1. CEK APAKAH ITEM ADA DI PERPUSTAKAAN INI
    // ============================================================
    $item_q = $dbs->query("
        SELECT i.item_code, i.library_id, l.library_name, b.title
        FROM item i
        LEFT JOIN mst_library l ON i.library_id = l.library_id
        LEFT JOIN biblio b ON i.biblio_id = b.biblio_id
        WHERE i.item_code = '$item_code' AND i.library_id = $library_id
    ");
    
    if ($item_q->num_rows == 0) {
        // Cek apakah item ada di library lain
        $other_q = $dbs->query("
            SELECT l.library_name 
            FROM item i
            LEFT JOIN mst_library l ON i.library_id = l.library_id
            WHERE i.item_code = '$item_code'
        ");
        
        if ($other_q->num_rows > 0) {
            $other = $other_q->fetch_assoc();
            echo json_encode([
                'status' => 'error',
                'message' => 'This item belongs to ' . ($other['library_name'] ?? 'another library') . '. Please return it to the owning library.'
            ]);
        } else {
            echo json_encode([
                'status' => 'error',
                'message' => 'Item not found in database.'
            ]);
        }
        exit;
    }
    
    // ============================================================
    // 2. CEK APAKAH ITEM SEDANG DIPINJAM (DENGAN FILTER LIBRARY_ID)
    // ============================================================
    $loan_q = $dbs->query("
        SELECT l.loan_id, l.member_id 
        FROM loan l
        LEFT JOIN item i ON l.item_code = i.item_code
        WHERE l.item_code = '$item_code' 
          AND l.is_lent = 1 
          AND l.is_return = 0
          AND i.library_id = $library_id
    ");
    
    if ($loan_q->num_rows == 0) {
        // Cek apakah item sedang dipinjam di library lain
        $other_loan_q = $dbs->query("
            SELECT l.library_name 
            FROM loan l
            LEFT JOIN item i ON l.item_code = i.item_code
            LEFT JOIN mst_library l ON i.library_id = l.library_id
            WHERE l.item_code = '$item_code' 
              AND l.is_lent = 1 
              AND l.is_return = 0
        ");
        if ($other_loan_q->num_rows > 0) {
            $other_loan = $other_loan_q->fetch_assoc();
            echo json_encode([
                'status' => 'error',
                'message' => 'This item is currently on loan at ' . ($other_loan['library_name'] ?? 'another library') . '. Please return it there.'
            ]);
        } else {
            echo json_encode([
                'status' => 'error',
                'message' => 'This item is not currently on loan.'
            ]);
        }
        exit();
    }
    
    // ============================================================
    // 3. SUKSES - ITEM VALID
    // ============================================================
    echo json_encode([
        'status' => 'success',
        'message' => 'Item is valid for return.',
        'data' => [
            'item_code' => $item_code
        ]
    ]);
    exit();
}

// ============================================================
// HANDLER: QUICK RETURN (EXISTING)
// ============================================================
if (isset($_POST['quickReturnID'])) {
    $_POST['quickReturnID'] = $dbs->escape_string(trim($_POST['quickReturnID']));
    
    // ========== TAMBAHAN: Validasi pulang kandang via AJAX ==========
    $item_check = $dbs->query("SELECT library_id FROM item WHERE item_code = '" . $_POST['quickReturnID'] . "'");
    if ($item_check->num_rows > 0) {
        $item_data = $item_check->fetch_assoc();
        $item_library_id = $item_data['library_id'];
        if ($item_library_id != $current_library_id) {
            // Item milik perpustakaan lain, tolak
            echo '<script type="text/javascript">'."\n";
            echo 'parent.$(\'#quickReturnMessage\').show();'."\n";
            echo 'parent.$(\'#quickReturnMsgText\').text(\'' . __('This item belongs to another library. Please return it to the owning library.') . '\');'."\n";
            echo 'parent.$(\'#quickReturnMessage\').removeClass(\'alert-info alert-success alert-warning\').addClass(\'alert-danger\');'."\n";
            echo 'parent.$(\'#quickReturnID\').val(\'\').focus();'."\n";
            echo '</script>';
            exit();
        }
    }
    // ========== AKHIR TAMBAHAN ==========
    
    echo '<script type="text/javascript">'."\n";
    echo 'parent.$(\'#circulationLayer\').simbioAJAX(\''.MWB.'circulation/circulation_action.php\', {method: \'post\', addData: \'quickReturnID='.trim($_POST['quickReturnID']).'\'});'."\n";
    echo 'parent.$(\'#quickReturnID\').val(\'\');'."\n";
    echo 'parent.$(\'#quickReturnID\').focus();'."\n";
    echo '</script>';
    exit();
}