
<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="company_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="company_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="company_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="profile-pic-wrapper">
			<div class="pic-holder">
				<!-- uploaded pic shown here -->
				<img id="profilePic" class="pic" src='<?php echo base_url() ?>image/default_logo.jpg' >

				<label for="newProfilePhoto" class="upload-file-block">
				<div class="text-center">
					<div class="mb-2">
					<i class="fa fa-camera fa-2x"></i>
					</div>
					<div class="text-uppercase">
					<br> รูปภาพโลโก้ <br> 
					</div>
					ขนาดไฟล์น้อยกว่า 2 MB. <br>
					ไฟล์ ่jpg, png
				</div>
				</label>
				<Input class="uploadProfileInput" type="file" name="profile_pic" id="newProfilePhoto" accept="image/*" style="display: none;" />
			</div>
		</div>
		<div class="form-group required">
			
			<label for="recipient-name" class="col-form-label">บริษัท/สำนักงาน</label>
			<input type="text" class="form-control" id="company_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_company();
	});

	let data_image;

    $(document).on("change", ".uploadProfileInput", function () {
		let triggerInput = this;
		let currentImg = $(this).closest(".pic-holder").find(".pic").attr("src");
		let holder = $(this).closest(".pic-holder");
		let wrapper = $(this).closest(".profile-pic-wrapper");
		$(wrapper).find('[role="alert"]').remove();

		let files = !!this.files ? this.files : [];
		
		if (!files.length || !window.FileReader) {
			return;
		}
		if (/^image/.test(files[0].type)) {
			// only image file
			if(files[0].size<=2048000){
				let reader = new FileReader(); // instance of the FileReader
				reader.readAsDataURL(files[0]); // read the local file
				reader.onloadend = function () {
					$(holder).addClass("uploadInProgress");
					$(holder).find(".pic").attr("src", this.result);
					
					$(holder).append(
						'<div class="upload-loader"><div class="spinner-border text-primary" role="status"><span class="sr-only">กำลังโหลด...</span></div></div>'
					);

					// Dummy timeout; call API or AJAX below
					setTimeout(() => {
						$(holder).removeClass("uploadInProgress");
						$(holder).find(".upload-loader").remove();
						// If upload successful
						if (Math.random() < 0.9) {
							$("#profilePic_confirm").attr("src", this.result);
							data_image = reader.result
							return data_image;
						}
					}, 1500);
				};
			}else{
				Swal.fire({
					icon: 'error',
					title: 'ไฟล์มากกว่า 2 MB !!',
					text: 'กรุณาเลือกไฟล์ที่มีขนาดน้อยกว่า 2 MB',                            
					showConfirmButton: false,
					timer: 2000
				});
			}
		}
	});

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

        },
        dataType: 'json',
        success: function(data) {
            create_table(data.company);
			let html_code = ''
			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("company_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_company(row.company_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 = ''
	data_image = ''
	const template = document.getElementById('company_modal_template')
	const template_clone = template.content.cloneNode(true);
	const input_name = template_clone.querySelector("#company_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_company(name, data_image)
        })
	}else{
		template_clone.querySelector('.modal-title-bold').innerText = 'แก้ไขบริษัท'
		input_name.value = row.name
		template_clone.getElementById("profilePic").src = `<?php echo base_url() ?>image/company/company_${row.company_id}/${row.image}`;
		template_clone.querySelector('#submit').addEventListener('click', function(){ 
			const name = input_name.value
			update_company(row.company_id ,name, data_image)
        })
	}
	content.appendChild(template_clone)
	$('#company_modal').modal('show')
}

function delete_company(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 company
        if (result.value) {
            $.ajax({
                type: 'post',
                url: "<?php echo site_url().'/company/delete_company'; ?>",
                data: {
                    'id': id
                },
                dataType: 'json',
                success: async function(data) {
                    if (data['message'] == true) {
                        Toast.fire({
                            icon: 'success',
                            title: 'ลบข้อมูลสำเร็จ',
                        });
                        get_company();
                    } 
                    else {
                        Toast.fire({
                            icon: 'success',
                            title: 'ลบข้อมูลไม่สำเร็จ',
                        });
                    } 
                }
            });
        }
    })
    $(".swal2-cancel").css("border", "1px solid #A79E9E");
}

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

function update_company(id,name,image) {
	if(name == ''){
		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().'/company/update_company'; ?>",
					data: {
						'id': id,
						'name': name,
						'image': image,
					},
					dataType: 'json',
					success: async function(data) {
						if (data['message'] == true) {
							Toast.fire({
								icon: 'success',
								title: 'แก้ไขข้อมูลสำเร็จ',
							});
							await get_company();
							$('#company_modal').modal('hide')
						} 
						else {
							Toast.fire({
								icon: 'error',
								title: 'แก้ไขข้อมูลไม่สำเร็จ',
								text: 'ชื่อบริษัทซ้ำกับข้อมูลในระบบ'
							});
						} 
					}
				});
			}
		})
		$(".swal2-cancel").css("border", "1px solid #A79E9E");
	}
}

</script>


