<style>
/* Snackbar css */
.snackbar {
	visibility: hidden;
	min-width: 250px;
	background-color: #333;
	color: #fff;
	text-align: center;
	padding: 16px;
	position: fixed;
	z-index: 1;
	left: 50%;
	bottom: 30px;
	font-size: 14px;
	transform: translateX(-50%);
}

.snackbar.show {
	visibility: visible;
	-webkit-animation: fadein 0.5s, fadeout 0.5s 2.5s;
	animation: fadein 0.5s, fadeout 0.5s 2.5s;
}
.required label:after {
    color: #e32;
    content: ' *';
    display: inline;
    /* font-weight: bold; */
}
.select2-container--default .select2-selection--multiple .select2-selection__choice{
    color: black !important;
}
.add-detail{
	background-color:#3177ce;
	position: sticky;
    top: 70px;
}
.add-tag{
	padding: 6px !important;
	height: 20px;
	display: inline-table;
}
label{
	font-weight: 400 !important; 
}
.filepond--credits{
	font-size: 0 !important;
}
.filepond {
  	margin-left: auto;
	margin-right: auto;
}
.profile .filepond--root {
	width: 170px;
	margin: 0 auto;
}
/* .select2-selection__rendered {
    line-height: 31px !important;
} */
.select2-container .select2-selection--single {
    height: 35px !important;
}
/* .select2-selection__arrow {
    height: 34px !important;
} */
.required label:after {
    color: #e32;
    content: ' *';
    display: inline;
    /* font-weight: bold; */
}
textarea  { 
	height: 150px !important;
}
[type=radio] { 
  position: absolute;
  opacity: 0;
  width: 0;
  height: 0;
}

/* IMAGE STYLES */
[type=radio] + img {
  cursor: pointer;
}

