<?php
/**
 * Popup untuk tambah member type anggota
 * Mengikuti metode SLiMS popup
 */

// 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-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.inc.php';
require SIMBIO.'simbio_DB/simbio_dbop.inc.php';

// privileges checking
$can_write = utility::havePrivilege('membership', 'w');
if (!$can_write) {
    die('<div class="errorBox">'.__('You are not authorized to view this section').'</div>');
}
# CHECK ACCESS
if ($_SESSION['uid'] != 1) {
    if (!utility::haveAccess('membership.add-new-member')) {
        die('<div class="errorBox">' . __('You are not authorized to view this section') . '</div>');
    }
}

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

// page title
$page_title = 'Tambah Member Type';

// get member_id from url
$member_id = isset($_GET['member_id']) ? $dbs->escape_string(trim($_GET['member_id'])) : '';
if (empty($member_id)) {
    die('<div class="errorBox">' . __('Member ID tidak ditemukan') . '</div>');
}

// ========== TAMBAHAN: Ambil library_id member ==========
$member_q = $dbs->query("SELECT library_id FROM member WHERE member_id = '$member_id'");
$member_data = $member_q->fetch_assoc();
$member_library_id = $member_data['library_id'] ?? 1;
// ========== AKHIR TAMBAHAN ==========

// start the output buffer
ob_start();

