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

$(document).ready(function(){
    console.info('add script loaded');
    $('#btn-new-staff').click(function(){
        var date        = $('#newdate').val();
        var dept_id     = $('#newdept').val();
        var dept_name   = $('#newdept option:selected').text();
        clearModal();

        $('#modal_new_date').val(date);
        $('#modal_new_department').val(dept_name);

    });

    $('#btnSave').click(function(){
        //disabled button save
        addMovement();
    });

    $('#btnEdit').click(function(){
        editGroup();
    });

});

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

function clearModal()
{
    $('#modal_new_date').val('');
    $('#modal_new_department').val('');
    $('#modal_new_timeout').val('');
    $('#modal_new_timein').val('');
}

function enableNewBtn()
{
    populateTable();
    var isFillDate      = false;
    var isFillDept      = false;

    var date            = $('#newdate').val();
    var dept            = $('#newdept').val();

    if(date.length > 0){
        isFillDate      = true;
    }else{
        isFillDate      = false;
    }

    if(dept != '-1'){
        isFillDept      = true;
    }else{
        isFillDept      = false;
    }

    if(isFillDate == true && isFillDept == true){
        $('#btn-new-staff').removeClass('disabled');
    }else{
        $('#btn-new-staff').addClass('disabled');
    }
}


function enableBtnSave()
{
    var isFillDate          = false;
    var isFillDept          = false;
    var isFillTable         = false;

    var date                = $('#newdate').val();
    var dept                = $('#newdept').val();

    if(date.length > 0)
    {
        isFillDate          = true;
    }else{
        isFillDate          = false;
    }

    if(dept != '-1')
    {
        isFillDept          = true;
    }else{
        isFillDept          = false;
    }

    if (movementTable.length > 0)
    {
        isFillTable         = true;
    }else{
        isFillTable         = false;
    }

    if (isFillDate == true && isFillDept == true && isFillTable == true){
        $('#btnSave').removeClass('disabled');    
    }else{
        $('#btnSave').addClass('disabled');
    }
}

function enableBtnPrint() 
{
    var isFillDate          = false;
    var isFillDept          = false;
    var isFillTable         = false;

    var date                = $('#newdate').val();
    var dept                = $('#newdept').val();

    if(date.length > 0){
        isFillDate          = true;
    }else{
        isFillDate          = false;
    }

    if(dept != '-1'){
        isFillDept          = true;
    }else{
        isFillDept          = false;
    }

    if (movementTable.length > 0){
        isFillTable         = true;
    }else{
        isFillTable         = false;
    }

    if (isFillDate == true && isFillDept == true && isFillTable == true){
        $('#btnPrint').removeClass('disabled');   
    }else{
        $('#btnPrint').addClass('disabled');
    }
}

function enableBtnCopy() 
{
    $('#btnCopy').removeClass('disabled');
}

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

}

function saveToEditBtn()
{
    $('#btnEdit').removeClass('d-none');
    $('#btnEdit').removeClass('disabled');
    $('#btnSave').addClass('d-none');
    enableCopyBtn();
}

function editToSaveBtn()
{
    $('#btnSave').removeClass('d-none');
    $('#btnEdit').addClass('d-none');
}

function addStaff()
{
    if(isFilledInput())
    {
        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();

        var table = [{
            staffId     : staff_id,
            staffName   : staff_name,
            timeout     : time_out,
            timein      : time_in
        }];

        movementTable.push(table);
    }

    $('#new').modal('toggle');
    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();
        };
    }
        enableBtnSave();enableBtnPrint();     
}

function isFilledInput()
{
    var flag = true;
    if(!$('#newdate').val() || 
        !$('#modal_new_timeout').val() || 
        !$('#modal_new_timein').val() || 
        $('#modal_new_user').val() == '-1')
    {
        flag = false;
    }
    return flag;
}