/* CHECKED STYLES */
[type=radio]:checked + img {
  outline: 2px solid #f00;
}
.check_template{
	border: 1px solid black;
}
</style>
<div class="content-wrapper h-100">
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-left">
                        <a class="breadcrumb-item " href='<?php echo site_url().'/Project/show_project_manage_user';?>'>โปรเจกต์</a>
                        <li class="breadcrumb-item active">แก้ไขโปรเจกต์</li>
                    </ol>
                </div>
            </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 class="form-body">
						<div class="row p-t-20 center">
							<div class="col-md-3 required">
								<div class="form-group has-success">
									<label class="form-label">ปี </label>
									<input type="text" class="form-control" name="datepicker" id="datepicker" value="<?php echo $project->date ?>" />
								</div>
							</div>
							<?php 
								$project->cluster_id != 0 ? $year2 = 'selected' : $year2 = '';
								$project->team_id != 0 ? $year3 = 'selected' : $year3 = '';
								$project->instructor_id != 0 ? $year4 = 'selected' : $year4 = '';
							?>
							<div class="col-md-3 required">
								<div class="form-group">
									<label class="form-label">ชั้นปี </label>
									<select class="form-control select-require" id="graduation" onchange="check_graduation()">
										<option value="2" <?php echo $year2; ?>>2</option>
										<option value="3" <?php echo $year3; ?>>3</option>
										<option value="4" <?php echo $year4; ?>>4</option>
									</select>
								</div>
							</div>
							<div class="col-md-6 required" id="cluster">
								<div class="form-group">
									<label class="form-label">มกุล </label>
									<select class="form-control select-require" id="cluster_select">
										<option value="" selected disabled></option>
										<?php foreach($clusters as $cluster){ ?>
											<option value="<?php echo $cluster->cluster_id ?>" <?php echo $cluster->cluster_id == $project->cluster_id ? 'selected' : '' ?>><?php echo $cluster->name ?></option>
										<?php } ?>
									</select>
								</div>
							</div>
							<div class="col-md-6 required" id="team">
								<div class="form-group">
									<label class="form-label">ทีม </label>
									<select class="form-control select-require" id="team_select">
										<option value="" selected disabled></option>
										<?php foreach($teams as $team){ ?>
											<option value="<?php echo $team->team_id ?>" <?php echo $team->team_id == $project->team_id ? 'selected' : '' ?>><?php echo $team->name ?></option>
										<?php } ?>
									</select>
								</div>
							</div>
							<div class="col-md-6 required" id="instructor">
								<div class="form-group">
									<label class="form-label">อาจารย์ที่ปรึกษา </label>
									<select class="form-control select-require" id="instructor_select">
										<option value="" selected disabled></option>
										<?php foreach($instructors as $instructor){ ?>
											<option value="<?php echo $instructor->instructor_id ?>" <?php echo $instructor->instructor_id == $project->instructor_id ? 'selected' : '' ?>><?php echo $instructor->name ?></option>
										<?php } ?>
									</select>
								</div>
							</div>
						</div>
						<div class="row p-t-20 center">
							<div class="col-md-6 required">
								<div class="form-group has-success">
									<label class="form-label">บริษัท/สำนักงาน </label>
									<select class="form-control select-require" id="company">
										<option value="" selected disabled></option>
										<?php foreach($companies as $company){ ?>
											<option value="<?php echo $company->company_id ?>" <?php echo $company->company_id == $project->company_id ? 'selected' : '' ?>><?php echo $company->name ?></option>
										<?php } ?>
									</select>
								</div>
							</div>
							<div class="col-md-6 required">
								<div class="form-group has-success">
									<label class="form-label">หมวดหมู่ </label>
									<select class="js-example-basic-multiple form-control" name="states[]" multiple="multiple" id="muti">   
											<?php foreach($tags as $tag){ ?>   
												<?php foreach($project_tag as $pt){ ?>   
													<option value="<?php echo $tag->tag_id ?>" <?php echo $tag->tag_id == $pt->tag_id ? 'selected' : '' ?>><?php echo $tag->name ?></option> 
												<?php } ?>
											<?php } ?>
									</select>            
								</div>
							</div>
							</label>
							<br>
						</div>
						<div class="row p-t-20 center">
							<div class="col-md-6 required">
								<div class="form-group has-success">
									<label class="form-label">ชื่อโปรเจกต์/โครงงาน/โครงการ (TH) </label>
									<input type="text" class="form-control" id="project_name" value="<?php echo $project->name_th ?>">
								</div>
							</div>
							<div class="col-md-6">
								<div class="form-group has-success">
									<label class="form-label">ชื่อโปรเจกต์/โครงงาน/โครงการ (EN)/label>
									<input type="text" class="form-control" id="project_name_en" value="<?php echo $project->name_en ?>">
								</div>
							</div>
						</div>
						<div class="card card-outline card-primary">
							<div class="card-header" id="headadd_detail">
								<h1 class="card-title"><b>รูปภาพโปรไฟล์ & พื้นหลัง</b> <span data-toggle="tooltip" data-html="true" title="รูปภาพโปรไฟล์ควรมีขนาดไม่เกิน 200x200 รูปภาพพื้นหลังควรมีขนาดไม่เกิน 1920x600"><i class="fa fa-question-circle-o" aria-hidden="true"></i></span></h1>
							</div>
							<div class="card-body">
								<div class="row">
									<div class="col-md-4 profile">
										<input type="file" class="filepond" name="filepond-circle" accept="image/png, image/jpeg"/>
									</div>
									<div class="col-md-8">
										<input type="file" class="filepond" name="filepond" accept="image/png, image/jpeg"/>
									</div>
								</div>
							</div>
						</div>
						<div class="card card-outline card-primary">
							<div class="card-header header_detail">
								<h1 class="card-title"><b>รายละเอียด</b></h1>
							</div>
							<div class="card-body">
								<button type="button" class="btn btn-primary float-right add-detail" onclick="show_select_template()"><i class="fas fa-plus-circle"></i> เพิ่ม</button>
								<div class="form-body">
									<div class='row'>
										<div class='col-md-11'>
											<div class="detail_template">
											
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>	
						<div class="card card-outline card-primary">
							<div class="card-header" id="headadd_detail">
								<h1 class="card-title"><b>สมาชิก</b></h1>
							</div>
							<div class="card-body">
								<button type="button" class="btn btn-primary float-right add-detail" onclick="add_member()"><i class="fas fa-plus-circle"></i> เพิ่ม</button>
								<div class="form-body">
									<div class='row'>
										<div class='col-md-11'>
											<div class="row member_template">
											
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>
					<br>
					<button type="button" id="submit" class="btn btn-default float-right" onclick="update_projecct()" style="color:white">บันทึก</button>
					<a type="button" class="btn btn-default float-right" style='margin-right:10px; border-color:#A79E9E;' onclick="cancel_create_project()">ยกเลิก</a>
				</div>
			</div>
		</div>
	</div>
