<?php
/**
 * @author Drajat Hasan
 * @email drajathasan20@gmail.com
 * @create date 2023-04-15 11:21:16
 * @modify date 2023-04-15 11:38:32
 * @license GPLv3
 * @desc [description]
 */

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

// main system configuration
require '../../../sysconfig.inc.php';
// start the session
require SB.'admin/default/session.inc.php';
require SB.'admin/default/session_check.inc.php';

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

// Privileges checking
$can_read = utility::havePrivilege('stock_take', 'r');
if (!$can_read) {
    die('<div class="alert alert-danger">'.__('You don\'t have enough privileges to access this area!').'</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'];
    }
}

$is_super_admin = (empty($user_lib_id) || $user_lib_id == 1 || $user_lib_id == 0);

// Sanitasi nama file input
$fileName = isset($_GET['file']) ? basename($_GET['file']) : '';
$reportPath = SB . 'files/reports/' . $fileName;

// Validasi kelayakan file
$is_valid_file = false;
if (!empty($fileName) && file_exists($reportPath)) {
    $ext = strtolower(pathinfo($reportPath, PATHINFO_EXTENSION));
    // Hanya izinkan format laporan HTML atau TXT
    if (in_array($ext, ['html', 'htm', 'txt'])) {
        $is_valid_file = true;
    }
}

$css = <<<HTML
<style>
@media print 
{
    #print {
        display: none !important;
    }
}
</style>
HTML;

ob_start();
if ($is_valid_file) {
    echo '<div class="p-3">';
    echo '<button id="print" class="btn btn-secondary mb-2 text-white" onclick="window.print()"><i class="text-white fa fa-print"></i>&nbsp;'.__('Print').'</button>';
    echo file_get_contents($reportPath);
    echo '</div>';
} else {
    echo '<div class="alert alert-danger">Path ' . simbio_security::xssFree($reportPath) . ' not found or invalid format!</div>';
}
$content = ob_get_clean();

include SB . 'admin/admin_template/printed_page_tpl.php';
exit;