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

/* Member card print */

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

// main system configuration
require '../../../sysconfig.inc.php';
// IP based access limitation
require LIB.'ip_based_access.inc.php';
do_checkIP('smc');
do_checkIP('smc-membership');
// 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/form_maker/simbio_form_table_AJAX.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';

// ========== 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('membership', 'r');

if (!$can_read) {
    die('<div class="errorBox">You dont have enough privileges to view this section</div>');
}

// local settings
$max_print = 10;

// ========== TAMBAHAN: Informasi Library di Header ==========
$library_info = '';
if (!$is_superadmin) {
    $lib_q = $dbs->query("SELECT library_name FROM mst_library WHERE library_id = " . $current_library_id);
    if ($lib_q->num_rows > 0) {
        $lib_d = $lib_q->fetch_assoc();
        $library_info = ' - ' . $lib_d['library_name'];
    }
}
// ========== AKHIR TAMBAHAN ==========

// clean print queue
if (isset($_GET['action']) AND $_GET['action'] == 'clear') {
    // update print queue count object
    echo '<script type="text/javascript">parent.$(\'#queueCount\').html(\'0\');</script>';
    utility::jsAlert(__('Print queue cleared!'));
    unset($_SESSION['card']);
    exit();
}

if (isset($_POST['itemID']) AND !empty($_POST['itemID']) AND isset($_POST['itemAction'])) {
    if (!$can_read) {
        die();
    }
    if (!is_array($_POST['itemID'])) {
        // make an array
        $_POST['itemID'] = array($_POST['itemID']);
    }
    // loop array
    if (isset($_SESSION['card'])) {
        $print_count = count($_SESSION['card']);
    } else {
        $print_count = 0;
    }
    // card size
    $size = 2;
    // create AJAX request
    echo '<script type="text/javascript" src="'.JWB.'jquery.js"></script>';
    echo '<script type="text/javascript">';
    // loop array
    foreach ($_POST['itemID'] as $itemID) {
        if ($print_count == $max_print) {
            $limit_reach = true;
            break;
        }
        if (isset($_SESSION['card'][$itemID])) {
            continue;
        }
        if (!empty($itemID)) {
            $card_text = trim($itemID);
            echo '$.ajax({url: \''.SWB.'lib/phpbarcode/barcode.php?code='.$card_text.'&encoding='.$sysconf['barcode_encoding'].'&scale='.$size.'&mode=png\', type: \'GET\', error: function() { alert(\'Error creating member card!\'); } });'."\n";
            // add to sessions
            $_SESSION['card'][$itemID] = $itemID;
            $print_count++;
        }
    }
    echo '</script>';
    if (isset($limit_reach)) {
        $msg = str_replace('{max_print}', $max_print, __('Selected items NOT ADDED to print queue. Only {max_print} can be printed at once')); //mfc
        utility::jsAlert($msg);
    } else {
        // update print queue count object
        echo '<script type="text/javascript">parent.$(\'#queueCount\').html(\''.$print_count.'\');</script>';
        utility::jsAlert(__('Selected items added to print queue'));
    }
    exit();
}