</div>
<div class="modal fade" id="modal_detail" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
		<div class="modal-content">
			<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">
						<div class="row">
								<div class="col">
									<label>
										<input type="radio" name="fav_language" value="1">
										<img src="<?php echo base_url()?>image/template1.jpg" class="check_template" >
									</label>
								</div>
								<div class="col">
									<label>
										<input type="radio" name="fav_language" value="2">
										<img src="<?php echo base_url()?>image/template2.jpg" class="check_template">
									</label>
								</div>
							</div>
							<div class="row">
								<div class="col">
									<label>
										<input type="radio" name="fav_language" value="3">
										<img src="<?php echo base_url()?>image/template3.jpg" class="check_template">
									</label>
								</div>
								<div class="col">
									<label>
										<input type="radio" name="fav_language" value="4">
										<img src="<?php echo base_url()?>image/template4.jpg" class="check_template">
									</label>
								</div>
							</div>
						</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;" onclick="chose_template()">เลือก</button>
			</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 modal-content-tag">
			</div>
    </div>
</div>
<template id="tag_modal_template">
	<div class="modal-header">
		<h5 class="modal-title"><b class="modal-title-bold header-tag"></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" name="tag_name" 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>
<template id="template_1">
	<div class="card">
		<div class="card-body">
			<button type="button" class="close" aria-label="Close"><span aria-hidden="true">&times;</span></button><br><br>
			<div class='row'>
				<div class='col-md-6'>
					<div class="form-group">
						<textarea class="form-control summernote" row="6"></textarea> 
					</div>
				</div>
				<div class='col-md-6'>
					<input type="file" class="filepond" name="filepond1" accept="image/png, image/jpeg"/>
					<input type="file" class="filepond" name="filepond2" accept="image/png, image/jpeg"/>
				</div>
			</div>
		</div>
	</div>
</template>
<template id="template_2">
	<div class="card">
		<div class="card-body">
			<button type="button" class="close" aria-label="Close"><span aria-hidden="true">&times;</span></button><br><br>
			<div class='row'>
				<div class='col-md-6'>
					<input type="file" class="filepond" name="filepond1" accept="image/png, image/jpeg"/>
					<input type="file" class="filepond" name="filepond2" accept="image/png, image/jpeg"/>
				</div>
				<div class='col-md-6'>
					<div class="form-group">
						<textarea class="form-control summernote" row="6"></textarea> 
					</div>
				</div>
			</div>
		</div>
	</div>
</template>
<template id="template_3">
	<div class="card">
		<div class="card-body">
			<button type="button" class="close" aria-label="Close"><span aria-hidden="true">&times;</span></button><br><br>
			<div class='row'>
				<div class='col-md-12'>
					<div class="form-group">
						<textarea class="form-control summernote" row="6"></textarea> 
					</div>
				</div>
			</div>
			<br>
			<div class='row'>
				<div class='col-md-6'>
					<input type="file" class="filepond" name="filepond1" accept="image/png, image/jpeg"/>
				</div>
				<div class='col-md-6'>
					<input type="file" class="filepond" name="filepond2" accept="image/png, image/jpeg"/>
				</div>
			</div>
		</div>
	</div>
</template>
<template id="template_4">
	<div class="card">
		<div class="card-body">
			<button type="button" class="close" aria-label="Close"><span aria-hidden="true">&times;</span></button><br><br>
			<div class='row'>
				<div class='col-md-6'>
					<input type="file" class="filepond" name="filepond1" accept="image/png, image/jpeg"/>
				</div>
				<div class='col-md-6'>
					<input type="file" class="filepond" name="filepond2" accept="image/png, image/jpeg"/>
				</div>
			</div>
			<div class='row'>
				<div class='col-md-12'>
					<div class="form-group">
						<textarea class="form-control summernote" row="6"></textarea> 
					</div>
				</div>
			</div>
		</div>
	</div>
</template>
<template id="template_member">
	<div class="col-md-3">
		<div class="card">
			<div class="card-body">
				<button type="button" class="close" aria-label="Close"><span aria-hidden="true">&times;</span></button><br><br>
				<div class='row'>
					<div class='col-md-12'>
						<input type="file" class="filepond" name="filepond-circle" accept="image/png, image/jpeg"/><br>
					</div>
				</div>
				<div class='row'>
					<div class='col-md-12'>
						<select class="js-example-basic-multiple form-control select-student">
							<option value="" selected disabled></option>
							<?php foreach($users as $user){ ?>แก้ไข
								<option value="<?php echo $user->user_id ?>"><?php echo $user->student_id.' '.$user->first_name.' '.$user->last_name ?></option>
							<?php } ?>
						</select>
					</div>
				</div>
				</div>
			</div>
		</div>
	</div>
