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

$(document).ready(function(){
	console.log('create script loaded');

	$('#createMove').click(function()
	{
		$('#staffSection').removeClass('d-none');
		changeClass('#step2','disabled','active');
		
	});

	//button to toggle modal
	$('#addBtn').click(function()
	{ 
		$('#modal_new_date').val($('#newdate').val());
		$('#modal_new_department').val($('#newdept option:selected').text());
	});

	//button in the modal
	$('#btnAdd').click(function()
	{
		var dept_id     = $('#newdept').val();
        var staff_id    = $('#modal_new_user option:selected').val();
        var staff_name  = $('#modal_new_user option:selected').text();
        var time_out    = $('#modal_new_timeout').val();
        var time_in     = $('#modal_new_timein').val();

        if(staff_id != -1 && time_out != '' && time_in != ''){
        	var table = [{
	            staffId     : staff_id,
	            staffName   : staff_name,
	            timeout     : time_out,
	            timein      : time_in
	        }];

	        movementTable.push(table);
	        populateTable();

	    	$('#new').modal('toggle');
			changeClass('#step2','active','complete');
			changeClass('#saveBtn','disabled','');
			$('#saveBtn').removeAttr('disabled');
        }

        var typeVal = $('#type').val();

		if(typeVal == 1){
			$('#addBtn').attr('disabled',true);
		}
	});

	$('#editSave').click(function(){
		event.preventDefault();
		var rowid 		= $('#editId').val();
		var timeout 	= $('#editTimeOut').val();
		var timein 		= $('#editTimeIn').val();

		movementTable[rowid][0].timeout = timeout;
		movementTable[rowid][0].timein 	= timein;
		populateTable();
		$('#edit').modal('toggle');
	});

	$('#type').change(function(){
		var typeVal = $('#type').val();
		destroyTable();
		if(typeVal == 1){
			console.log('val is equal to one'+typeVal);
			$('#replacement_wrapper').removeClass('d-none');
		}else{
			console.log('val is not equal to one '+typeVal);
			$('#replacement_wrapper').addClass('d-none');

		}
	});

	$('#saveBtn').click(function()
	{
		//disabled button save 
		// changeClass('#saveBtn','disabled','');
		$('#saveBtn').addClass('disabled');
		$('#saveBtn').attr('disabled','disabled');

		event.preventDefault();
	    var date = $('#newdate').val();
	    var dept_id = $('#newdept').val();
	    var client_id = $('#client').val();
	    var destination = $('#pac-input').val();
	    var type_id = $('#type').val();
	    var desc = $('#desc').val();
	    var staff = JSON.stringify(movementTable);
	    var createdBy = <?php echo $_SESSION['user']['id'];?>;
	    var date_replacement = $('#modal_replacement_date').val();
	    var timein_replacement = $('#modal_replacement_timein').val();
	    var timeout_replacement = $('#modal_replacement_timeout').val();

	    var frmData = new FormData();
	    frmData.append("token",token);
	    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("staff",staff);
	    frmData.append("createdby",createdBy);
	    frmData.append("date_replacement",date_replacement);
	    frmData.append("timein_replacement",timein_replacement);
	    frmData.append("timeout_replacement",timeout_replacement);

	    iziToast.info({
	        title: 'Please wait',
	        message: 'Sending email for movement approval.'
	     });

	    $.ajax({
	        url:"<?php echo base_url('/hr/api/staffmovement/create'); ?>",
	        type:'post',
	        dataType:'json', //return type value
	        data:frmData,
	        processData: false,
	        contentType: false,
	        success:function(data){
	            iziToast.success({
	                title: '',
	                message: 'A new movement created'
	            });
	            window.location.replace("<?php echo base_url('hr/StaffMovement/edit/') ?>"+data.group_id);
	            
	        },error:function(){
				$('#error_notice').modal('toggle');

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


//js helper functions
// function clientChoose(val)
// {
//     var element = $('#client').val();
//      if(element=='others')
//      {
//         $('#newclient').removeClass('d-none');
//      }else{
//         $('#newclient').addClass('d-none');
//      }
// }

function changeClass(element,from,to) 
{
	$(element).removeClass(from);
	$(element).addClass(to);
}

//button to toggle new modal and edit content
function editModal(row) 
{
	$('#editDate').val($('#newdate').val());
	$('#editName').val(movementTable[row-1][0].staffName);
	$('#editTimeOut').val(movementTable[row-1][0].timeout);
	$('#editTimeIn').val(movementTable[row-1][0].timein);
	$('#editId').val(row-1);
}

function removeMovement(row) 
{
	movementTable.splice(row-1,1);
	populateTable();
}

function populateTable() {
	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();
        };
    }
}

function destroyTable() {
	movementTable = [];
	populateTable();
}

function typeChange() {
	destroyTable();
	if($('#type').val() == 1){
		$('#client_row').addClass('d-none');
		$('#client').val(-1);
		$('#client').select2('val',-1);
	}else{
		$('#client_row').removeClass('d-none');
	}
}
</script>