// card pdf download
if (isset($_GET['action']) AND $_GET['action'] == 'print') {
    // check if label session array is available
    if (!isset($_SESSION['card'])) {
        utility::jsAlert(__('There is no data to print!'));
        die();
    }
    if (count($_SESSION['card']) < 1) {
        utility::jsAlert(__('There is no data to print!'));
        die();
    }
    // concat all ID together
    $member_ids = '';
    foreach ($_SESSION['card'] as $id) {
        $member_ids .= '\''.$dbs->escape_string($id).'\',';
    }
    // strip the last comma
    $member_ids = substr_replace($member_ids, '', -1);

    // ========== PERBAIKAN: Fetch member data dengan GROUP_CONCAT member_type_name ==========
    $member_q = $dbs->query('SELECT m.member_name, m.member_id, m.member_image, m.member_address, m.member_email, m.inst_name, m.postal_code, m.pin, m.member_phone, m.expire_date, m.register_date, 
        GROUP_CONCAT(DISTINCT mt.member_type_name SEPARATOR ", ") AS member_type_name 
        FROM member AS m
        LEFT JOIN member_member_type AS mmt ON m.member_id = mmt.member_id
        LEFT JOIN mst_member_type AS mt ON (
            (mmt.member_type_id = mt.member_type_id AND mmt.library_id = ' . (int)$current_library_id . ') 
            OR (m.member_type_id = mt.member_type_id)
        )
        WHERE m.member_id IN('.$member_ids.')
        GROUP BY m.member_id');
        
    $member_datas = array();
    while ($member_d = $member_q->fetch_assoc()) {
        if ($member_d['member_id']) {
            $member_datas[] = $member_d;
        }
    }

    // include printed settings configuration file
    include SB.'admin'.DS.'admin_template'.DS.'printed_settings.inc.php';
    // check for custom template settings
    $custom_settings = SB.'admin'.DS.$sysconf['admin_template']['dir'].DS.$sysconf['template']['theme'].DS.'printed_settings.inc.php';
    if (file_exists($custom_settings)) {
        include $custom_settings;
    }

    // load print settings from database to override value from printed_settings file
    loadPrintSettings($dbs, 'membercard');

    // execute registered hook
    \SLiMS\Plugins::getInstance()->execute('membercard_theme_print', [$member_datas]);

    // chunk cards array
    $chunked_card_arrays = array_chunk($member_datas, $card_ = $sysconf['print']['membercard']['items_per_row']);

    // create html output
    ob_start();
    $card_conf = $sysconf['print']['membercard'];
    $card_template = $card_conf['template'];
    $card_path = SWB.FLS.DS.'membercard'.DS.$card_template.DS;
    $card_logo = $card_path.IMG.DS.$card_conf['logo'];
    $card_stamp = $card_path.IMG.DS.$card_conf['stamp_file'];
    $card_signature = $card_path.IMG.DS.$card_conf['signature_file'];
    
    require_once SB.FLS.DS.'membercard'.DS.$card_template.DS.'membercard.php';
    $html_str = ob_get_clean();

    // unset the session
    unset($_SESSION['card']);
    // write to file
    $print_file_name = 'member_card_gen_print_result_'.strtolower(str_replace(' ', '_', $_SESSION['uname'])).'.html';
    $file_write = @file_put_contents(UPLOAD.$print_file_name, $html_str);
    if ($file_write) {
        // update print queue count object
        echo '<script type="text/javascript">parent.$(\'#queueCount\').html(\'0\');</script>';
        // open result in window
        echo '<script type="text/javascript">top.jQuery.colorbox({href: "'.SWB.FLS.'/'.$print_file_name.'?v='.date('YmdHis').'", iframe: true, width: 800, height: 500, title: "'.__('Member Card Printing').'"})</script>';
    } else { utility::jsAlert(str_replace('{directory}', SB.FLS, __('ERROR! Cards failed to generate, possibly because {directory} directory is not writable'))); }
    exit();
}

?>
<div class="menuBox">
<div class="menuBoxInner printIcon">
    <div class="per_title">
        <h2><?php echo __('Member Card Printing'); ?></h2>
    </div>
    <div class="sub_section">
        <div class="btn-group mb-2">
            <a target="blindSubmit" href="<?php echo MWB; ?>membership/member_card_generator.php?action=clear" class="btn btn-default notAJAX" > <?php echo __('Clear Print Queue'); ?></a>
            <a target="blindSubmit" href="<?php echo MWB; ?>membership/member_card_generator.php?action=print" class="btn btn-default notAJAX"><?php echo __('Print Member Cards for Selected Data'); ?></a>
            <a href="<?php echo MWB; ?>system/membercard_theme.php" width="780" height="500" class="btn btn-default" title="<?php echo __('Member card print settings'); ?>"><?php echo __('Member card print settings'); ?></a>
        </div>
        <form name="search" action="<?php echo MWB; ?>membership/member_card_generator.php" id="search" method="get" class="form-inline">
            <!-- ========== Dropdown Library untuk Superadmin ========== -->
            <?php if ($is_superadmin) { ?>
                <select name="library_id" class="form-control mr-2">
                    <option value="0"><?php echo __('All Libraries'); ?></option>
                    <?php
                    $lib_q = $dbs->query("SELECT library_id, library_name FROM mst_library ORDER BY library_name");
                    while ($lib_d = $lib_q->fetch_assoc()) {
                        $selected = (isset($_GET['library_id']) && $_GET['library_id'] == $lib_d['library_id']) ? 'selected' : '';
                        echo '<option value="' . $lib_d['library_id'] . '" ' . $selected . '>' . htmlspecialchars($lib_d['library_name']) . '</option>';
                    }
                    ?>
                </select>
            <?php } ?>
            <!-- ========== AKHIR DROPDOWN ========== -->

            <?php echo __('Search'); ?>
            <input type="text" name="keywords" class="form-control col-md-3 ml-1 mr-1" value="<?php echo isset($_GET['keywords']) ? htmlspecialchars($_GET['keywords']) : ''; ?>" />
            <input type="submit" id="doSearch" value="<?php echo __('Search'); ?>" class="s-btn btn btn-default" />
        </form>
    </div>
    <div class="infoBox">
    <?php
    echo __('Maximum').' <strong class="text-danger">'.$max_print.'</strong> '.__('records can be printed at once. Currently there is').' ';
    if (isset($_SESSION['card'])) {
        echo '<strong id="queueCount" class="text-danger">'.count($_SESSION['card']).'</strong>';
    } else { echo '<strong id="queueCount" class="text-danger">0</strong>'; }
    echo ' '.__('in queue waiting to be printed.');
    if (!$is_superadmin) {
        echo ' <strong class="ml-2">' . htmlspecialchars($library_info) . '</strong>';
    }
    ?>
    </div>
</div>
</div>
<?php
/* search form end */
/* ITEM LIST */

// ========== PERBAIKAN: Table Spec & Join dengan member_member_type ==========
$table_spec = 'member AS m
    LEFT JOIN member_member_type AS mmt ON m.member_id = mmt.member_id
    LEFT JOIN mst_member_type AS mt ON (
        (mmt.member_type_id = mt.member_type_id AND mmt.library_id = ' . (int)$current_library_id . ') 
        OR (m.member_type_id = mt.member_type_id)
    )
    LEFT JOIN mst_library AS lib ON m.library_id=lib.library_id';

// create datagrid
$datagrid = new simbio_datagrid();
$datagrid->setSQLColumn('m.member_id',
    'm.member_id AS \''.__('Member ID').'\'',
    'm.member_name AS \''.__('Member Name').'\'',
    'GROUP_CONCAT(DISTINCT mt.member_type_name SEPARATOR ", ") AS \''.__('Membership Type').'\'',
    'lib.library_name AS \''.__('Library').'\'');
$datagrid->setSQLorder('m.last_update DESC');

// ========== PERBAIKAN: Filter Multi-Library (Library Asal OR Member Type Aktif) ==========
$criteria = array();

if ($is_superadmin) {
    if (isset($_GET['library_id']) && (int)$_GET['library_id'] > 0) {
        $selected_lib = (int)$_GET['library_id'];
        $criteria[] = "(m.library_id = $selected_lib OR (mmt.library_id = $selected_lib AND mmt.is_active = 1))";
    }
} else {
    // Non-Superadmin: tampilkan jika library asal ATAU punya member_type aktif di perpustakaan tersebut
    $criteria[] = "(m.library_id = $current_library_id OR (mmt.library_id = $current_library_id AND mmt.is_active = 1))";
}

// Filter Keyword Pencarian
if (isset($_GET['keywords']) AND $_GET['keywords']) {
    $keyword = utility::filterData('keywords', 'get', true, true, true);
    $words = explode(' ', $keyword);
    if (count($words) > 1) {
        $concat_sql = ' (';
        foreach ($words as $word) {
            $concat_sql .= " (m.member_id LIKE '%$word%' OR m.member_name LIKE '%$word%') AND";
        }
        $concat_sql = substr_replace($concat_sql, '', -4);
        $concat_sql .= ') ';
        $criteria[] = $concat_sql;
    } else {
        $criteria[] = "(m.member_id LIKE '%$keyword%' OR m.member_name LIKE '%$keyword%')";
    }
}

// Gabungkan semua kriteria dengan 'AND'
if (count($criteria) > 0) {
    $datagrid->setSQLCriteria(implode(' AND ', $criteria) . " GROUP BY m.member_id");
} else {
    $datagrid->setSQLCriteria("m.member_id IS NOT NULL GROUP BY m.member_id");
}
// ========== AKHIR PERBAIKAN ==========

// set table and table header attributes
$datagrid->table_attr = 'id="dataList" class="s-table table"';
$datagrid->table_header_attr = 'class="dataListHeader" style="font-weight: bold;"';
// edit and checkbox property
$datagrid->edit_property = false;
$datagrid->chbox_property = array('itemID', __('Add'));
$datagrid->chbox_action_button = __('Add To Print Queue');
$datagrid->chbox_confirm_msg = __('Add to print queue?');
$datagrid->column_width = array('10%', '15%', '35%', '20%', '20%');
// set checkbox action URL
$datagrid->chbox_form_URL = $_SERVER['PHP_SELF'];
// put the result into variables
$datagrid_result = $datagrid->createDataGrid($dbs, $table_spec, 20, $can_read);
if (isset($_GET['keywords']) AND $_GET['keywords']) {
    echo '<div class="infoBox">'.__('Found').' '.$datagrid->num_rows.' '.__('from your search with keyword').': "'.htmlspecialchars($_GET['keywords']).'"</div>';
}
echo $datagrid_result;
/* main content end */