</template>
<script>
$(function () {
    $('[data-toggle="tooltip"]').tooltip()
})
$(document).ready(function() {
	$("#datepicker").datepicker({
		format: "yyyy",
		viewMode: "years", 
		minViewMode: "years",
		autoclose: true,
	});  
	$("#muti").select2().on('select2:open', () => {
        $(".select2-results:not(:has(a))").append('<a href="#" class="add-tag" onclick="open_modal_tag()"><i class="fas fa-plus-circle"></i> เพิ่มหมวดหมู่</a>')
	})
	let cluster_id = '<?php echo $project->cluster_id ?>'
	let team_id = '<?php echo $project->team_id ?>'
	let instructor_id = '<?php echo $project->instructor_id ?>'
	if(cluster_id == 0){
		document.getElementById("cluster").style.display = "none"
	}
	if(team_id == 0){
		document.getElementById("team").style.display = "none"
	}
	if(instructor_id == 0){
		document.getElementById("instructor").style.display = "none"
	}

	get_project_detail_member()
});

let all_user = [];

function get_project_detail_member(){
	$.ajax({
        type: 'post',
        url: "<?php echo site_url() . '/Project/get_project_detail_member'; ?>",
        data: {
			'id' : "<?php echo $project->project_id ?>"
        },
        dataType: 'json',
        success: function(data) {
			set_detail(data.detail)
			set_member(data.member, data.users)
			all_user = data.users
		}
    })
}

FilePond.registerPlugin(
	FilePondPluginFileEncode,
	FilePondPluginImageExifOrientation,
	FilePondPluginImagePreview,
	FilePondPluginFileValidateType,
);


const image = document.querySelector('input[name="filepond"]');
const image_circle = document.querySelector('input[name="filepond-circle"]');

let data_result = []
let data_member = []
let index = 0;
let index_member = 0;

const pond_image_circle = FilePond.create(image_circle, {
	files: [
        {
			source: "<?php echo base_url().$project->image_logo ?>",
        },
    ],
	acceptedFileTypes: ['image/png'],
	labelIdle: `<div style="font-size: 40px;"><i class="fa fa-picture-o"></i></div>`,
	imagePreviewHeight: 170,
	imageCropAspectRatio: '1:1',
	imageResizeTargetWidth: 200,
	imageResizeTargetHeight: 200,
	stylePanelLayout: 'compact circle',
	styleLoadIndicatorPosition: 'center bottom',
	styleButtonRemoveItemPosition: 'center bottom',
});

let data_circle
pond_image_circle.on('addfile', (error, file) => {
	data_circle = file.getFileEncodeBase64String()
});
pond_image_circle.on('removefile', (error, file) => {
	data_circle = ''
});

const pond_image_cover = FilePond.create(image, {
	files: [
        {
			source: "<?php echo base_url().$project->image_cover ?>",
        },
    ],
	labelIdle: `<div style="font-size: 40px;"><i class="fa fa-picture-o"></i></div>`,
});
let data_cover
pond_image_cover.on('addfile', (error, file) => {
	data_cover = file.getFileEncodeBase64String()
});
pond_image_cover.on('removefile', (error, file) => {
	data_cover = ''
});

