<script type="text/javascript" src="https://unpkg.com/xlsx@0.15.1/dist/xlsx.full.min.js"></script>
<style>
.required label:after {
    color: #e32;
    content: ' *';
    display: inline;
    /* font-weight: bold; */
}
.showmore_center{
	text-align: center;
}
</style>

<!-- Start Content Wrapper. Contains page content -->
<div class="content-wrapper h-100">
    <!-- Start content header (Page header) -->
    <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().'/User/show_user_manage';?>'>ผู้ใช้งาน</a>
                        <li class="breadcrumb-item active">เพิ่มผู้ใช้งานจาก Excel</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>
    <!-- End content-header -->
    <div class="content">
        <div class="container-fluid">
            <div class="card card-outline card-primary">
                <div class="card-header">
                    <h1 class="card-title"><b>เพิ่มผู้ใช้งานจาก Excel</b></h1>
                </div>
                <div class="card-body">
                    <div class="form-body">
						<input type="file" id="excel_file" />
						<button type="button" id="submit" class="btn btn-default float-right" onclick="create_user()" style="color:white">บันทึก</button>
						<a type="button" class="btn btn-default float-right" style='margin-right:10px; border-color:#A79E9E;' onclick="cancel_create_user()">ยกเลิก</a>
						<a href="<?php echo base_url() ?>image/template.xlsx" download="template.xlsx"><img src="<?php echo base_url() ?>image/excel.png" style="width: 25px;"> ดาวน์โหลด Template</a download>
						<br><br>
						<div id="excel_data"></div>
						<br>
                    </div>
                </div>
            </div>
        </div>
    </div>
	<div class="modal fade bd-example-modal-lg" id="modal_excel" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
		<div class="modal-dialog modal-lg">
			<div class="modal-content">
				<div class="modal-header">
					<h5 class="modal-title"><b>บันทึกไม่สำเร็จ</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">
					<p style="text-align: center; font-size: 18px" id="number"></p>
					<div class="showmore_center">
					<a class="btn" style="background-color:white;border-color:#A79E9E; font-size: 18px;" data-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
   			 			แสดงรายละเอียดข้อผิดพลาด
  					</a>
					<br><br>
					<div class="collapse" id="collapseExample">
						<div id="excel_error"></div>
					</div>
				</div>
			</div>
		</div>
	</div>
<script>
	
const excel_file = document.getElementById('excel_file');
let data_result = []

excel_file.addEventListener('change', (event) => {

	if(!['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel'].includes(event.target.files[0].type))
	{
		document.getElementById('excel_data').innerHTML = '<div class="alert alert-danger">Only .xlsx or .xls file format are allowed</div>';
		excel_file.value = '';
		return false;
	}

	var reader = new FileReader();
	reader.readAsArrayBuffer(event.target.files[0]);
	reader.onload = function(event){
		var data = new Uint8Array(reader.result);
		var work_book = XLSX.read(data, {type:'array'});
		var sheet_name = work_book.SheetNames;
		var sheet_data = XLSX.utils.sheet_to_json(work_book.Sheets[sheet_name[0]], {header:1});
		console.log(sheet_data)
		header = sheet_data[0]
		if(sheet_data.length > 0)
		{
			data_result = sheet_data
			var table_output = '<table class="table table-striped table-bordered">';
			for(var row = 0; row < sheet_data.length; row++)
			{
				table_output += '<tr>';
				for(var cell = 0; cell < sheet_data[row].length; cell++)
				{
					if(row == 0)
					{
						table_output += '<th>'+sheet_data[row][cell]+'</th>';
					}
					else
					{
						table_output += '<td>'+sheet_data[row][cell]+'</td>';
					}
				}
				table_output += '</tr>';
			}
			table_output += '</table>';
			document.getElementById('excel_data').innerHTML = table_output;
		}
		excel_file.value = ''
	}
});


function cancel_create_user(){
	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().'/User/show_user_manage';?>';
		} 
	})
	$(".swal2-cancel").css("border", "1px solid #A79E9E");
}

function create_user(){
	if(data_result.length == 0){
		Toast.fire({
			icon: 'error',
			title: 'กรุณาป้อนข้อมูล',
		})
	}else if(data_result[0][0] != "รหัสนิสิต" || data_result[0][1] != "คำนำหน้า" || data_result[0][2] != "ชื่อจริง" || data_result[0][3] != "นามสกุล" || data_result[0][4] != "อีเมล"){
		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().'/User/insert_user_excel'; ?>",
					data: {
						data: data_result
					},
					dataType: 'json',
					success: function(data) {
						console.log(data)
						if (data.result.length == 0) {
							Toast.fire({
								icon: 'success',
								title: 'เพิ่มข้อมูลสำเร็จ',
							}).then((result) => {
								window.location.href = '<?php echo site_url().'/User/show_user_manage';?>';
							})
						}else {
							Toast.fire({
								icon: 'error',
								title: "เพิ่มข้อมูลไม่สำเร็จ",
								text: "อีเมลซ้ำกับข้อมูลในระบบ",
							})
							var table_output = '<table class="table table-striped table-bordered">';
							for(var row = 0; row < data.result.length; row++)
							{	
								if(row == 0){
									table_output += '<tr>';
									table_output += '<th>รหัสนิสิต</th>'
									table_output += '<th>คำนำหน้า</th>'
									table_output += '<th>ชื่อจริง</th>'
									table_output += '<th>นามสกุล</th>'
									table_output += '<th>อีเมล</th>'
									table_output += '</tr>';
								}
								table_output += '<tr>';
								for(var cell = 0; cell < data.result[row].length; cell++)
								{
									table_output += '<td>'+data.result[row][cell]+'</td>';
								}
								table_output += '</tr>';
							}
							table_output += '</table>';
							document.getElementById('excel_error').innerHTML = table_output;
							document.getElementById('number').innerText = `จำนวนผู้ใช้ที่บันทึกไม่สำเร็จ ${data.result.length} คน`
							$('#modal_excel').modal('show')
						}
					}
				});
			}
		})
		$(".swal2-cancel").css("border", "1px solid #A79E9E");
	}
	document.getElementById("submit").disabled = false;
}
</script>
