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

/* System Log Viewer */
use SLiMS\Log\Factory as Log;

// 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-system');
// 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/paging/simbio_paging.inc.php';
require SIMBIO.'simbio_DB/datagrid/simbio_dbgrid.inc.php';
require SIMBIO.'simbio_DB/simbio_dbop.inc.php';

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

if (!$can_read) {
    die('<div class="errorBox">'.__('You don\'t have enough privileges to view this section').'</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 (Atau Kosong/0)
// Pustakawan Fakultas (FT, FEB, dll) yang memiliki library_id > 1 PASTI FALSE
$is_super_admin = (empty($user_lib_id) || $user_lib_id == 1 || $user_lib_id == 0);

// Aksi simpan / bersihkan log HANYA BISA dilakukan oleh Superadmin
if (isset($_POST['saveLogs']) AND $can_write AND $is_super_admin) {
   Log::download();
   exit();
}

if (isset($_POST['clearLogs']) AND $can_write AND $is_super_admin) {
   Log::truncate();
   Log::write('staff', $_SESSION['uid'], 'System', $_SESSION['realname'].' is cleaning all logs '. 'Log record', 'Clear');
   utility::jsToastr(__('System Log'), __('System Log data completely cleared!'), 'success');    
   echo '<script type="text/javascript">parent.$(\'#mainContent\').simbioAJAX(\''.MWB.'system/sys_log.php\');</script>';
   exit();
}

/* SEARCH FORM & HEADER */
?>
<div class="menuBox">
<div class="menuBoxInner syslogIcon">
    <div class="per_title">
        <h2><?php echo __('System Log'); ?></h2>
    </div>
    <div class="sub_section">
        <?php if ($is_super_admin) { ?>
        <div class="btn-group mb-3">
            <a href="#" onclick="confSubmit('clearLogsForm', '<?php echo __('Are you SURE to completely clear system log data? This action cannot be undo!'); ?>')" class="notAJAX btn btn-danger"> <?php echo __('CLEAR LOGS'); ?></a>
            <a href="#" onclick="confSubmit('saveLogsForm', '<?php echo __('Save Logs record to file?'); ?>')" class="notAJAX btn btn-default"><?php echo __('Save Logs To File'); ?></a>
        </div>
        <?php } ?>

        <form name="search" action="<?php echo MWB; ?>system/sys_log.php" id="search" method="get" class="form-inline mb-3" onsubmit="return false;">
    <?php if ($is_super_admin): ?>
        <!-- HANYA MUNCUL PADA SUPERADMIN (library_id = 1) -->
        <label class="mr-2 font-weight-bold"><?php echo __('Perpustakaan'); ?>:</label>
        <select name="library_id" id="libraryFilter" class="form-control col-md-3 mr-3" onchange="$('#doSearch').trigger('click')">
            <option value=""><?= __('-- Semua Perpustakaan --') ?></option>
            <?php
            $selected_lib = $_GET['library_id'] ?? '';
            $libs = $dbs->query("SELECT library_id, library_name FROM mst_library ORDER BY library_name");
            while ($lib = $libs->fetch_assoc()) {
                $selected = ($selected_lib !== '' && $selected_lib == $lib['library_id']) ? 'selected' : '';
                echo '<option value="' . $lib['library_id'] . '" ' . $selected . '>' . htmlspecialchars($lib['library_name']) . '</option>';
            }
            ?>
        </select>
    <?php else: ?>
        <!-- PUSTAKAWAN FAKULTAS (FT, FEB, DLL): Dropdown Tersembunyi -->
        <?php
        $user_lib_name = 'Perpustakaan Unit';
        $lib_info = $dbs->query("SELECT library_name FROM mst_library WHERE library_id = " . intval($user_lib_id));
        if ($lib_info && $lib_d = $lib_info->fetch_assoc()) {
            $user_lib_name = $lib_d['library_name'];
        }
        ?>
        <input type="hidden" name="library_id" id="libraryFilter" value="<?= htmlspecialchars($user_lib_id) ?>">
        <span class="badge badge-info p-2 mr-3" style="font-size: 0.9rem;">Unit: <?= htmlspecialchars($user_lib_name) ?></span>
    <?php endif; ?>

    <label class="mr-2 font-weight-bold"><?php echo __('Search'); ?>:</label>
    <input type="text" name="keywords" id="keywords" value="<?php echo isset($_GET['keywords']) ? htmlspecialchars($_GET['keywords']) : ''; ?>" class="form-control col-md-3 mr-2" placeholder="Kata kunci..." />
    <input type="button" id="doSearch" value="<?php echo __('Search'); ?>" class="btn btn-default" />
</form>

        <script type="text/javascript">
        $(document).ready(function() {
            $('#doSearch').on('click', function() {
                var libId = $('#libraryFilter').val();
                var kw = $('#keywords').val();
                var url = '<?php echo MWB; ?>system/sys_log.php?library_id=' + encodeURIComponent(libId) + '&keywords=' + encodeURIComponent(kw);
                $('#mainContent').simbioAJAX(url);
            });

            $('#keywords').on('keypress', function(e) {
                if (e.which == 13) {
                    e.preventDefault();
                    $('#doSearch').trigger('click');
                }
            });
        });
        </script>

        <!-- LOG CLEARANCE FORM -->
        <?php if ($is_super_admin) { ?>
        <form action="<?php echo MWB; ?>system/sys_log.php" id="clearLogsForm" target="blindSubmit" method="post" class="form-inline"><input type="hidden" name="clearLogs" value="true" /></form>
        <form action="<?php echo MWB; ?>system/sys_log.php" id="saveLogsForm" target="blindSubmit" method="post" class="form-inline"><input type="hidden" name="saveLogs" value="true" /></form>
        <?php } ?>
    </div>
</div>
</div>

<?php
/* DATAGRID LOGS LIST */
$datagrid = new simbio_datagrid();
$table_spec = 'system_log AS sl LEFT JOIN user AS u ON sl.id = u.user_id';

$datagrid->setSQLColumn(
    'sl.log_id',
    'sl.log_location AS \'' . __('Log Location') . '\'',
    'sl.log_msg AS \'' . __('Log Message') . '\'',
    'u.realname AS \'' . __('User') . '\'',
    '(SELECT library_name FROM mst_library WHERE library_id = u.library_id) AS \'' . __('Perpustakaan') . '\'',
    'sl.log_date AS \'' . __('Log Date') . '\''
);

$datagrid->setSQLorder('sl.log_date DESC');

$criteria = 'sl.log_id IS NOT NULL ';

if (!$is_super_admin) {
    // Pustakawan Fakultas DIKUNCI MATI ke user.library_id miliknya
    $criteria .= " AND u.library_id = " . intval($user_lib_id);
} else {
    // Superadmin bebas memfilter jika ada pilihan di dropdown
    if (isset($_GET['library_id']) && $_GET['library_id'] !== '') {
        $criteria .= " AND u.library_id = " . intval($_GET['library_id']);
    }
}

// Filter Kata Kunci
if (isset($_GET['keywords']) && $_GET['keywords'] !== '') {
    $keywords = $dbs->escape_string($_GET['keywords']);
    $criteria .= " AND (sl.log_msg LIKE '%$keywords%' OR sl.log_location LIKE '%$keywords%' OR u.realname LIKE '%$keywords%')";
}

$datagrid->setSQLCriteria($criteria);
$datagrid->table_attr = 'id="dataList" class="s-table table"';
$datagrid->table_header_attr = 'class="dataListHeader" style="font-weight: bold;"';

$datagrid_result = $datagrid->createDataGrid($dbs, $table_spec, 20, false);

if (isset($_GET['keywords']) && $_GET['keywords'] !== '') {
    $msg = str_replace('{result->num_rows}', $datagrid->num_rows, __('Found <strong>{result->num_rows}</strong> from your keywords'));
    echo '<div class="infoBox">' . $msg . ' : "' . htmlspecialchars($_GET['keywords']) . '"</div>';
}

echo $datagrid_result;
?>