$(function () {
    console.log('user.js');
    ListTable();

	$(document).on('change', '#user-role', function() {
		var cur_val = $(this).val();	
		
		if(cur_val == 5) {
			$("#vendor_dropdown").show();
		} else {
			$("#vendor_dropdown").hide();
		}
	});
	
    $(document).on('click', '.btnAddUser', function() {
        console.log('[Add User] Clicked!');
        $("#edit_User .user-name").text('Add User');

        $('input[type=text]').each(function() {            
            $(this).val('');           
        });

        $('input[type=checkbox][name=project]').each(function() {            
            $(this).prop('checked', false);           
        }); 

        $('#edit_User .btnSaveStaff').data('id', '');
    });

     /* When click show user */
    // $(document).on("click", ".btnSaveCategory", function() {
    $(document).on('click', '#pm_staff_settings .fa-edit', function () {
        var user_id = $(this).data('id');
        // var user_id = $(this).closest('td').data('id');
        $('#edit_User .btnSaveStaff').data('id', user_id);
        // console.log('[user_id: '+user_id+'] Clicked!');

        $('input[type=checkbox][name=project]').each(function() {            
            $(this).prop('checked', false);           
        });      

        $.ajax({
            headers : {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },            
            url     : APP_URL + '/admin/users/show/'+user_id,
            type    : 'GET',           
            data: {
                // 'type'              : 'category',                
            },
            success: function(data) {                
                console.log('Get User Data Success! '+user_id);                      

                if(data.status == "success"){
                    // alert(data.status);
                    var detail      = data.details;
                    var user_role   = data.user_role;
                    var arr_res     = new Array();

                    if(data.projects['residential_id'] != "") {
                        arr_res = data.projects['residential_id'].split(',');
                        
                        $('input[type=checkbox][name=project]').each(function() {
                            var cur_val = $(this).val();
                            if(arr_res.includes(cur_val)){
                                $(this).prop('checked', true);
                            }
                        });
                    }                                       

                    // console.log('user-role: ' + user_role.role_id);
                    // console.log('user-status: ' + detail.status);

                    $("#edit_User .user-name").text(detail.name);
                    $("#edit_User .user-name").val(detail.name);
                    $("#edit_User #user-contact").val(detail.tel);
                    $("#edit_User #user-email").val(detail.email);
                    $("#edit_User #user-role").val(user_role.role_id);
                    $("#edit_User #user-status").val(detail.status);

                    $('.selectpicker').selectpicker('refresh');

                }else{
                    printErrorMsg(data.msg);
                    
                }
             
            },
        });
    });

    $(document).on('click', '#edit_User .btnSaveStaff', function() {
        var user_id = $('#edit_User .btnSaveStaff').data('id');        
        console.log('[.btnSaveStaff] [user_id: '+user_id+'] Clicked!');
        
        var name		= $("#edit_User #user-name").val();
        var tel			= $("#edit_User #user-contact").val();
        var email		= $("#edit_User #user-email").val();
        var role		= $("#edit_User #user-role").val();
        var status		= $("#edit_User #user-status").val(); 
        var vendor		= $("#edit_User #user-vendor").val(); 
        var pass		= $("#edit_User #user-pass").val(); 
        var confirm_pass= $("#edit_User #user-confirm-pass").val(); 
        var project = [];

        $("input:checkbox[name=project]:checked").each(function(){
            project.push($(this).val());
        });

        var formData = {
			'action'		: "update_user",
            'name'			: name,
            'tel'			: tel,
            'email'			: email,
            'role'			: role,
            'status'		: status,
            'project'			: project,
            'vendor'			: vendor,
            'password'			: pass,
            'confirm_password'  : confirm_pass,
		};

        var ajaxURL = APP_URL + '/admin/users/update/'+user_id;
        var method  = 'POST';

        if(user_id == "undefined" || user_id == "") {
            ajaxURL = APP_URL + '/admin/users/store';
            method  = 'PUT';
        }

        // console.log('[ajaxURL]' + ajaxURL);

        $.ajax({
            headers : {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },           
            url     : ajaxURL,
            type    : method,
            data    : formData,
            success : function(data) {
                if(data.status == "success"){
                    // alert(data.status);
					// $("#SuccessPopup p").html("<strong>Success</strong><br>Data has been saved.");
					// $('#SuccessPopup').modal(); 
					
					var msg = "<strong>Success</strong><br>Data has been saved.";
					SuccessPopup(msg);
                    $("#pm_staff_settings").remove();					
                    ListTable();

                }else{
					// $("#AlertPopup p").html();
					// $('#AlertPopup').modal();
                    // console.log(data.msg);
					var msg = "<strong>ERROR</strong><br>"+ data.msg;
					AlertPopup(msg);
                }
             
            },
        });
    });

    function ListTable() {
        $("#pm_staff_settings").remove();

        var date	= new Date();
		var month 	= date.getMonth() + 1;
			month 	= (month < 10) ? '0'+month : month;
		var today	= date.getFullYear() + month + date.getDay();
        var tableName = "pm_staff_settings";
        var row = '';
		row += '<table id="'+tableName+'" class="table table-bordered mt-15 table_pm_staff_settings table-hover" data-category="0">';
		row += '<thead>';
		row += '<tr>';
		row += '<th>#</th>';
		row += '<th class="excelExport">Name</th>';		
		row += '<th class="excelExport">Email</th>';
		row += '<th class="excelExport">Contact</th>';
		row += '<th class="excelExport">Role</th>';
		row += '<th class="excelExport">Project</th>';		
		row += '<th class="excelExport">Status</th>';		
		row += '<th style="width:6%">Action</th>';
		row += '</tr>';
		row += '</thead>';
		row += '<tbody>';
		row += '</tbody>';
		row += '</table>';
		$('#ListTable').html(row);

        var formData = {
			'action'	: "listing",			
		};
        
        var user_table = $('#pm_staff_settings').DataTable({
            processing  : true,
            serverSide  : true,
            dom		    : 'lBfrtip',
            ajax        : {
				headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                url: APP_URL + '/admin/users/list',
				type: "post",  
				data: formData,
				error: function(){  
					console.log("error");
				}
			}, 
            columnDefs: [				
				{
					"targets"	: [0,2,3,4,5,6,7],
					"className"	: "text-center",
				},               
			],
            buttons: [
				{
					text: "<i class='fa fa-download' style='vertical-align:middle;'></i> <label style='margin:5px;'>Export</label>",
					extend: 'excelHtml5',
                    exportOptions: {
						columns: '.excelExport'
					},
					filename: 'Trade_List_'+today,
					title: '',
					className: 'btn-export',
					action: function (e, dt, button, config) {
						var that = this;
						if(confirm("Do you want to export trade listing to Excel file?")) {
							console.log('COnfirm == OK');
							that.processing(true);
							that.disable();
							setTimeout(function () {
								console.log('[excelHtml5]button',button);
								$.fn.dataTable.ext.buttons.excelHtml5.action.call(that, e, dt, button, config);
								
							}, 500);
							that.enable();
						} else {
							console.log('Confirm == Cancel');
						}
					}
				},
			],			           
            columns: [                
                { "data": null,"sortable": false, 
                    render: function (data, type, row, meta) {
                                return meta.row + meta.settings._iDisplayStart + 1;
                    }  
                },
                { data: 'name', name: 'name' },                  
                { data: 'email', name: 'email' },                  
                { data: 'tel', name: 'tel' },                  
                { data: 'role', name: 'role' },                  
                { data: 'project', name: 'project' },                  
                { data: 'status', name: 'status' },                  
                { data: 'action', name: 'action'},
            ],
            order: [[1, 'asc']],
            createdRow : function(row, data, index) {
                // console.log('row: ', row);
                // console.log('- - - [index: '+ index + '] data: ', data);

                if(data.status == "Active") {
                    $('td', row).eq(6).addClass('active');
                } else {
                    $('td', row).eq(6).addClass('inactive');
                }
            }
        });         
       
    }
});