
<style>
input[type="search"]:focus {
    outline: none;
}
.dataTables_filter {
    float: left !important;
}
.card-header{
    box-shadow: 0 .125rem .25rem rgba(0,0,0,.075)!important;
}
.required label:after {
    color: #e32;
    content: ' *';
    display: inline;
}
.btn-default {
    border: none;
    background: none;
    border-radius: 50%;
}
.dataTables_length{
    padding-top: 0.73em;
}
div.dataTables_filter{
    padding-bottom: 0.7em;
}
.table-hover tbody tr:hover td {
    background: #F8F8F8;
}
.card-header{
    box-shadow: 0 .125rem .25rem rgba(0,0,0,.075)!important;
}
#cancle{
    margin-right: 10px;
    border-color: #A79E9E;
}
div.dataTables_wrapper div.dataTables_info{
  	margin-left: -13px;
}
input[type="search"]{
 	width: 250px !important;
}
</style>
<div class="content-wrapper h-100">
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
            </div>
        </div>
    </div>
    <div class="content">
        <div class="container-fluid">
            <div class="card card-outline card-primary">
                <div class="card-header">
                    <h1 class="card-title"><b>ป้ายกำกับ</b></h1>
                </div>
                <div class="card-body">
					<div id="create_table">

					</div>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="tag_modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
			<div class="modal-content">
			</div>
    </div>
</div>
<template id="tag_modal_template">
	<div class="modal-header">
		<h5 class="modal-title"><b class="modal-title-bold"></b></h5>
		<button type="button" class="close" data-dismiss="modal" aria-label="Close">
			<span aria-hidden="true">&times;</span>
		</button>
	</div>
	<div class="modal-body">
			<div class="form-group required">
				<label for="recipient-name" class="col-form-label">ชื่อป้ายกำกับ</label>
				<input type="text" class="form-control" id="tag_name" size="50" required autocomplete="off" maxlength='50'>
				<div class="invalid-feedback">&nbsp; กรุณาป้อนข้อมูล</div>
			</div>
	</div>
	<div class="modal-footer">
		<button type="button" style="background-color:white;border-color:#A79E9E" class="btn float-right" data-dismiss="modal" >ยกเลิก</button>
		<button type="button" id="submit" class="btn float-right" style="color: white;">บันทึก</button>
	</div>
</template>

<script>
$(document).ready(function() {
    get_tag();
});

function get_tag() {
    $.ajax({
        type: 'get',
        url: "<?php echo site_url() . '/Tag/get_tag'; ?>",
        dataType: 'json',
        success: function(data) {
            create_table(data.tag);
			html_code = ' <a type="button" onclick="open_modal(null)"  id="submit" class="btn btn=info float-right" style="color:white"><i class="fas fa-plus"></i> เพิ่มป้ายกำกับ</a>'
			$("#myTable_filter").after(html_code);
        }
    })
}

function create_table(data) {
	let html_code = '';
	html_code += '<table class="table table-bordered table-hover" id="myTable">';
	html_code +='<thead>';
	html_code +='<tr class="table-heading">';
	html_code +='<th style="text-align:left" width="3%">#</th>';
	html_code +='<th style="text-align:left">ชื่อป้ายกำกับ</th>';
	html_code +='<th style=text-align:center width="20%">สถานะ</th>';
	html_code +='<th width="15%">จัดการ</th>';
	html_code +='</tr>';
	html_code +='</thead>';
	html_code +='<tbody id="mybody">';
	data.forEach((row, index) => {
		html_code += '<tr>';
		html_code += '<td class="text-center">'+(index + 1)+'</td>';
		html_code += '<td style="padding-left:19px">'+row.name+'</td>';
		html_code += '<td style="text-align:center">';
		if (row.status == 1) {
            html_code += '<div class="custom-switch custom-switch-label custom-switch-sm pl-0">';
            html_code += '<input class="custom-switch-input" id="' + row.tag_id +'" type="checkbox" onchange="update_status(' + row.tag_id + ',' + row.status + ')" checked>';
            html_code += '<label class="custom-switch-btn" for="' + row.tag_id + '"></label>';
            html_code += '</div>';
        } else if (row.status == 0) {
            html_code += '<div class="custom-switch custom-switch-label custom-switch-sm pl-0">';
            html_code += '<input class="custom-switch-input" id="' + row['qp_id'] +'" type="checkbox" onchange="update_status(' + row.tag_id+ ',' + row.status + ')" >';
            html_code += '<label class="custom-switch-btn" for="' + row['qp_id'] + '"></label>';
            html_code += '</div>';
        }
		html_code += '</td>';
		html_code += '<td class="text-center">';
		html_code += '<button type="button" title="แก้ไข" class="btn btn-default edit" onclick="open_modal('+row.tag_id+ ',\'' + row.name +'\')"><i class="fas fa-edit"></i></button>';
		html_code += '<button type="button" title="ลบ" class="btn btn-default delete" onclick="delete_tag('+row.tag_id+')"><i class="fas fa-trash-alt"></i></button>';
		html_code += '</td>';
	});
	html_code +='</tbody>';
	html_code +='</table>';
	$('#create_table').html(html_code);
	convert_to_datatable('myTable')
    $(".dataTables_length").css('clear', 'none');
    $(".dataTables_length").css('margin-right', '20px');
    $(".dataTables_info").css('clear', 'none');
    $(".dataTables_info").css('padding-top', '1');
	oTable = $('#myTable').DataTable();   //pay attention to capital D, which is mandatory to retrieve "api" datatables' object, as @Lionel said
	$('#myInput').keyup(function(){
		oTable.search($(this).val()).draw() ;
	})
}

