<?php
/**
 * Collection general report
 * 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
 *
 */

/* Reporting section */

// key to authentication
define('INDEX_AUTH', '1');

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-reporting');

require SB.'admin/default/session_check.inc.php';
require SIMBIO.'simbio_GUI/table/simbio_table.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('reporting', 'r');
$can_write = utility::havePrivilege('reporting', 'w');

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

// ============================================================
// TAMBAHAN: FILTER LIBRARY DARI GET (UNTUK SUPERADMIN)
// ============================================================
$filter_library_id = isset($_GET['filter_library']) ? (int)$_GET['filter_library'] : 0;

// Tentukan library_id yang akan digunakan untuk filter
if ($is_superadmin && $filter_library_id > 0) {
    $selected_library_id = $filter_library_id;
} elseif ($is_superadmin) {
    $selected_library_id = 0; // 0 = semua library
} else {
    $selected_library_id = $current_library_id;
}

// ============================================================
// TAMBAHAN: INFORMASI LIBRARY DI HEADER
// ============================================================
$library_info = '';
if ($selected_library_id > 0) {
    $lib_q = $dbs->query("SELECT library_name FROM mst_library WHERE library_id = " . $selected_library_id);
    if ($lib_q->num_rows > 0) {
        $lib_d = $lib_q->fetch_assoc();
        $library_info = ' (' . $lib_d['library_name'] . ')';
    }
} else {
    $library_info = ' (Semua Perpustakaan)';
}

// ============================================================
// PERBAIKAN: FILTER library_id PER ALIAS TABEL
// ============================================================
if ($selected_library_id > 0) {
    $lib_biblio_filter = " AND b.library_id = $selected_library_id";
    $lib_item_filter   = " AND i.library_id = $selected_library_id";  // ← INI YANG DIPAKAI
    $lib_lh_filter     = " AND lh.library_id = $selected_library_id";
    $lib_loan_filter   = " AND l.library_id = $selected_library_id";
} else {
    $lib_biblio_filter = "";
    $lib_item_filter   = "";
    $lib_lh_filter     = "";
    $lib_loan_filter   = "";
}
// ============================================================


/* collection statistic */
$table = new simbio_table();
$table->table_attr = 'class="s-table table table-bordered mb-0"';

// 1. Total number of titles
$stat_query = $dbs->query("SELECT COUNT(b.biblio_id) FROM biblio b WHERE 1=1 $lib_biblio_filter");
$total_title_all = $stat_query->fetch_row()[0] ?? 0;
$collection_stat[__('Total Titles')] = $total_title_all.' '.__(' (including titles that still don\'t have items yet)');