function set_detail(details){
	for(detail of details){
		const template_index = detail.template
		const content = document.querySelector('.detail_template')
		const template = document.getElementById(`template_${detail.template}`)
		const template_clone = template.content.cloneNode(true);
		template_clone.querySelector('.close').addEventListener('click', function(){
			data_result = data_result.filter(x => x.template_index != template_index)
			this.parentNode.parentNode.remove();
		})
		const image1 = template_clone.querySelector('input[name="filepond1"]');
		const image2 = template_clone.querySelector('input[name="filepond2"]');
		const pond_a = FilePond.create(image1, {
			files: [
				{
					source: `<?php echo base_url()?>${detail.image1}`,
				},
			],
			labelIdle: `<div style="font-size: 40px;"><i class="fa fa-picture-o"></i></div>`,
		})
		const pond_b = FilePond.create(image2, {
			files: [
				{
					source: `<?php echo base_url()?>${detail.image2}`,
				},
			],
			labelIdle: `<div style="font-size: 40px;"><i class="fa fa-picture-o"></i></div>`,
		})
		const x = template_clone.querySelector(".summernote")
		content.appendChild(template_clone)
		x.id  = `summernote_${template_index}`
		document.getElementById(`summernote_${template_index}`).value = detail.description;
		const obj = {
			template_index: template_index,
			textarea_id : x.id,
			textarea: '',
			image1: '',
			image2: '',
			template: detail.template,
		}
		pond_a.on('addfile', (error, file) => {
			obj.image1 = file.getFileEncodeBase64String()
		});
		pond_a.on('removefile', (error, file) => {
			obj.image1 = ''
		});
		pond_b.on('addfile', (error, file) => {
			obj.image2 = file.getFileEncodeBase64String()
		});
		pond_b.on('removefile', (error, file) => {
			obj.image2 = ''
		});
		data_result.push(obj)
		index++
	$('#modal_detail').modal('hide')
	}
}

function set_member(members, users){
	for(member of members){
		const member_index = index_member
		const content = document.querySelector('.member_template')
		const template = document.getElementById(`template_member`)
		const template_clone = template.content.cloneNode(true);
		template_clone.querySelector('.close').addEventListener('click', function(){ 
			data_member = data_member.filter(x => x.member_index != member_index)
			this.parentNode.parentNode.parentNode.remove();
		})
		const image = template_clone.querySelector('input[name="filepond-circle"]');
		const x = template_clone.querySelector(".select-student")
		x.id = `select-student-${member_index}`
		const input_select = template_clone.querySelector(".select-student")
        let option = document.createElement("option");
		for (user of users) {
            option = document.createElement("option");
            option.setAttribute("value", user.user_id);
            option.text = `${user.student_id} ${user.first_name} ${user.last_name}`;
			if(user.user_id == member.user_id){
				option.setAttribute('selected', 'selected')
			}
            input_select.appendChild(option);
        }
		content.appendChild(template_clone)
		const image_member = FilePond.create(image, {
			files: [
				{
					source: `<?php echo base_url()?>${member.image}`,
				},
			],
			acceptedFileTypes: ['image/png'],
			labelIdle: `<div style="font-size: 40px;"><i class="fa fa-picture-o"></i></div>`,
			imagePreviewHeight: 170,
			imageCropAspectRatio: '1:1',
			imageResizeTargetWidth: 200,
			imageResizeTargetHeight: 200,
			stylePanelLayout: 'compact circle',
			styleLoadIndicatorPosition: 'center bottom',
			styleButtonRemoveItemPosition: 'center bottom',
		});
		const obj = {
			member_index: member_index,
			value: '',
			select: member.user_id
		}
		image_member.on('addfile', (error, file) => {
			obj.value = file.getFileEncodeBase64String()
		});
		image_member.on('removefile', (error, file) => {
			obj.value = ''
		});
		$(`#select-student-${member_index}`).select2()
		$(`#select-student-${member_index}`).on('select2:select', function (e) {
			obj.select = $(`#select-student-${member_index}`).val()
		});
		data_member.push(obj)
		index_member++;
	}
}

function open_modal_tag(id, name){
	$('#muti').select2('close');
	const content = document.querySelector('.modal-content-tag')
    content.innerHTML = ''
	const template = document.getElementById('tag_modal_template')
	const template_clone = template.content.cloneNode(true);
	const input_name = template_clone.querySelector("#tag_name")
	template_clone.querySelector('.header-tag').innerText = 'เพิ่มหมวดหมู่'
	template_clone.querySelector('.header-tag').innerText = 'เพิ่มหมวดหมู่'
	template_clone.querySelector('#submit').addEventListener('click', function(){ 
		const name = input_name.value.trim()
		insert_tag(name)
	})
	content.appendChild(template_clone)
	$('#tag_modal').modal('show')
}

function get_tag(name) {
    $.ajax({
        type: 'get',
        url: "<?php echo site_url() . '/Tag/get_tag'; ?>",
        dataType: 'json',
        success: function(data) {
			let tag_selected = $('#muti').val()
			document.querySelectorAll('#muti option').forEach(option => option.remove());
			let selectList = document.querySelector('#muti');
			data.tag.forEach((row, index) => {
				option = document.createElement("option")
				option.setAttribute("value", row.tag_id)
				option.text = row.name
				selectList.appendChild(option)
			});
			if(name){
				let val = $("#muti").find("option:contains('"+name+"')").val()
				tag_selected.push(val)
				$("#muti").val(tag_selected).trigger('change.select2')
			}
		}
    })
}