/* main content */
// Proses simpan
if (isset($_POST['save']) && isset($_POST['member_type_id'])) {
    $member_type_id = (int)$_POST['member_type_id'];
    $library_id = (int)$_POST['library_id'];
    
    // Cek apakah sudah ada
    $check = $dbs->query("SELECT id FROM member_member_type 
                          WHERE member_id = '$member_id' AND member_type_id = $member_type_id");
    
    if ($check->num_rows == 0) {
        // Insert relasi baru
        $insert = $dbs->query("INSERT INTO member_member_type 
                               (member_id, member_type_id, library_id, is_active) 
                               VALUES ('$member_id', $member_type_id, $library_id, 1)");
        
        if ($insert) {
            // Nonaktifkan yang lain di library yang sama
            $dbs->query("UPDATE member_member_type SET is_active = 0 
                         WHERE member_id = '$member_id' AND library_id = $library_id 
                         AND member_type_id != $member_type_id");
            
            utility::jsToastr('Member Type', __('Member type berhasil ditambahkan'), 'success');
            echo '<script type="text/javascript">';
            echo 'parent.$("#mainContent").simbioAJAX("' . MWB . 'membership/index.php?action=detail&itemID=' . $member_id . '");';
            echo 'parent.$.colorbox.close();';
            echo '</script>';
            exit;
        } else {
            utility::jsToastr('Member Type', __('Gagal menambahkan member type'), 'error');
        }
    } else {
        utility::jsToastr('Member Type', __('Member type sudah terdaftar untuk anggota ini'), 'warning');
        echo '<script type="text/javascript">';
        echo 'parent.$.colorbox.close();';
        echo '</script>';
        exit;
    }
}

// ========== TAMBAHAN: Ambil member types yang belum dimiliki anggota ==========
// Ambil library_id yang sudah dimiliki
$existing_q = $dbs->query("SELECT library_id FROM member_member_type WHERE member_id = '$member_id'");
$existing_libs = array();
while ($row = $existing_q->fetch_assoc()) {
    $existing_libs[] = $row['library_id'];
}

// Query member types yang belum dimiliki
$lib_filter = '';
if (!empty($existing_libs)) {
    $lib_filter = "AND mt.library_id NOT IN (" . implode(',', $existing_libs) . ")";
}
// ========== AKHIR TAMBAHAN ==========

// Query member types
$mtype_q = $dbs->query("SELECT mt.member_type_id, mt.member_type_name, mt.library_id,
                        l.library_code, l.library_name 
                        FROM mst_member_type mt
                        LEFT JOIN mst_library l ON mt.library_id = l.library_id
                        WHERE 1=1 $lib_filter
                        ORDER BY l.library_code ASC, mt.member_type_name ASC");

if ($mtype_q->num_rows == 0) {
    ?>
    <div class="popUpForm">
        <div class="alert alert-info">
            <?php echo __('Tidak ada member type tambahan yang tersedia untuk anggota ini.'); ?>
        </div>
        <script type="text/javascript">
            setTimeout(function() {
                parent.$.colorbox.close();
            }, 2000);
        </script>
    </div>
    <?php
    $content = ob_get_clean();
    require SB.'/admin/'.$sysconf['admin_template']['dir'].'/notemplate_page_tpl.php';
    exit;
}
?>

<div class="popUpForm">
    <form name="mainForm" action="<?php echo $_SERVER['PHP_SELF'] . '?member_id=' . $member_id; ?>" method="post">
        <strong><?php echo __('Tambah Member Type'); ?></strong>
        <hr />
        
        <div class="form-group">
            <label><?php echo __('Member ID'); ?>:</label>
            <strong><?php echo $member_id; ?></strong>
            <input type="hidden" name="member_id" value="<?php echo $member_id; ?>" />
        </div>
        
        <div class="form-group">
            <label><?php echo __('Pilih Member Type'); ?> <span style="color:red;">*</span></label>
            <select name="member_type_id" class="form-control" style="width:100%;">
                <option value="">-- <?php echo __('Pilih Member Type'); ?> --</option>
                <?php
                $grouped = array();
                while ($row = $mtype_q->fetch_assoc()) {
                    $lib_key = 'lib_' . $row['library_id'];
                    if (!isset($grouped[$lib_key])) {
                        $grouped[$lib_key] = array(
                            'label' => $row['library_code'] . ' - ' . $row['library_name'],
                            'options' => array()
                        );
                    }
                    $grouped[$lib_key]['options'][] = array(
                        'id' => $row['member_type_id'],
                        'name' => $row['member_type_name'],
                        'lib_id' => $row['library_id']
                    );
                }
                
                foreach ($grouped as $lib_key => $group) {
                    echo '<optgroup label="' . $group['label'] . '">';
                    foreach ($group['options'] as $opt) {
                        echo '<option value="' . $opt['id'] . '" data-library="' . $opt['lib_id'] . '">' . $opt['name'] . '</option>';
                    }
                    echo '</optgroup>';
                }
                ?>
            </select>
            <small class="text-muted"><?php echo __('Pilih member type untuk perpustakaan yang berbeda'); ?></small>
        </div>
        
        <input type="hidden" name="library_id" id="hidden_library_id" value="" />
        
        <!-- ========== TAMBAHAN: Tombol sesuai alur SLiMS ========== -->
        <div class="form-group" style="margin-top:15px;">
            <!-- Tombol Save (Update) - akan aktif setelah klik Edit -->
            <input type="submit" name="save" id="btnSave" value="<?php echo __('Tambah Member Type'); ?>" class="s-btn btn btn-primary popUpSubmit" disabled="disabled" />
            <!-- Tombol Edit - untuk enable form -->
            <button type="button" id="btnEdit" class="s-btn btn btn-default" onclick="enableForm()"><?php echo __('Edit'); ?></button>
            <!-- Tombol Batal -->
            <button type="button" onclick="parent.$.colorbox.close();" class="s-btn btn btn-default"><?php echo __('Batal'); ?></button>
        </div>
        <!-- ========== AKHIR TAMBAHAN ========== -->
    </form>
</div>

<script type="text/javascript">
    $(document).ready(function() {
        // Set library_id saat memilih member type
        $('select[name="member_type_id"]').change(function() {
            var lib_id = $(this).find('option:selected').data('library');
            $('#hidden_library_id').val(lib_id);
        });
        
        // Trigger change untuk set default
        $('select[name="member_type_id"]').trigger('change');
        
        // ========== TAMBAHAN: Fungsi enableForm ==========
        window.enableForm = function() {
            // Enable select
            $('select[name="member_type_id"]').prop('disabled', false);
            // Enable save button
            $('#btnSave').prop('disabled', false);
            // Tambah class highlight
            $('#btnSave').addClass('btn-primary');
            // Sembunyikan tombol edit
            $('#btnEdit').hide();
        };
        
        // ========== ALUR SLiMS: Form dimulai disabled ==========
        $('select[name="member_type_id"]').prop('disabled', true);
        // ========== AKHIR TAMBAHAN ==========
        
        // Validasi sebelum submit
        $('form[name="mainForm"]').submit(function(e) {
            var selected = $('select[name="member_type_id"]').val();
            if (!selected || selected === '') {
                alert('<?php echo __('Silakan pilih member type terlebih dahulu'); ?>');
                e.preventDefault();
                return false;
            }
            return true;
        });
    });
</script>

<?php
$content = ob_get_clean();
// include the page template
require SB.'/admin/'.$sysconf['admin_template']['dir'].'/notemplate_page_tpl.php';