<?= form_open('', 'id="form_rekam_menu"', ['id_rm' => $id_rm]) ?>
	<div class="modal-body">
		<div class="row">
			<div class="col-sm-6">
	            <div class="form-group" id="fgr_nama_group">
                    <label class="control-label" for="nama_group">Nama Role:</label>
                    <select class="form-control select2" id="group_idx" name="group_id">
                    	<option>Pilih Group...</option>
                    	<?php foreach ($dd_groups as $k) { ?>
                    	<option value="<?= $k->id_group ?>" data-id_modul="<?= $k->id_modul ?>" data-nama_modul="<?= $k->nama_modul ?>"><?= $k->nama_group ?></option>
                    	<?php } ?>
                    </select>
                </div>
	        </div>
	        <div class="col-sm-6">
	        	<div class="form-group" id="fgr_nama_group">
                    <label class="control-label" for="nama_group">Nama Modul:</label>
                    <input type="text" id="nama_modul" value="" class="form-control rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent" placeholder="Nama Modul" disabled>
                </div>
	        </div>
		</div><hr>
		<div class="table-responsive">
            <table id="tb-menux" class="table table-bordered">
                <thead>
                    <tr>
                        <th width="70" class="text-center">NO.</th>
                        <th width="300">MENU</th>
                        <th class="text-center">PARENT</th>
                        <th class="text-center">REKAM</th>
                        <th class="text-center">UBAH</th>
                        <th class="text-center">HAPUS</th>
                        <th class="text-center">EXPORT</th>
                        <th class="text-center" width="100">AKSI</th>
                    </tr>
                </thead>
                <tbody>
                    
                </tbody>
            </table>
        </div>
        <hr/>
	</div>
	<div class="modal-footer">
		<button type="button" class="btn btn-secondary waves-effect waves-themed" data-dismiss="modal">Close</button>
      	<button type="submit" id="btn_rekam_menu" class="btn btn-primary waves-effect waves-themed">
         	Save Changes
      	</button>
   </div>
</form>

<script type="text/javascript">
	$('.select2').select2({
        dropdownCssClass:'increasezindex'
    });

    $('#group_idx').on('change', function() {
        var nama_modul = $(this).find(':selected').data('nama_modul');
        $('#nama_modul').val(nama_modul || '');

        //ambil data menu yg belum ada
        var id_group = $(this).val();
        var id_modul = $(this).find(':selected').data('id_modul');

        if (id_group) {
        	$.ajax({
                url: '<?= base_url('admin/rolegroup/get_related_menu2') ?>',
                type: "post",
                dataType: 'json',
                data: {
                	id_group: id_group,
                    id_modul: id_modul,
                    "<?= csrf_token() ?>": "<?= csrf_hash() ?>",
                },
                error: function (xhr, status, message) {
                    $.messager.alert(status,message,'warning');
                },
                success: function(res) {
                    // Bersihkan tbody sebelum menambahkan data baru
                	$('#tb-menux tbody').empty();

                	// Cek apakah data kosong
				    if (res.length === 0) {
				        // Jika kosong, tambahkan row dengan pesan "TIDAK ADA DATA"
				        var emptyRow = `<tr>
				            <td colspan="8" class="text-center">SEMUA MENU SUDAH DITAMBAHKAN KE ROLE INI</td>
				        </tr>`;
				        $('#tb-menux tbody').append(emptyRow);
				    } else {
	                	// Loop data yang didapat dari response dan tambahkan ke tbody
		                $.each(res, function(index, item) {
		                    // Buat row baru untuk setiap item yang ada di response
		                    var row = `<tr>
		                        <td class="text-center">${index + 1}</td>
		                        <td>${item.nama_menu}</td>
	                            <td class="text-center">${item.id_parent}</td>
	                            <td class="text-center"><input type="checkbox" name="rekamx_${item.id_menu}" value="1"></td>
	                            <td class="text-center"><input type="checkbox" name="ubahx_${item.id_menu}" value="1"></td>
	                            <td class="text-center"><input type="checkbox" name="hapusx_${item.id_menu}" value="1"></td>
	                            <td class="text-center"><input type="checkbox" name="expx_${item.id_menu}" value="1"></td>
	                            <td class="text-center">
	                                <button type="button" class="btn btn-danger btn-delete btn-xs" data-id="${item.id_menu}"><i class="fal fa-trash"></i></button>
	                            </td>
		                    </tr>`;

		                    // Tambahkan row baru ke dalam tbody
		                    $('#tb-menux tbody').append(row);
		                });
		            }

	                $('.btn-delete').on('click', function() {
                        // Menghapus baris dari tabel
                        $(this).closest('tr').remove();
                    });
                }
            });
        }
    });

    //SUBMIT
    $('#form_rekam_menu').on('submit', function(e) {
        e.preventDefault(); // Mencegah submit form secara langsung

        // Ambil semua data form yang sudah ada
        let formData = $(this).serialize(); 

        // Tambahkan data tabel dinamis ke formData
        $('#tb-menux tbody tr').each(function(index) {
            let id_menu = $(this).find('input[name^="rekamx_"]').attr('name').split('_')[1];
            let rekam = $(this).find(`input[name="rekamx_${id_menu}"]`).is(':checked') ? 1 : 0;
            let ubah = $(this).find(`input[name="ubahx_${id_menu}"]`).is(':checked') ? 1 : 0;
            let hapus = $(this).find(`input[name="hapusx_${id_menu}"]`).is(':checked') ? 1 : 0;
            let exp = $(this).find(`input[name="expx_${id_menu}"]`).is(':checked') ? 1 : 0;

            // Tambahkan data dinamis secara manual ke formData
            // Tambahkan data dinamis ke formData
	        formData += `&data_tabel[${index}][id_menu]=${id_menu}`;
            formData += `&data_tabel[${index}][rekam]=${rekam}`;
            formData += `&data_tabel[${index}][ubah]=${ubah}`;
            formData += `&data_tabel[${index}][hapus]=${hapus}`;
            formData += `&data_tabel[${index}][exp]=${exp}`;
        });

        // Kirim data ke server melalui AJAX
        $.ajax({
            url: '<?= $action ?>',
            type: 'post',
            dataType: 'json',
            data: formData,
            beforeSend  : function() {
                $(".form-group").removeClass("has-error");
                $(".error-message").html('').hide();
                BtnLoading($("#btn_rekam_menu"));
            },
            success: function(res) {
                toastr.success(res.message, 'Updated!!', {timeOut: 3000});
                $('#modal-add-rm').modal('hide');
                $('#datagrid_rolemenu').datagrid('load');
            },
            error: function(xhr, status, error) {
                console.error('Error: ' + error);
                alert('Terjadi kesalahan saat menyimpan data.');
            },
            complete: function() {
                BtnReset($("#btn_rekam_menu"));
            }
        });
    });
    //END TAMBAH MENU -----------
</script>