<script type="text/javascript">
var token = "<?php echo $this->session->userdata('token');?>";
var movementTable = new Array();
var movementDescription = '';

$(document).ready(function(){
	disableNewBtn();
	var groupid = <?php echo $this->uri->segment(4)?>;
	var frmData = new FormData();
    frmData.append('token',token);
    frmData.append('groupid',groupid);
    $.ajax({
	 	url:"<?php echo base_url('/hr/api/staffmovement/getDetails'); ?>",
		type:'post',
		dataType:'json',
		data:frmData,
		processData: false,
		contentType: false,
		success:function(data){
			console.log(data);
			$("#newdept").val(data.group.departmentid);
			$('#newdept').select2('val',data.group.departmentid);

			if(data.group.customerid > 0 && data.group.customerName != null){
				$("#client").val(data.group.customerid).trigger('change');
			}
			

			if(data.group.typeid == 1){
				$('.replacement-wrapper').removeClass('d-none');
				$('#replacement_date').val(reformatDate(data.group.replacement_date));
				$('#replacement_start').val(timeTo12(data.group.replacement_start));
				$('#replacement_end').val(timeTo12(data.group.replacement_end));
			}
			

			if (data.table != 'no result')
			{
				for (var i = 0; i < data.table.length; i++) 
				{
					
					var table = [{
						typeid 		: data.table[i].typeid,
						detailid 	: data.table[i].detailid,
			            staffId     : data.table[i].staffid,
			            staffName   : data.table[i].staffName,
			            timeout     : timeTo12(data.table[i].timeOut),
			            timein      : timeTo12(data.table[i].timeIn)
			        }];

					$('#newdate').val(reformatDate(data.table[i].date));
					$('#modal_new_date').val(data.table[i].date);

					$("#type").val(data.table[i].typeid);
					$('#type').select2('val',data.table[i].typeid);
					
					$('#destination').val(data.table[i].destination);
					$('#desc').val(data.table[i].description);
					$('#creator').html(data.table[i].creator);
					console.log("creator : <?php echo $_SESSION['user']['name']?>");
					if(data.table[i].created_by == <?php echo $_SESSION['user']['id']?>){
					console.log("inner creator : <?php echo $_SESSION['user']['name']?>");

						$('#editButton').removeClass('d-none');
						$('#deleteButton').removeClass('d-none');
						var postDate = new Date(data.group.date).getTime()+(6 * 24 * 60 * 60 * 1000);
						var today = new Date().getTime();
						// var today = Math.round(+new Date()/10);

						var newdate = new Date(today * 1000);
						console.log(newdate.getDate());
						// var tomorrow = today.add(1).day().getTime();

						console.log('postdate : '+postDate);
						console.log('today : '+today);

						if(today > postDate){
							$('#editButton').addClass('d-none');
							$('#deleteButton').addClass('d-none');
						}
					}

			        movementTable.push(table);
				};
				
			};   
    	createTable();

    	if(data.similar.length > 0 && data.group.typeid != 1){
    		for (var i = 0; i < data.similar.length; i++) {
    			$('#similar-movement').append('<li><a href="<?php echo base_url();?>/hr/StaffMovement/edit/'+data.similar[i].id+'" data-tooltip="tooltip" data-placement="bottom" data-trigger="hover" data-original-title="view and edit movement">'+data.similar[i].date+' <span class="fas fa-eye"></span></a></li>');
    		};
    	}

		},error:function(){
			iziToast.error({
				title: '',
				message: '500 internal server error'
			});
		}
	});

	$('#btnSave').click(function(){
		event.preventDefault();
		var date 		= $('#newdate').val();
		var dept_id 	= $('#newdept').val();
		var client_id 	= $('#client').val();
		var destination = $('#destination').val();
		var type_id 	= $('#type').val();
		var desc 		= $('#desc').val();
		var group_id 	= <?php echo $this->uri->segment(4)?>;

		var replacement_date = $('#replacement_date').val();
		var replacement_start= $('#replacement_start').val();
		var replacement_end  = $('#replacement_end').val();


		var frmData = new FormData();
	    frmData.append('token',token);
	    frmData.append('groupid',group_id);
	    frmData.append('date',date);
	    frmData.append('deptid',dept_id);
	    frmData.append('clientid',client_id);
	    frmData.append('destination',destination);
	    frmData.append('typeid',type_id);
	    frmData.append('desc',desc);
	    frmData.append('replacement_date',replacement_date);
	    frmData.append('replacement_start',replacement_start);
	    frmData.append('replacement_end',replacement_end);
	    frmData.append('staff',JSON.stringify(movementTable));

		$.ajax({
		 	url:"<?php echo base_url('/hr/api/staffmovement/editGroup'); ?>",
			type:'post',
			dataType:'json',
			data:frmData,
			processData: false,
			contentType: false,
			success:function(data){
				location.reload();
				iziToast.success({
	                title: '',
	                message: 'success'
	            });
			},error:function(){
				iziToast.error({
					title: '',
					message: '500 internal server error'
				});
			}
		});

	});
	
	$('#btn-new-staff').click(function(){
		var dept = $('#newdept option:selected').text();
		$('#modal_new_department').val(dept);
	});

	$('#btnNewCopy').click(function(){
		var date 		= $('#copyDate').val();
		var dept_id 	= $('#newdept').val();
		var client_id 	= $('#client').val();
		var type_id 	= $('#type').val();
		var desc 		= $('#desc').val();

		var frmData = new FormData();
	    frmData.append('token',token);
	    frmData.append('date',date);
	    frmData.append('deptid',dept_id);
	    frmData.append('clientid',client_id);
	    if(client_id == 'others')
	    {
	        destination = $('#newclient').val();
	    }else{
	        destination = '';
	    }
	    frmData.append('destination',destination);
	    frmData.append('typeid',type_id);
	    frmData.append('desc',desc);
	    frmData.append('staff',JSON.stringify(movementTable));

		$.ajax({
		 	url:"<?php echo base_url('/hr/api/staffmovement/create'); ?>",
			type:'post',
			dataType:'json',
			data:frmData,
			processData: false,
			contentType: false,
			success:function(data){
				location.reload();
				iziToast.success({
	                title: '',
	                message:'Success copy movement to a new date'
	            });
	            $('#copy').modal('toggle');
			},error:function(){
				iziToast.error({
					title: '',
					message: '500 internal server error'
				});
			}
		});

	});

	$('#btnApproved').click(function(){
		console.log('approving data');

		var frmData = new FormData();
            frmData.append('token',token);
            frmData.append('group_id',$('#approveid').val());
            frmData.append('status',$('#approveStatus').val());
            frmData.append('update_by',<?php echo $_SESSION['user']['id']; ?>);

            $.ajax({
            url:"<?php echo base_url('/hr/api/staffmovement/changeStatus'); ?>",
            type:'post',
            dataType:'json',
            data:frmData,
            processData: false,
            contentType: false,
            success:function(data){
                console.log(data);
                iziToast.success({
                    title: '',
                    message: data.message
                });
                location.reload();
            },error:function(){
                iziToast.error({
                    title: '',
                    message: '500 internal server error'
                });
            }
        });


		 $('#approve').modal('toggle');
	});
});