function open_modal(id, name){
	const content = document.querySelector('.modal-content')
    content.innerHTML = ''
	const template = document.getElementById('tag_modal_template')
	const template_clone = template.content.cloneNode(true);

	const input_name = template_clone.querySelector("#tag_name")
	if(id == null){
		template_clone.querySelector('.modal-title-bold').innerText = 'เพิ่มป้ายกำกับ'
		template_clone.querySelector('#submit').addEventListener('click', function(){ 
			const name = input_name.value.trim()
			insert_tag(name)
        })
	}else{
		template_clone.querySelector('.modal-title-bold').innerText = 'แก้ไขป้ายกำกับ'
		input_name.value = name
		template_clone.querySelector('#submit').addEventListener('click', function(){ 
			const name = input_name.value
			update_tag(id ,name)
        })
	}
	content.appendChild(template_clone)
	$('#tag_modal').modal('show')
}

function delete_tag(id) {
    Swal.fire({
        title: ' คุณยืนยันที่จะลบป้ายกำกับหรือไม่',
        text: "",
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#3177ce',
        cancelButtonColor: ' white ',
        confirmButtonText: 'ใช่',
        cancelButtonText:  '<Font color=black> ไม่ <Font>',
        reverseButtons: true
    }).then((result) => {
        //Start delete tag
        if (result.value) {
            $.ajax({
                type: 'post',
                url: "<?php echo site_url().'/Tag/delete_tag'; ?>",
                data: {
                    'id': id
                },
                dataType: 'json',
                success: async function(data) {
                    if (data['message'] == true) {
                        Toast.fire({
                            icon: 'success',
                            title: 'ลบข้อมูลสำเร็จ',
                        });
                        await get_tag();
                    } 
                    else {
                        Toast.fire({
                            icon: 'error',
                            title: 'ลบข้อมูลไม่สำเร็จ',
                        });
                    } 
                }
            });
        }
    })
    $(".swal2-cancel").css("border", "1px solid #A79E9E");
}


function insert_tag(name) {
	if(name == '' || name == null){
		$('input[type=text]').attr('class','form-control is-invalid');
		Toast.fire({
			icon: 'error',
			title: 'กรุณากรอกข้อมูล',
		})
	}else{
		Swal.fire({
			title: ' คุณยืนยันที่จะเพิ่มป้ายกำกับหรือไม่',
			text: "",
			icon: 'question',
			showCancelButton: true,
			confirmButtonColor: '#3177ce',
			cancelButtonColor: ' white ',
			confirmButtonText: 'ใช่',
			cancelButtonText:  '<Font color=black> ไม่ <Font>',
			reverseButtons: true
		}).then((result) => {
			//Start delete tag
			if (result.value) {
				$.ajax({
					type: 'post',
					url: "<?php echo site_url().'/Tag/insert_tag'; ?>",
					data: {
						'name': name.trim()
					},
					dataType: 'json',
					success: async function(data) {
						if (data['message'] == true) {
							Toast.fire({
								icon: 'success',
								title: 'เพิ่มข้อมูลสำเร็จ',
							});
							await get_tag();
							$('#tag_modal').modal('hide')
						} 
						else {
							Toast.fire({
								icon: 'error',
								title: 'เพิ่มข้อมูลไม่สำเร็จ',
								text: 'ชื่อป้ายกำกับซ้ำกับข้อมูลในระบบ'
							});
						} 
					}
				});
			}
		})
		$(".swal2-cancel").css("border", "1px solid #A79E9E");
	}
}

function update_tag(id, name) {
	if(name == '' || name == null){
		$('input[type=text]').attr('class','form-control is-invalid');
		Toast.fire({
			icon: 'error',
			title: 'กรุณากรอกข้อมูล',
		})
	}else{
		Swal.fire({
			title: ' คุณยืนยันที่จะแก้ไขป้ายกำกับหรือไม่',
			text: "",
			icon: 'question',
			showCancelButton: true,
			confirmButtonColor: '#3177ce',
			cancelButtonColor: ' white ',
			confirmButtonText: 'ใช่',
			cancelButtonText:  '<Font color=black> ไม่ <Font>',
			reverseButtons: true
		}).then((result) => {
			//Start delete tag
			if (result.value) {
				$.ajax({
					type: 'post',
					url: "<?php echo site_url().'/Tag/update_tag'; ?>",
					data: {
						'id': id,
						'name': name.trim(),
					},
					dataType: 'json',
					success: async function(data) {
						if (data['message'] == true) {
							Toast.fire({
								icon: 'success',
								title: 'แก้ไขข้อมูลสำเร็จ',
							});
							await get_tag();
							$('#tag_modal').modal('hide')
						} 
						else {
							Toast.fire({
								icon: 'error',
								title: 'แก้ไขข้อมูลไม่สำเร็จ',
								text: 'ชื่อป้ายกำกับซ้ำกับข้อมูลในระบบ'
							});
						} 
					}
				});
			}
		})
		$(".swal2-cancel").css("border", "1px solid #A79E9E");
	}
}

function update_status(id, status) {
	$.ajax({
		type: 'post',
		url: "<?php echo site_url().'/Tag/change_status'; ?>",
		data: {
			'id': id,
			'status': status == 0 ? 1 : 0
		},
		dataType: 'json',
		success: async function(data) {
			if (data['message'] == true) {
				Toast.fire({
					icon: 'success',
					title: 'อัพเดทสถานะสำเร็จ',
				});
				await get_tag();
				$('#tag_modal').modal('hide')
			} 
			else {
				Toast.fire({
					icon: 'error',
					title: 'อัพเดทสถานะไม่สำเร็จ',
				});
			} 
		}
	});
    
}


</script>


