<style>
input[type="search"]:focus {
    outline: none;
}
input[type="search"]{
  border-radius: 3px;
  border: 1px solid #aaa;
  width: 250px;
}

.dataTables_filter {
  float: left !important;
}
.btn-default{
    border: none;
    background: none;
    border-radius: 50%;
}
select#status{
  border:0px;
  outline:0px;
  width: 190px;
  text-align:center;
}
.dataTables_length{
  padding-top: 0.73em;
}
.table-hover tbody tr:hover td {
  background: #F8F8F8;
}
.card-header{
    box-shadow: 0 .125rem .25rem rgba(0,0,0,.075)!important;
}
div.dataTables_wrapper div.dataTables_info{
  margin-left: -13px;
}
div#filler {
    padding-bottom: 0.7em;
}
select#yearfiller{
    display: inline;
    width: 150px;
  }
select#graduationfiller{
    display: inline;
    width: 100px;
}
.dataTables_filter{ 
  display: none; 
}
option { 
  text-align: left; 
}
.required label:after {
    color: #e32;
    content: ' *';
    display: inline;
    /* font-weight: bold; */
}
</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">
				<a type="button" href="<?php echo site_url() . "/Project/show_project_create"; ?>"  id="submit" class="btn btn=info float-right" style="color:white"><i class="fas fa-plus"></i> เพิ่มโปรเจกต์</a>
				<div id="filler">ค้นหา : <input id="myInput" type="search" onsearch="OnSearch()" size="4">
					&nbsp;&nbsp;ปี :
					<select id="yearfiller" onchange="year_filter()" class="form-control">
						<option value="">ทั้งหมด</option>
					</select>
					&nbsp;&nbsp;ชั้นปี :
					<select id="graduationfiller" onchange="graduation_filter()" class="form-control">
						<option value="">ทั้งหมด</option>
						<option value="2">2</option>
						<option value="3">3</option>
						<option value="4">4</option>
					</select>
				</div>
					<table class="table table-bordered table-hover" id="myTable">
    					<thead>
    						<tr>
								<th width="5%">#</th>
								<th style="text-align: left"; >ชื่อโปรเจกต์</th>
								<th style="text-align: left"; width="5%">ปี</th>
								<th style="text-align: left"; width="10%">ชั้นปี</th>
								<th style="text-align: center"; width="15%">สถานะ</th>
    							<th width="15%">จัดการ</th>
    						</tr>
    					</thead>
    					<tbody id="mybody">
							
						</tbody>
					</table>
                </div>
            </div>
        </div>
    </div>
</div>
<template id="project_template">
	<td class="text-center index"></td>
	<td class="name" style="padding-left:19px"></td>
	<td class="year" style="padding-left:19px"></td>
	<td class="graduation" style="padding-left:19px"></td>
	<td class="status text-center">
		<div class="custom-switch custom-switch-label custom-switch-sm pl-0">
         	<input class="custom-switch-input" id="" type="checkbox">
           	<label class="custom-switch-btn" for=""></label>
        </div>
	</td>
	<td  class="text-center">
		<a type="button" title="ดู" class="btn btn-default view" w><i class="fas fa-search"></i></a>
		<button type="button" title="แก้ไข" class="btn btn-default edit"><i class="fas fa-edit"></i></button>
	</td>
</template>

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

function get_project() {
    $.ajax({
        type: 'get',
        url: "<?php echo site_url() . '/Project/get_project'; ?>",
        dataType: 'json',
        success: function(data) {
            create_table(data.project);
			create_option_year(data.year)
		}
    })
}

function create_table(data) {
	$('#myTable').DataTable().destroy();;
	const table = document.querySelector("#myTable tbody")
    table.innerHTML = ''
	const template = document.getElementById("project_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_th;
		template_clone.querySelector('.year').innerText = row.date;
		let graduation 
		if(row.cluster_id != 0){
			graduation = 2
		}else if(row.team_id != 0){
			graduation = 3
		}else{
			graduation = 4
		}
		template_clone.querySelector('.graduation').innerText =  graduation
		template_clone.querySelector('.custom-switch-input').checked = row.status == 1 ? true : false
		template_clone.querySelector(".custom-switch-input").setAttribute('id', `status${row.project_id}`)
		template_clone.querySelector(".custom-switch-btn").setAttribute('for', `status${row.project_id}`)
		template_clone.querySelector(".custom-switch-input").addEventListener('change', function(){ 
			update_status(row.project_id, row.status)
		})
		template_clone.querySelector('.edit').addEventListener('click', function(){ window.location.href = '<?php echo site_url().'/Project/show_project_edit/';?>'+row.project_id })
		template_clone.querySelector('.view').addEventListener('click', function(){ window.open('<?php echo site_url().'/General/show_select/';?>'+row.project_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 create_option_year(data){
	let selectList = document.querySelector('#yearfiller')
	data.forEach((row, index) => {
		option = document.createElement("option")
		option.setAttribute("value", row.date)
		option.text = row.date
		selectList.appendChild(option)
	})
}

function year_filter(){
	//Get a reference to the new datatable
	var table = $('#myTable').DataTable();
	
	var categoryIndex = 0;
	$("#myTable th").each(function (i) {
	if ($($(this)).html() == "Year") {
		categoryIndex = i; return false;
	}
	});
	//Use the built in datatables API to filter the existing rows by the Category column
	$.fn.dataTable.ext.search.push(
	function (settings, data, dataIndex) {
		var selectedItem = $('#yearfiller').val()
		var text = data[categoryIndex];
		var category = text;
		if (selectedItem === "" || category.includes(selectedItem)) {
		return true;
		}
		return false;
	}
	);
	
	$("#statusfiller").change(function (e) {
	table.draw();
	});
	table.draw();
}

function graduation_filter(){
	//Get a reference to the new datatable
	var table = $('#myTable').DataTable();
	var categoryIndex = 0;
	$("#myTable th").each(function (i) {
	if ($($(this)).html() == "Graduation") {
		categoryIndex = i; return false;
	}
	});
	//Use the built in datatables API to filter the existing rows by the Category column
	$.fn.dataTable.ext.search.push(
	function (settings, data, dataIndex) {
		var selectedItem = $('#graduationfiller').val()
		var text = data[categoryIndex].substring(0, 1);
		if(text == '2'){
			text = '2';
		}else if(text == '3'){
			text = '3';
		}else if(text == '4'){
			text = '4';
		}
		var category = text;

		if (selectedItem === "" || category.includes(selectedItem)) {
		return true;
		}
		return false;
	}
	);
	
	$("#statusfiller").change(function (e) {
	table.draw();
	});
	table.draw();
}

function OnSearch(){
	oTable = $('#myTable').DataTable();  
	oTable.search('').draw(); 
}

function update_status(id, status) {
	$.ajax({
		type: 'post',
		url: "<?php echo site_url().'/Project/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_project()
			} 
			else {
				Toast.fire({
					icon: 'error',
					title: 'อัพเดตสถานะไม่สำเร็จ',
				});
			} 
		}
	});
}

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');
</script>