function addStaff() {
	var table = [{
		// detailid 	: data.table[i].detailid, doesnt have this data ye because it not been saved yet
		staffId     : $('#modal_new_user').val(),
		staffName   : $('#modal_new_user option:selected').text(),
		timeout     : $('#modal_new_timeout').val(),
		timein      : $('#modal_new_timein').val()
	}];

	movementTable.push(table);
	populateTable();
    $('#new').modal('toggle');

}

function disableNewBtn() 
{
   $('#btn-new-staff').addClass('disabled');
}
function enableNewBtn()
{
   $('#btn-new-staff').removeClass('disabled'); 
}

function enableSaveBtn() 
{
   $('#btnSave').removeClass('disabled'); 
}

function enablePrintBtn() 
{
	$('#btnPrint').removeClass('disabled');
}

function enableCopyBtn() 
{
	$('#copyMovement').removeClass('d-none');
	$('#btnCopy').removeClass('disabled');

}

function removeGroup(){
	var id = <?php echo $this->uri->segment(4);?>;
	var frmData = new FormData();
   	frmData.append('token',token);
    frmData.append('groupid',id);

    $.ajax({
        url:"<?php echo base_url('/hr/api/staffmovement/remove'); ?>",
        type:'post',
        dataType:'json', //return type value
        data:frmData,
        processData: false,
        contentType: false,
        success:function(data){
            iziToast.success({
                title: '',
                message: 'success'
            });
           
            window.location.replace("<?php echo base_url('hr/StaffMovement/groups');?>");

        },error:function(){
            iziToast.error({
                title: '',
                message: '500 internal server error'
            });
        }
    });
}
function enableEdit(){
	$('#newdate').removeAttr('disabled');
	$('#newdept').removeAttr('disabled');
	$('#client').removeAttr('disabled');
	$('#type').removeAttr('disabled');
	$('#desc').removeAttr('disabled');
	$('#destination').removeAttr('disabled');
	$('#replacement_date').removeAttr('disabled');
	$('#replacement_start').removeAttr('disabled');
	$('#replacement_end').removeAttr('disabled');

	$('#rowSave').removeClass('d-none');

	$type_id = $('#type').val();

	if($type_id != 1){
		$('#rowAddStaff').removeClass('d-none');
	}

	populateTable();
}