// 2. Total number of titles with items
$stat_query = $dbs->query("
    SELECT DISTINCT b.biblio_id 
    FROM biblio b 
    INNER JOIN item i ON b.biblio_id = i.biblio_id 
    WHERE 1=1 $lib_biblio_filter
");
$stat_data = $stat_query->num_rows;
$collection_stat[__('Total Titles with items')] = $stat_data.__(' (only titles that have items)');
$collection_stat[__('Total Titles without items')] = ($total_title_all - $stat_data).__(' (only titles that haven\'t items)');

// 3. Total number of items (gunakan i.library_id jika ada)
$stat_query = $dbs->query("
    SELECT i.item_code 
    FROM item i 
    LEFT JOIN biblio b ON i.biblio_id = b.biblio_id 
    WHERE 1=1 $lib_item_filter
");
$stat_data = $stat_query->num_rows;
$collection_stat[__('Total Items/Copies')] = $stat_data;

// 4. Total number of checkout items (langsung pakai lh.library_id)
$stat_query = $dbs->query("
    SELECT COUNT(item_code) 
    FROM loan_history lh 
    WHERE is_lent=1 AND is_return=0 $lib_lh_filter
");
$stat_data = $stat_query->fetch_row();
$collection_stat[__('Total Checkout Items')] = $stat_data[0] ?? 0;

// 5. Total number of items in library
$total_items = $collection_stat[__('Total Items/Copies')];
$total_checkout = $collection_stat[__('Total Checkout Items')];
$collection_stat[__('Total Items In Library')] = (is_numeric($total_items) && is_numeric($total_checkout)) ? ($total_items - $total_checkout) : '?';

// 6. Total titles by GMD/medium
$stat_query = $dbs->query("
    SELECT gmd_name, COUNT(b.biblio_id) AS total_titles
    FROM `biblio` AS b
    INNER JOIN mst_gmd AS gmd ON b.gmd_id = gmd.gmd_id
    WHERE 1=1 $lib_biblio_filter
    GROUP BY b.gmd_id HAVING total_titles>0 ORDER BY COUNT(b.biblio_id) DESC
");

$stat_data = '<div class="chartLink"><a class="btn btn-success notAJAX openPopUp" href="'.MWB.'reporting/charts_report.php?chart=total_title_gmd&filter_library=' . $selected_library_id . '" width="700" height="470" title="'.__('Total Titles By Medium/GMD').'">'.__('Show in chart/plot').'</a></div>';
while ($data = $stat_query->fetch_row()) {
    $stat_data .= $data[0].' (<strong>'.$data[1].'</strong>), ';
}
$stat_data = substr($stat_data,0,-1);
if (empty($stat_data) || strstr($stat_data, 'href="..."')) {
    $stat_data .= __('No data available');
}
$collection_stat[__('Total Titles By Medium/GMD')] = $stat_data;

// 7. Total items by Collection Type
$stat_query = $dbs->query("
    SELECT coll_type_name, COUNT(i.item_id) AS total_items
    FROM `item` AS i
    INNER JOIN mst_coll_type AS ct ON i.coll_type_id = ct.coll_type_id
    INNER JOIN biblio b ON i.biblio_id = b.biblio_id
    WHERE 1=1 $lib_biblio_filter
    GROUP BY i.coll_type_id
    HAVING total_items >0
    ORDER BY COUNT(i.item_id) DESC
");

$stat_data = '<div class="chartLink"><a class="btn btn-success notAJAX openPopUp" href="'.MWB.'reporting/charts_report.php?chart=total_title_colltype&filter_library=' . $selected_library_id . '" width="700" height="470" title="'.__('Total Items By Collection Type').'">'.__('Show in chart/plot').'</a></div>';
while ($data = $stat_query->fetch_row()) {
    $stat_data .= $data[0].' (<strong>'.$data[1].'</strong>), ';
}
$stat_data = substr($stat_data,0,-1);
if (empty($stat_data) || strstr($stat_data, 'href="..."')) {
    $stat_data .= __('No data available');
}
$collection_stat[__('Total Items By Collection Type')] = $stat_data;

// 8. Popular titles (langsung pakai lh.library_id)
$stat_query = $dbs->query("
    SELECT b.title, COUNT(lh.loan_id) AS total_loans 
    FROM loan_history lh
    INNER JOIN biblio b ON lh.biblio_id = b.biblio_id
    WHERE lh.member_id IS NOT NULL AND lh.biblio_id IS NOT NULL $lib_lh_filter
    GROUP BY lh.biblio_id 
    ORDER BY total_loans DESC 
    LIMIT 10
");
$stat_data = '<ol>';
if (!empty($stat_query->num_rows)) {
    while ($data = $stat_query->fetch_row()) {
        $stat_data .= '<li>'.htmlspecialchars($data[0]).'</li>';
    }
} else {
    $stat_data .= '<li>'.__('No popular titles data available').'</li>';
}
$stat_data .= '</ol>';
$collection_stat[__('10 Most Popular Titles')] = $stat_data;

// Table Header
$table->setHeader(array(__('Collection Statistic Summary') . $library_info));
$table->table_header_attr = 'class="dataListHeader"';
$table->setCellAttr(0, 0, 'colspan="2"');

// Initial Row Count
$row = 1;
foreach ($collection_stat as $headings=>$stat_data) {
    $table->appendTableRow(array($headings, $stat_data));
    $table->setCellAttr($row, 0, 'class="alterCell" valign="top" style="width: 300px;"');
    $table->setCellAttr($row, 1, 'class="alterCell" valign="top" style="width: auto;"');
    $row++;
}

// Print Mode
$page_title = __('Collection Statistic Report');
if (isset($_GET['print'])) {
    require_once SB.'admin/admin_template/printed.tpl.php';
    $file_write = @file_put_contents(REPBS.'biblio_stat_print_result.html', $html_str);
    if ($file_write) {
        echo '<script type="text/javascript">
        top.$.colorbox({
            href: "'.SWB.FLS.'/'.REP.'/biblio_stat_print_result.html", 
            height: 500,  
            width: 800,
            iframe : true,
            fastIframe: false,
            title: function(){return "'.$page_title.'";}
        })
        </script>';
    } else { 
        utility::jsAlert(str_replace('{directory}', REPBS, __('ERROR! Collection Statistic Report failed to generate, possibly because {directory} directory is not writable'))); 
    }
    exit();
}

?>
<div class="menuBox">
    <div class="menuBoxInner statisticIcon">
        <div class="per_title">
            <h2><?php echo __('Collection Statistic'); ?></h2>
        </div>
        <div class="infoBox">
            <form name="printForm" action="<?php echo $_SERVER['PHP_SELF']; ?>" target="submitPrint" id="printForm" class="notAJAX" method="get">
                <input type="hidden" name="print" value="true" />
                <input type="submit" value="<?php echo __('Download Report'); ?>" class="s-btn btn btn-default" />
            </form>
            
            <?php if ($is_superadmin): ?>
            <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get" style="display:inline-block; margin-left: 15px;">
                <span class="mr-2"><?php echo __('Filter Library'); ?>:</span>
                <select name="filter_library" class="form-control" style="display:inline-block; width:auto;" onchange="this.form.submit()">
                    <option value="0" <?= $selected_library_id == 0 ? 'selected' : '' ?>><?php echo __('All Libraries'); ?></option>
                    <?php
                    $libs = $dbs->query("SELECT library_id, library_code, library_name FROM mst_library ORDER BY library_code ASC");
                    while ($lib = $libs->fetch_assoc()):
                        $selected = ($selected_library_id == $lib['library_id']) ? 'selected' : '';
                    ?>
                        <option value="<?= $lib['library_id'] ?>" <?= $selected ?>>
                            <?= $lib['library_code'] . ' - ' . $lib['library_name'] ?>
                        </option>
                    <?php endwhile; ?>
                </select>
                <noscript><button type="submit" class="btn btn-default"><?php echo __('Filter'); ?></button></noscript>
            </form>
            <?php endif; ?>
            
            <span style="margin-left: 15px; font-style: italic;">
                <?php 
                if ($selected_library_id > 0) {
                    $lib_name = $dbs->query("SELECT library_name FROM mst_library WHERE library_id = $selected_library_id")->fetch_assoc();
                    echo __('Showing statistics for') . ' <strong>' . ($lib_name['library_name'] ?? '') . '</strong>';
                } else {
                    echo __('Showing statistics for') . ' <strong>' . __('All Libraries') . '</strong>';
                }
                ?>
            </span>
        </div>
        <iframe name="submitPrint" style="display: none; visibility: hidden; width: 0; height: 0;"></iframe>
    </div>
</div>
<?php
echo $table->printTable();