
<style>
.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;
}
.profile-pic-wrapper {
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.pic-holder {
    text-align: center;
    position: relative;
    width: 200px;
    height: 200px;
    overflow: hidden;
    /*   display: flex; */
    justify-content: center;
    align-items: center;
    margin-bottom: 20px;
	border-color: black;
	border-style: solid;
  	border-width: thin;
}

.pic-holder .pic {
  height: 100%;
  width: 100%;
  -o-object-fit: cover;
  object-fit: cover;
  -o-object-position: center;
  object-position: center;
}

.pic-holder .upload-file-block,
.pic-holder .upload-loader {
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    background-color: rgba(90, 92, 105, 0.7);
    color: #f8f9fc;
    font-size: 12px;
    font-weight: 600;
    opacity: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
    border: 10px black;
}

.pic-holder .upload-file-block {
    cursor: pointer;
}

.pic-holder:hover .upload-file-block {
    opacity: 1;
}

.pic-holder.uploadInProgress .upload-file-block {
    display: none;
}

.pic-holder.uploadInProgress .upload-loader {
    opacity: 1;
}
</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 class="profile-pic-wrapper">
            </div>
                </div>
                <div class="card-body">
					<table class="table table-bordered table-hover" id="myTable">
    					<thead>
    						<tr>
								<th width="5%">#</th>
								<th style="text-align: left";>ชื่ออาจารย์ที่ปรึกษา</th>
    							<th width="15%">จัดการ</th>
    						</tr>
    					</thead>
    					<tbody id="mybody">
							
						</tbody>
					</table>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="instructor_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="instructor_template">
	<td class="text-center index"></td>
	<td class="name" style="padding-left:19px"></td>
	<td  class="text-center">
		<button type="button" title="แก้ไข" class="btn btn-default edit"><i class="fas fa-edit"></i></button>
		<button type="button" title="ลบ" class="btn btn-default delete"><i class="fas fa-trash-alt"></i></button>
	</td>
</template>
<template id="instructor_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="instructor_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_instructor();
});


function get_instructor() {
    $.ajax({
        type: 'get',
        url: "<?php echo site_url() . '/Instructor/get_instructor'; ?>",
        data: {

        },
        dataType: 'json',
        success: function(data) {
            create_table(data.instructor);
			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) {
	$('#myTable').DataTable().destroy();;
	const table = document.querySelector("#myTable tbody")
    table.innerHTML = ''
	const template = document.getElementById("instructor_template");
    data.forEach((row, index) => {
		const tr = document.createElement("tr")
		const template_clone = template.content.cloneNode(true);
		template_clone.querySelector('.index').innerText = index+1
		template_clone.querySelector('.name').innerText = row.name
		template_clone.querySelector('.edit').addEventListener('click', function(){ open_modal(row) })
		template_clone.querySelector('.delete').addEventListener('click', function(){ delete_instructor(row.instructor_id) })
		tr.appendChild(template_clone);
		table.appendChild(tr);
    });
	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');
}

function open_modal(row){
	const content = document.querySelector('.modal-content')
    content.innerHTML = ''
	const template = document.getElementById('instructor_modal_template')
	const template_clone = template.content.cloneNode(true);
	const input_name = template_clone.querySelector("#instructor_name")
	if(row == null){
		template_clone.querySelector('.modal-title-bold').innerText = 'เพิ่มอาจารย์ที่ปรึกษา'
		template_clone.querySelector('#submit').addEventListener('click', function(){ 
			const name = input_name.value.trim()
			insert_instructor(name)
        })
	}else{
		template_clone.querySelector('.modal-title-bold').innerText = 'แก้ไขอาจารย์ที่ปรึกษา'
		input_name.value = row.name
		template_clone.querySelector('#submit').addEventListener('click', function(){ 
			const name = input_name.value
			update_instructor(row.instructor_id ,name)
        })
	}
	content.appendChild(template_clone)
	$('#instructor_modal').modal('show')
}

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

function insert_instructor(name) {
	if(name == '' || name == null){
		$('input').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().'/instructor/insert_instructor'; ?>",
					data: {
						'name': name,
					},
					dataType: 'json',
					success: async function(data) {
						if (data['message'] == true) {
							Toast.fire({
								icon: 'success',
								title: 'เพิ่มข้อมูลสำเร็จ',
							});
							await get_instructor();
							$('#instructor_modal').modal('hide')
						} 
						else {
							Toast.fire({
								icon: 'error',
								title: 'เพิ่มข้อมูลไม่สำเร็จ',
								text: 'ชื่ออาจารย์ที่ปรึกษาซ้ำกับข้อมูลในระบบ'
							});
						} 
					}
				});
			}
		})
		$(".swal2-cancel").css("border", "1px solid #A79E9E");
	}
}

function update_instructor(id,name) {
	if(name == '' || name == null){
		$('input').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) => {
			if (result.value) {
				$.ajax({
					type: 'post',
					url: "<?php echo site_url().'/instructor/update_instructor'; ?>",
					data: {
						'id': id,
						'name': name,
					},
					dataType: 'json',
					success: async function(data) {
						if (data['message'] == true) {
							Toast.fire({
								icon: 'success',
								title: 'แก้ไขข้อมูลสำเร็จ',
							});
							await get_instructor();
							$('#instructor_modal').modal('hide')
						} 
						else {
							Toast.fire({
								icon: 'error',
								title: 'แก้ไขข้อมูลไม่สำเร็จ',
								text: 'ชื่ออาจารย์ที่ปรึกษาซ้ำกับข้อมูลในระบบ'
							});
						} 
					}
				});
			}
		})
		$(".swal2-cancel").css("border", "1px solid #A79E9E");
	}
}

</script>