function editModal(id) 
{
	$('#editTableId').val(id-1);
	$('#editName').val(movementTable[id-1][0].staffName);
	var date    = $('#newdate').val();

	$('#editDate').val(date);
	$('#editTimeOut').val(movementTable[id-1][0].timeout);
	$('#editTimeIn').val(movementTable[id-1][0].timein);
}

function saveEdit() {
	var id = $('#editTableId').val();
	movementTable[id][0].timeout = $('#editTimeOut').val();
	movementTable[id][0].timein  = $('#editTimeIn').val();

	populateTable();
    $('#edit').modal('toggle');

}

function removeMovement(id) 
{
	movementTable.splice(id-1,1);
	console.log('movement table after splice : '+movementTable);
	populateTable();
}

function clientChoose(){
	console.log($('#client').val());
	$('#newclient').val('');
	if($('#client').val() == 'others'){
		$('#newclient').removeClass('d-none');
	}
}

function createTable() 
{
	console.log(movementTable);
	var date    = $('#newdate').val();
    var table   = $('.table').DataTable();
    table.clear().draw();

    if(movementTable.length > 0)
    {      
    	for (var i = 0; i < movementTable.length; i++) 
    	{
			var overlap = 'OK';
            
            for (var k = 0; k <= i; k++) 
            {
                if ((movementTable[i][0].staffId == movementTable[k][0].staffId) && k != i) 
                {

                    var firstrange   = 
                    {
                        startTime : timeTo24(movementTable[k][0].timeout),
                        endTime   : timeTo24(movementTable[k][0].timein)
                    };
                    var secondrange  = 
                    {
                        startTime : timeTo24(movementTable[i][0].timeout),
                        endTime   : timeTo24(movementTable[i][0].timein)
                    };

                    if(ifTimeOverlap(firstrange,secondrange))
                    {
                        overlap = 'Overlap';
                    }
                };    
            };

            var rowCount = table.data().count();

            var action_one = '<td class="text-center">\
                		<a class="disabled" data-tooltip="tooltip" data-placement="bottom" data-trigger="hover" data-original-title="Delete" style="cursor:not-allowed;opacity:0.7;"><i class="fas fa-edit"></i></a>\
                        <a disabled style="cursor:not-allowed;opacity:0.7;"><i class="fas fa-trash-alt text-danger" ></i>\
                        </a>\
                    </td>';

           	table.row.add({
                0   : ++rowCount,
                1   : date,
                2   : movementTable[i][0].staffName,  
                3   : movementTable[i][0].timeout,
                4   : movementTable[i][0].timein,
                5   : overlap,
                6   : action_one,
            }).draw();
          
           

    		enableNewBtn();
    		enableSaveBtn();
    		enablePrintBtn();
    		enableCopyBtn();

    	};
    }

}
function populateTable() 
{
	console.log(movementTable);
	var date    = $('#newdate').val();
	

    var table   = $('.table').DataTable();
    table.clear().draw();

    if(movementTable.length > 0)
    {      
    	for (var i = 0; i < movementTable.length; i++) 
    	{
			var overlap = 'OK';
            
            for (var k = 0; k <= i; k++) 
            {
                if ((movementTable[i][0].staffId == movementTable[k][0].staffId) && k != i) 
                {

                    var firstrange   = 
                    {
                        startTime : timeTo24(movementTable[k][0].timeout),
                        endTime   : timeTo24(movementTable[k][0].timein)
                    };
                    var secondrange  = 
                    {
                        startTime : timeTo24(movementTable[i][0].timeout),
                        endTime   : timeTo24(movementTable[i][0].timein)
                    };

                    if(ifTimeOverlap(firstrange,secondrange))
                    {
                        overlap = 'Overlap';
                    }
                };    
            };

            var rowCount = table.data().count();
            table.row.add({
                0   : ++rowCount,
                1   : date,
                2   : movementTable[i][0].staffName,  
                3   : movementTable[i][0].timeout,
                4   : movementTable[i][0].timein,
                5   : overlap,
                6   : '<td class="text-center">\
                        <a href="#" data-toggle="modal" data-target="#edit" data-toggle="tooltip" data-placement="top" title="Edit" onclick="editModal('+rowCount+')"><i class="fas fa-edit"></i></a>\
                        <a href="javascript:removeMovement('+rowCount+')" data-toggle="tooltip" data-placement="top" title="Delete"><i class="fas fa-trash-alt text-danger" ></i>\
                        </a>\
                    </td>',
            }).draw();

    		enableNewBtn();
    		enableSaveBtn();
    		enablePrintBtn();
    		enableCopyBtn();

    	};
    }

}
</script>