function removeMovement(rowcount)
{
    
        iziToast.question({
        title: '',
        timeout:20000,
        close: false,
        toastOnce: true,
        message: 'Are you sure you want to remove this record? ',
        position:"center",
        buttons: [
                    ['<button><b>YES</b></button>', function (instance, toast) {
                        movementTable.splice(rowcount-1,1);
                        populateTable();
                        instance.hide(toast, {
                            transitionOut: 'fadeOutUp'
                        });
                    }],
                    ["<button>No</button>", function (instance, toast) {
                        instance.hide(toast, {
                            transitionOut: 'fadeOutUp'
                        });

                        iziToast.warning({
                            position: 'bottomRight',
                            message: 'Operation cancelled.'
                        });

                    },true]
                ]
        });
   
}

function editGroup() 
{
    var date        = $('#newdate').val();
    var dept_id     = $('#newdept').val();
    var client_id   = $('#client').val();
    if(client_id == 'others')
    {
        destination = $('#newclient').val();
    }else{
        destination = '';
    }  
    var type_id = $('#type').val();
    var desc = $('#desc').val();
    var groupid = $('#groupid').val();
    var staff = JSON.stringify(movementTable);

    var frmData = new FormData();
    frmData.append("token",token);
    frmData.append('groupid',groupid);
    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);

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

function editMovement (value) 
{
    iziToast.question({
    title: '',
    timeout:20000,
    close: false,
    toastOnce: true,
    message: 'Are you sure you want to edit this record? ',
    position:"center",
    buttons: [
                ['<button><b>YES</b></button>', function (instance, toast) {
                    instance.hide(toast, {
                        transitionOut: 'fadeOutUp'
                    });
                }],
                ["<button>No</button>", function (instance, toast) {
                    instance.hide(toast, {
                        transitionOut: 'fadeOutUp'
                    });

                    iziToast.warning({
                        position: 'bottomRight',
                        message: 'Operation cancelled.'
                    });
                }]
            ]
    });
}

//-------------------------------------
// this will be done in edit screen
//-------------------------------------
function saveEdit() 
{
    // var tableid  =  $('#editTableId').val();
    // var editName =  $('#editName').val();
    // var editDate =  $('#editDate').val();
    // var timeOut  =  $('#editTimeOut').val();
    // var timeIn   =  $('#editTimeIn').val();

    // console.log('new timeout : '+timeOut);
    // console.log('new timein : '+timeIn);

    // movementTable[tableid][0].timeout = timeOut;
    // movementTable[tableid][0].timein  = timeIn;
    // populateTable();
    // $('#edit').modal('toggle');
    // var groupid = $('#groupid').val();
    // if(groupid)
    // {
    //     var staffid = movementTable[tableid][0].staffId;
    //     var timeout = $('#editTimeOut').val();
    //     var timein  = $('#editTimeIn').val();

    //     var frmData = new FormData();
    //     frmData.append("token",token);
    //     frmData.append('staffid',staffid);
    //     frmData.append('groupid',groupid);
    //     frmData.append('timeout',timeout);
    //     frmData.append('timein',timein);

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

    // }
}

function editModal(id) 
{
    var id = id-1;
    var content = movementTable[id][0];
    $('#editTableId').val(id);
    $('#editName').val(content.staffName);
    $('#editDate').val($('#newdate').val());
    $('#editTimeOut').val(content.timeout);
    $('#editTimeIn').val(content.timein);
}

function addMovement()
{
    event.preventDefault();
    var date = $('#newdate').val();
    var dept_id = $('#newdept').val();
    var client_id = $('#client').val();
    if(client_id == 'others')
    {
        var client_id = -1;
        destination = $('#newclient').val();
    }else{
        destination = '';
    }
    var type_id = $('#type').val();
    var desc = $('#desc').val();
    var staff = JSON.stringify(movementTable);

    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);

    $.ajax({
        url:"<?php echo base_url('/hr/api_movement/create'); ?>",
        type:'post',
        dataType:'json', //return type value
        data:frmData,
        processData: false,
        contentType: false,
        success:function(data){
            // $('#groupid').val(data.group_id);
            // saveToEditBtn();
            iziToast.success({
                title: '',
                message: 'A new movement created'
            });
            window.location.replace("<?php echo base_url('hr/api_movement/edit/') ?>"+data.group_id);
            
        },error:function(){
            iziToast.error({
                title: '',
                message: '500 internal server error'
            });
        }
    });
}    

</script> 