function check_graduation(){
    const graduation = $('#graduation').val()
    let team = document.getElementById("team");
    let cluster = document.getElementById("cluster");
    let instructor = document.getElementById("instructor");
    if(graduation == 2){
        team.style.display = "none";
        cluster.style.display = "block";
        instructor.style.display = "none";
		document.getElementById("team_select").value = '';
		document.getElementById("instructor_select").value = '';
    }else if(graduation == 3){
        team.style.display = "block";
        cluster.style.display = "none";
        instructor.style.display = "none";
		document.getElementById("cluster_select").value = '';
		document.getElementById("instructor_select").value = '';
    }else{
        team.style.display = "none";
        cluster.style.display = "none";
        instructor.style.display = "block";
		document.getElementById("team_select").value = '';
		document.getElementById("cluster_select").value = '';
    }
}

function show_select_template(){
	$('#modal_detail').modal('show')
}

function chose_template(){
	if($('input[name=fav_language]:checked').length == 0){
		Toast.fire({
			icon: 'error',
			title: 'กรุณาเลิอกเทมเพลต',
		})
	}else{
		const template_index = index
		const choice = document.querySelector('input[name="fav_language"]:checked').value
		const content = document.querySelector('.detail_template')
		const template = document.getElementById(`template_${choice}`)
		const template_clone = template.content.cloneNode(true);
		template_clone.querySelector('.close').addEventListener('click', function(){
			data_result = data_result.filter(x => x.template_index != template_index)
			this.parentNode.parentNode.remove();
		})
		const image1 = template_clone.querySelector('input[name="filepond1"]');
		const image2 = template_clone.querySelector('input[name="filepond2"]');
		const pond_a = FilePond.create(image1, {
			labelIdle: `<div style="font-size: 40px;"><i class="fa fa-picture-o"></i></div>`,
		})
		const pond_b = FilePond.create(image2, {
			labelIdle: `<div style="font-size: 40px;"><i class="fa fa-picture-o"></i></div>`,
		})
		const x = template_clone.querySelector(".summernote")
		content.appendChild(template_clone)
		x.id  = `summernote_${template_index}`
		const obj = {
			template_index: template_index,
			textarea_id : x.id,
			textarea: '',
			image1: '',
			image2: '',
			template: choice,
		}
		pond_a.on('addfile', (error, file) => {
			obj.image1 = file.getFileEncodeBase64String()
		});
		pond_a.on('removefile', (error, file) => {
			obj.image1 = ''
		});
		pond_b.on('addfile', (error, file) => {
			obj.image2 = file.getFileEncodeBase64String()
		});
		pond_b.on('removefile', (error, file) => {
			obj.image2 = ''
		});
		data_result.push(obj)
		index++
	$('#modal_detail').modal('hide')
	}
}

function add_member(){
	const member_index = index_member
	const content = document.querySelector('.member_template')
	const template = document.getElementById(`template_member`)
	const template_clone = template.content.cloneNode(true);
	template_clone.querySelector('.close').addEventListener('click', function(){ 
		data_member = data_member.filter(x => x.member_index != member_index)
		this.parentNode.parentNode.parentNode.remove();
	})
	const image = template_clone.querySelector('input[name="filepond-circle"]');
	const x = template_clone.querySelector(".select-student")
	x.id = `select-student-${member_index}`
	const input_select = template_clone.querySelector(".select-student")
	let option = document.createElement("option");
	for (user of all_user) {
		option = document.createElement("option");
		option.setAttribute("value", user.user_id);
		option.text = `${user.student_id} ${user.first_name} ${user.last_name}`;	
		input_select.appendChild(option);
	}
	content.appendChild(template_clone)
	const image_member = FilePond.create(image, {
		acceptedFileTypes: ['image/png'],
		labelIdle: `<div style="font-size: 40px;"><i class="fa fa-picture-o"></i></div>`,
		imagePreviewHeight: 170,
		imageCropAspectRatio: '1:1',
		imageResizeTargetWidth: 200,
		imageResizeTargetHeight: 200,
		stylePanelLayout: 'compact circle',
		styleLoadIndicatorPosition: 'center bottom',
		styleButtonRemoveItemPosition: 'center bottom',
	});
	const obj = {
		member_index: member_index,
		value: '',
		select: ''
	}
	image_member.on('addfile', (error, file) => {
		obj.value = file.getFileEncodeBase64String()
	});
	image_member.on('removefile', (error, file) => {
		obj.value = ''
	});
	$(`#select-student-${member_index}`).select2()
	$(`#select-student-${member_index}`).on('select2:select', function (e) {
		obj.select = $(`#select-student-${member_index}`).val()
	});
	data_member.push(obj)
	index_member++;
}

function insert_tag(name) {
	if(name == '' || name == null){
		$('input[name="tag_name"]').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
					},
					dataType: 'json',
					success: async function(data) {
						if (data['message'] == true) {
							Toast.fire({
								icon: 'success',
								title: 'เพิ่มข้อมูลสำเร็จ',
							});
							await get_tag(name);
							$('#tag_modal').modal('hide')
						} 
						else {
							Toast.fire({
								icon: 'error',
								title: 'เพิ่มข้อมูลไม่สำเร็จ',
								text: 'ชื่อหมวดหมู่ซ้ำกับข้อมูลในระบบ'
							});
						} 
					}
				});
			}
		})
		$(".swal2-cancel").css("border", "1px solid #A79E9E");
	}
}

function update_projecct(){
	let year = $('#datepicker').val()
	let graduation = $('#graduation').val()
	let company = $('#company').val()
	let tags = [];
    tags = $('#muti').val();
	let name = $('#project_name').val();
	let name_en = $('#project_name_en').val();
	let select 
	let select_text
	for(data of data_result){
		data.textarea = $(`#${data.textarea_id}`).val()
	}
	let detail = data_result
	let member = data_member
	let image_logo = data_circle
	let image_cover = data_cover
	if(graduation == 2){
		select = $('#cluster_select').val()
		select_text = $("#cluster_select option:selected").text();
	}else if(graduation == 3){	
		select = $('#team_select').val()
		select_text = $("#team_select option:selected").text();
	}else{
		select =$('#instructor_select').val()
	}
	if(year == '' || graduation == '' || company == '' || name == '' || select == ''){
		Toast.fire({
			icon: 'error',
			title: 'กรุณากรอกข้อมูล',
		})
	}else if((image_logo == null || image_logo == '') || (image_cover == null || image_cover == '')){
		Toast.fire({
			icon: 'error',
			title: 'กรุณาเพิ่มรูปภาพ',
		})
	}else if(tags.length < 1){
		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().'/Project/update_project'; ?>",
					data: {
						'id' : '<?php echo $project->project_id ?>',
						'name': name,
						'name_en': name_en,
						'year': year,
						'graduation': graduation,
						'company': company,
						'tags': tags,
						'select': select,
						'detail': detail,
						'member': member,
						'image_logo': image_logo,
						'image_cover': image_cover,
						'select_text': select_text,
					},
					dataType: 'json',
					beforeSend: function() {
                        Swal.fire({
                            title: 'โปรดรอ',
                            html: 'กำลังดำเนินการ',// add html attribute if you want or remove
                            allowOutsideClick: false,
                            showConfirmButton: false,
                            didOpen: () => {
                                Swal.showLoading()
                            },
                        })
                    },
					success: function(data) {
						if (data['message'] == true) {
							Toast.fire({
								icon: 'success',
								title: 'แก้ไขข้อมูลสำเร็จ',
							}).then((result) => {
								window.location.href = '<?php echo site_url().'/Project/show_project_manage_user';?>';
							})
						}else {
							Toast.fire({
								icon: 'error',
								title: "แก้ไขข้อมูลไม่สำเร็จ",
							})
						}
					}
				});
			}
		})
		$(".swal2-cancel").css("border", "1px solid #A79E9E");
	}
}

function cancel_create_project(){
	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) {
			window.location.href = '<?php echo site_url().'/Project/show_project_manage_user';?>';
		} 
	})
	$(".swal2-cancel").css("border", "1px solid #A79E9E");
}

$("input[type=text]").focusout(function(){
	str = $(this).val().trim();
	if(str === ''){
		$(this).attr('class','form-control is-invalid');
	}else{
		$(this).removeClass('is-invalid');
	}
});

$("select").focusout(function(){
	str = $(this).val().trim();
	if(str === ''){
		$(this).attr('class','custom-select is-invalid');
	}else{
		$(this).removeClass('is-invalid');
	}
});
</script>
